Download github repo sub-folder

download github sub-folder via one click, copy the single file's source code easily

  1. // ==UserScript==
  2. // @name Download github repo sub-folder
  3. // @name:zh-CN 在线下载Github仓库文件夹
  4. // @description download github sub-folder via one click, copy the single file's source code easily
  5. // @description:zh-CN 无需克隆GitHub仓库, 一键在线下载 Github仓库子文件夹; 同时还能在源码详情页一键复制源码
  6. // @version 0.7.2
  7. // @author Saiya
  8. // @supportURL https://github.com/oe/download-git-userscript/issues
  9. // @match https://github.com/*
  10. // @match https://gist.github.com/*
  11. // @connect cdn.jsdelivr.net
  12. // @grant GM_setClipboard
  13. // @grant GM_xmlhttpRequest
  14. // @homepageURL https://github.com/oe/download-git-userscript
  15. // @icon https://github.githubassets.com/pinned-octocat.svg
  16. // @namespace https://app.evecalm.com
  17. // @noframes
  18. // ==/UserScript==
  19.  
  20. /******/ (() => { // webpackBootstrap
  21. /******/ "use strict";
  22. /******/ var __webpack_modules__ = ({
  23.  
  24. /***/ 607:
  25. /***/ (function(__unused_webpack_module, exports, __webpack_require__) {
  26.  
  27.  
  28. var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
  29. if (k2 === undefined) k2 = k;
  30. var desc = Object.getOwnPropertyDescriptor(m, k);
  31. if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
  32. desc = { enumerable: true, get: function() { return m[k]; } };
  33. }
  34. Object.defineProperty(o, k2, desc);
  35. }) : (function(o, m, k, k2) {
  36. if (k2 === undefined) k2 = k;
  37. o[k2] = m[k];
  38. }));
  39. var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
  40. Object.defineProperty(o, "default", { enumerable: true, value: v });
  41. }) : function(o, v) {
  42. o["default"] = v;
  43. });
  44. var __importStar = (this && this.__importStar) || function (mod) {
  45. if (mod && mod.__esModule) return mod;
  46. var result = {};
  47. if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
  48. __setModuleDefault(result, mod);
  49. return result;
  50. };
  51. Object.defineProperty(exports, "__esModule", ({ value: true }));
  52. const utils = __importStar(__webpack_require__(593));
  53. (function () {
  54. const DOWNLOAD_BTN_ID = 'xiu-download-btn';
  55. const STYLE_ELEMENT_ID = 'xiu-style-element';
  56. let tid = 0;
  57. main();
  58. // observe body change
  59. const observer = new MutationObserver(onBodyChanged);
  60. observer.observe(document, { subtree: true, childList: true });
  61. function main() {
  62. if (!utils.isRepo())
  63. return;
  64. addDownloadBtn();
  65. addDownload2FileList();
  66. }
  67. function onBodyChanged() {
  68. // debounce, avoid frequent call
  69. clearTimeout(tid);
  70. // @ts-ignore
  71. tid = setTimeout(main, 100);
  72. }
  73. function addDownloadBtn() {
  74. let $navi = utils.isRepoRootDir() && document.querySelector('#branch-picker-repos-header-ref-selector');
  75. if ($navi) {
  76. $navi = $navi.parentElement.parentElement.nextElementSibling;
  77. }
  78. else {
  79. $navi = document.querySelector('#StickyHeader .js-github-dev-new-tab-shortcut');
  80. if (!$navi) {
  81. $navi = document.querySelector('[data-testid="tree-overflow-menu-anchor"]');
  82. if (!$navi)
  83. return;
  84. }
  85. $navi = $navi.parentElement;
  86. }
  87. if (!$navi)
  88. return;
  89. const downloadBtn = getDownloadBtn();
  90. if (!downloadBtn || $navi.contains(downloadBtn))
  91. return;
  92. $navi.appendChild(downloadBtn);
  93. }
  94. function getDownloadBtn() {
  95. let downloadBtn = document.getElementById(DOWNLOAD_BTN_ID);
  96. if (!downloadBtn) {
  97. downloadBtn = document.createElement('a');
  98. downloadBtn.id = DOWNLOAD_BTN_ID;
  99. }
  100. const isRoot = utils.isRepoRootDir();
  101. downloadBtn.className = `btn d-none d-md-block ${isRoot ? 'ml-0' : ''}`;
  102. downloadBtn.target = '_blank';
  103. let url = '';
  104. if (isRoot) {
  105. try {
  106. // @ts-ignore
  107. const repoInfo = JSON.parse(document.querySelector('[partial-name="repos-overview"] [data-target="react-partial.embeddedData"]').innerText);
  108. const zipUrl = repoInfo.props.initialPayload.overview.codeButton.local.platformInfo.zipballUrl;
  109. url = new URL(zipUrl, location.href).href;
  110. }
  111. catch (error) {
  112. console.warn('unable to get zip url', error);
  113. return;
  114. }
  115. }
  116. else {
  117. url = utils.getGithubDownloadUrl(utils.getCurrentUrlPath());
  118. }
  119. downloadBtn.textContent = 'Download';
  120. downloadBtn.href = url;
  121. return downloadBtn;
  122. }
  123. function addDownload2FileList() {
  124. if (document.getElementById(STYLE_ELEMENT_ID))
  125. return;
  126. const style = document.createElement('style');
  127. style.id = STYLE_ELEMENT_ID;
  128. const styleContent = `
  129. .react-directory-filename-column { position: relative; }
  130. .react-directory-filename-column:has(a[aria-label*="File"]):after,
  131. .react-directory-filename-column:has(a[aria-label*="Directory"]):after,
  132. .Box .Box-row > [role="gridcell"]:first-child:after {
  133. position: absolute;
  134. left: 20px;
  135. top: 10px;
  136. opacity: 0.6;
  137. pointer-events: none;
  138. content: '↓';
  139. font-size: 0.8em;
  140. z-index: 11;
  141. }
  142.  
  143. .react-directory-filename-column:has(a[aria-label*="File"]):after,
  144. .react-directory-filename-column:has(a[aria-label*="Directory"]):after{
  145. left: 4px;
  146. top: 12px;
  147. color: white;
  148. }
  149.  
  150.  
  151. [data-color-mode="light"] .react-directory-filename-column:after {
  152. color: black;
  153. }
  154. @media (prefers-color-scheme: light) {
  155. [data-color-mode=auto][data-light-theme*=light] .react-directory-filename-column:after {
  156. color: black;
  157. }
  158. }
  159.  
  160. .react-directory-filename-column:has(a[aria-label*="File"]) svg,
  161. .react-directory-filename-column:has(a[aria-label*="Directory"]) svg{
  162. cursor: pointer;
  163. }
  164. `;
  165. style.textContent = styleContent;
  166. document.head.appendChild(style);
  167. addEvent2FileIcon();
  168. }
  169. function addEvent2FileIcon() {
  170. document.documentElement.addEventListener('click', (e) => {
  171. var _a, _b, _c, _d, _e, _f, _g;
  172. // @ts-ignore
  173. const target = (e.target && e.target.ownerSVGElement || e.target);
  174. if (!target || (target.tagName || '').toLowerCase() !== 'svg')
  175. return;
  176. const label = target.getAttribute('aria-label') || '';
  177. let url = '';
  178. let isFile = false;
  179. if (['Directory', 'File'].includes(label)) {
  180. url = (_d = (_c = (_b = (_a = target.parentElement) === null || _a === void 0 ? void 0 : _a.nextElementSibling) === null || _b === void 0 ? void 0 : _b.querySelector) === null || _c === void 0 ? void 0 : _c.call(_b, 'a')) === null || _d === void 0 ? void 0 : _d.href;
  181. isFile = label === 'File';
  182. }
  183. else if ((_e = target.parentElement) === null || _e === void 0 ? void 0 : _e.classList.contains('react-directory-filename-column')) {
  184. const anchor = (_g = (_f = target.nextElementSibling) === null || _f === void 0 ? void 0 : _f.querySelector) === null || _g === void 0 ? void 0 : _g.call(_f, 'a');
  185. if (!anchor)
  186. return;
  187. const label = anchor.getAttribute('aria-label') || '';
  188. if (!label.includes('Directory') && !label.includes('File'))
  189. return;
  190. url = anchor.href;
  191. console.warn("url", url);
  192. isFile = target.classList.contains('color-fg-muted');
  193. }
  194. else {
  195. return;
  196. }
  197. if (!url)
  198. return;
  199. utils.openLink(utils.getGithubDownloadUrl(url, isFile));
  200. }, {
  201. capture: true,
  202. passive: true,
  203. });
  204. }
  205. })();
  206.  
  207.  
  208. /***/ }),
  209.  
  210. /***/ 593:
  211. /***/ ((__unused_webpack_module, exports) => {
  212.  
  213.  
  214. Object.defineProperty(exports, "__esModule", ({ value: true }));
  215. exports.getGithubDownloadUrl = exports.openLink = exports.getCurrentUrlPath = exports.getRawBtn = exports.getUrlTextResponse = exports.isTextBasedSinglePage = exports.isRepoRootDir = exports.isPrivateRepo = exports.isRepo = exports.isGist = void 0;
  216. /**
  217. * is gist website
  218. */
  219. function isGist() {
  220. return location.hostname === 'gist.github.com';
  221. }
  222. exports.isGist = isGist;
  223. function isRepo() {
  224. if (!document.querySelector('.repository-content, #js-repo-pjax-container'))
  225. return false;
  226. const meta = document.querySelector('meta[name="selected-link"]');
  227. if (meta && meta.getAttribute('value') === 'repo_commits')
  228. return false;
  229. if (document.querySelector('.js-navigation-container>.TimelineItem'))
  230. return false;
  231. return true;
  232. }
  233. exports.isRepo = isRepo;
  234. function isPrivateRepo() {
  235. const label = document.querySelector('#js-repo-pjax-container .hide-full-screen .Label');
  236. return label && label.textContent === 'Private';
  237. }
  238. exports.isPrivateRepo = isPrivateRepo;
  239. function isRepoRootDir() {
  240. return !!document.querySelector('.repository-content [partial-name="repos-overview"]');
  241. }
  242. exports.isRepoRootDir = isRepoRootDir;
  243. function isTextBasedSinglePage() {
  244. if (!getRawBtn())
  245. return;
  246. if (document.getElementById('readme'))
  247. return true;
  248. const boxBody = document.querySelector('table.highlight');
  249. if (boxBody)
  250. return true;
  251. return false;
  252. }
  253. exports.isTextBasedSinglePage = isTextBasedSinglePage;
  254. function getUrlTextResponse(url) {
  255. // https://github.com/oe/search/raw/gh-pages/app-icon-retina.f492fc13.png
  256. // https://cdn.jsdelivr.net/gh/oe/search@gh-pages/app-icon-retina.f492fc13.png
  257. // https://github.com/oe/search/raw/master/CNAME
  258. let apiUrl = url
  259. .replace('github.com/', 'cdn.jsdelivr.net/gh/')
  260. .replace('/raw/', '@');
  261. return new Promise((resolve, reject) => {
  262. // @ts-ignore
  263. GM_xmlhttpRequest({
  264. url: apiUrl,
  265. method: 'GET',
  266. onload: (s) => {
  267. resolve(s.responseText);
  268. }
  269. });
  270. });
  271. }
  272. exports.getUrlTextResponse = getUrlTextResponse;
  273. // if is single file page, then it has a raw btn
  274. function getRawBtn() {
  275. return document.getElementById('raw-url');
  276. }
  277. exports.getRawBtn = getRawBtn;
  278. // remove qeurystring & hash
  279. function getCurrentUrlPath() {
  280. const url = location.origin + location.pathname;
  281. return url.replace(/\/$/, '');
  282. }
  283. exports.getCurrentUrlPath = getCurrentUrlPath;
  284. function openLink(url) {
  285. const link = document.createElement('a');
  286. link.target = '_blank';
  287. link.href = url;
  288. link.click();
  289. }
  290. exports.openLink = openLink;
  291. function getGithubDownloadUrl(url, isFile) {
  292. if (isFile) {
  293. try {
  294. const u = new URL(url);
  295. let paths = u.pathname.split('/');
  296. paths[3] = 'raw';
  297. u.pathname = paths.join('/');
  298. return u.href;
  299. }
  300. catch (error) { }
  301. }
  302. return `https://downgit.evecalm.com/#/home?url=${encodeURIComponent(url)}`;
  303. }
  304. exports.getGithubDownloadUrl = getGithubDownloadUrl;
  305.  
  306.  
  307. /***/ })
  308.  
  309. /******/ });
  310. /************************************************************************/
  311. /******/ // The module cache
  312. /******/ var __webpack_module_cache__ = {};
  313. /******/
  314. /******/ // The require function
  315. /******/ function __webpack_require__(moduleId) {
  316. /******/ // Check if module is in cache
  317. /******/ var cachedModule = __webpack_module_cache__[moduleId];
  318. /******/ if (cachedModule !== undefined) {
  319. /******/ return cachedModule.exports;
  320. /******/ }
  321. /******/ // Create a new module (and put it into the cache)
  322. /******/ var module = __webpack_module_cache__[moduleId] = {
  323. /******/ // no module.id needed
  324. /******/ // no module.loaded needed
  325. /******/ exports: {}
  326. /******/ };
  327. /******/
  328. /******/ // Execute the module function
  329. /******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  330. /******/
  331. /******/ // Return the exports of the module
  332. /******/ return module.exports;
  333. /******/ }
  334. /******/
  335. /************************************************************************/
  336. /******/
  337. /******/ // startup
  338. /******/ // Load entry module and return exports
  339. /******/ // This entry module is referenced by other modules so it can't be inlined
  340. /******/ var __webpack_exports__ = __webpack_require__(607);
  341. /******/
  342. /******/ })()
  343. ;