GitHub Repository Size Checker (Excluding .git)

Displays the total size of files in a GitHub repository (excluding .git directory) next to the repo name.

当前为 2025-04-13 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name GitHub Repository Size Checker (Excluding .git)
  3. // @version 1.0
  4. // @description Displays the total size of files in a GitHub repository (excluding .git directory) next to the repo name.
  5. // @author John Gray
  6. // @match *://github.com/*/*
  7. // @exclude *://github.com/*/issues*
  8. // @exclude *://github.com/*/pulls*
  9. // @exclude *://github.com/*/actions*
  10. // @exclude *://github.com/*/projects*
  11. // @exclude *://github.com/*/wiki*
  12. // @exclude *://github.com/*/security*
  13. // @exclude *://github.com/*/pulse*
  14. // @exclude *://github.com/*/settings*
  15. // @exclude *://github.com/*/branches*
  16. // @exclude *://github.com/*/tags*
  17. // @exclude *://github.com/*/*/commit*
  18. // @exclude *://github.com/*/*/tree*
  19. // @exclude *://github.com/*/*/blob*
  20. // @exclude *://github.com/settings*
  21. // @exclude *://github.com/notifications*
  22. // @exclude *://github.com/marketplace*
  23. // @exclude *://github.com/explore*
  24. // @exclude *://github.com/topics*
  25. // @exclude *://github.com/sponsors*
  26. // @exclude *://github.com/dashboard*
  27. // @exclude *://github.com/new*
  28. // @exclude *://github.com/codespaces*
  29. // @exclude *://github.com/account*
  30. // @grant GM_setValue
  31. // @grant GM_getValue
  32. // @grant GM_xmlhttpRequest
  33. // @grant GM_registerMenuCommand
  34. // @connect api.github.com
  35. // @license MIT
  36. // @namespace https://gf.qytechs.cn/users/1342408
  37. // ==/UserScript==
  38.  
  39. (function() {
  40. 'use strict';
  41.  
  42. const CACHE_KEY = 'repoSizeCache';
  43. const PAT_KEY = 'github_pat_repo_size';
  44. const CACHE_EXPIRY_MS = 24 * 60 * 60 * 1000; // 24 hours
  45.  
  46. // --- Configuration ---
  47. const GITHUB_API_BASE = 'https://api.github.com';
  48. // Target element selector (this might change if GitHub updates its layout)
  49. const TARGET_ELEMENT_SELECTOR = '#repo-title-component > span.Label.Label--secondary'; // The 'Public'/'Private' label
  50. const DISPLAY_ELEMENT_ID = 'repo-size-checker-display';
  51.  
  52. // --- Styles ---
  53. const STYLE_LOADING = 'color: orange; margin-left: 6px; font-size: 12px; font-weight: 600;';
  54. const STYLE_ERROR = 'color: red; margin-left: 6px; font-size: 12px; font-weight: 600;';
  55. const STYLE_SIZE = 'color: #6a737d; margin-left: 6px; font-size: 12px; font-weight: 600;'; // Use GitHub's secondary text color
  56.  
  57. let currentRepoInfo = null; // { owner, repo, key: 'owner/repo' }
  58. let pat = null;
  59. let displayElement = null;
  60. let observer = null; // MutationObserver to watch for page changes
  61.  
  62. // --- Helper Functions ---
  63.  
  64. function log(...args) {
  65. console.log('[RepoSizeChecker]', ...args);
  66. }
  67.  
  68. function getRepoInfoFromUrl() {
  69. const match = window.location.pathname.match(/^\/([^/]+)\/([^/]+)(?:\/?$|\/tree\/|\/find\/|\/graphs\/|\/network\/|\/releases\/)/);
  70. if (match && match[1] && match[2]) {
  71. // Basic check to avoid non-code pages that might match the pattern
  72. if (document.querySelector('#repository-container-header')) {
  73. return { owner: match[1], repo: match[2], key: `${match[1]}/${match[2]}` };
  74. }
  75. }
  76. return null;
  77. }
  78.  
  79. function formatBytes(bytes, decimals = 1) {
  80. if (bytes === 0) return '0 Bytes';
  81. const k = 1024;
  82. const dm = decimals < 0 ? 0 : decimals;
  83. const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
  84. const i = Math.floor(Math.log(bytes) / Math.log(k));
  85. return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
  86. }
  87.  
  88. function getPAT() {
  89. if (pat) return pat;
  90. pat = GM_getValue(PAT_KEY, null);
  91. return pat;
  92. }
  93.  
  94. function setPAT(newPat) {
  95. if (newPat && typeof newPat === 'string' && newPat.trim().length > 0) {
  96. pat = newPat.trim();
  97. GM_setValue(PAT_KEY, pat);
  98. log('GitHub PAT saved.');
  99. // Clear current error message if any
  100. if (displayElement && displayElement.textContent?.includes('PAT Required')) {
  101. updateDisplay('', STYLE_LOADING); // Reset display
  102. }
  103. // Re-run the main logic if PAT was missing
  104. main();
  105. return true;
  106. } else {
  107. GM_setValue(PAT_KEY, ''); // Clear stored PAT if input is invalid/empty
  108. pat = null;
  109. log('Invalid PAT input. PAT cleared.');
  110. updateDisplay('Invalid PAT', STYLE_ERROR);
  111. return false;
  112. }
  113. }
  114.  
  115. function promptForPAT() {
  116. const newPat = prompt('GitHub Personal Access Token (PAT) required for API access. Please enter your PAT (needs repo scope):\n\nIt will be stored locally by Tampermonkey.', '');
  117. if (newPat === null) { // User cancelled
  118. updateDisplay('PAT Required', STYLE_ERROR);
  119. return false;
  120. }
  121. return setPAT(newPat);
  122. }
  123.  
  124. function getCache() {
  125. const cacheStr = GM_getValue(CACHE_KEY, '{}');
  126. try {
  127. return JSON.parse(cacheStr);
  128. } catch (e) {
  129. log('Error parsing cache, resetting.', e);
  130. GM_setValue(CACHE_KEY, '{}');
  131. return {};
  132. }
  133. }
  134.  
  135. function setCache(repoKey, data) {
  136. try {
  137. const cache = getCache();
  138. cache[repoKey] = data;
  139. GM_setValue(CACHE_KEY, JSON.stringify(cache));
  140. } catch (e) {
  141. log('Error writing cache', e);
  142. }
  143. }
  144.  
  145. function updateDisplay(text, style = STYLE_SIZE, isLoading = false) {
  146. if (!displayElement) {
  147. const targetElement = document.querySelector(TARGET_ELEMENT_SELECTOR);
  148. if (!targetElement) {
  149. log('Target element not found.');
  150. return; // Target element isn't on the page yet or selector is wrong
  151. }
  152. displayElement = document.createElement('span');
  153. displayElement.id = DISPLAY_ELEMENT_ID;
  154. targetElement.insertAdjacentElement('afterend', displayElement);
  155. log('Display element injected.');
  156. }
  157.  
  158. displayElement.textContent = isLoading ? `(${text}...)` : text;
  159. displayElement.style.cssText = style;
  160. }
  161.  
  162. function makeApiRequest(url, method = 'GET') {
  163. return new Promise((resolve, reject) => {
  164. const currentPat = getPAT();
  165. if (!currentPat) {
  166. reject(new Error('PAT Required'));
  167. return;
  168. }
  169.  
  170. GM_xmlhttpRequest({
  171. method: method,
  172. url: url,
  173. headers: {
  174. "Authorization": `token ${currentPat}`,
  175. "Accept": "application/vnd.github.v3+json"
  176. },
  177. onload: function(response) {
  178. if (response.status >= 200 && response.status < 300) {
  179. try {
  180. resolve(JSON.parse(response.responseText));
  181. } catch (e) {
  182. reject(new Error(`Failed to parse API response: ${e.message}`));
  183. }
  184. } else if (response.status === 401) {
  185. reject(new Error('Invalid PAT'));
  186. } else if (response.status === 403) {
  187. const rateLimitRemaining = response.responseHeaders.match(/x-ratelimit-remaining:\s*(\d+)/i);
  188. const rateLimitReset = response.responseHeaders.match(/x-ratelimit-reset:\s*(\d+)/i);
  189. let errorMsg = 'API rate limit exceeded or insufficient permissions.';
  190. if (rateLimitRemaining && rateLimitRemaining[1] === '0' && rateLimitReset) {
  191. const resetTime = new Date(parseInt(rateLimitReset[1], 10) * 1000);
  192. errorMsg += ` Limit resets at ${resetTime.toLocaleTimeString()}.`;
  193. } else {
  194. errorMsg += ' Check PAT permissions (needs `repo` scope).';
  195. }
  196. reject(new Error(errorMsg));
  197. } else if (response.status === 404) {
  198. reject(new Error('Repository not found or PAT lacks access.'));
  199. }
  200. else {
  201. reject(new Error(`API request failed with status ${response.status}: ${response.statusText}`));
  202. }
  203. },
  204. onerror: function(response) {
  205. reject(new Error(`Network error during API request: ${response.error || 'Unknown error'}`));
  206. },
  207. ontimeout: function() {
  208. reject(new Error('API request timed out.'));
  209. }
  210. });
  211. });
  212. }
  213.  
  214. async function fetchLatestDefaultBranchSha(owner, repo) {
  215. log(`Fetching repo info for ${owner}/${repo}`);
  216. const repoUrl = `${GITHUB_API_BASE}/repos/${owner}/${repo}`;
  217. try {
  218. const repoData = await makeApiRequest(repoUrl);
  219. const defaultBranch = repoData.default_branch;
  220. if (!defaultBranch) {
  221. throw new Error('Could not determine default branch.');
  222. }
  223. log(`Default branch: ${defaultBranch}. Fetching its latest SHA.`);
  224. const branchUrl = `${GITHUB_API_BASE}/repos/${owner}/${repo}/branches/${defaultBranch}`;
  225. const branchData = await makeApiRequest(branchUrl);
  226. return branchData.commit.sha;
  227. } catch (error) {
  228. log(`Error fetching latest SHA for ${owner}/${repo}:`, error);
  229. throw error; // Re-throw to be caught by the main logic
  230. }
  231. }
  232.  
  233. async function fetchRepoTreeSize(owner, repo, sha) {
  234. log(`Fetching tree size for ${owner}/${repo} at SHA ${sha}`);
  235. const treeUrl = `${GITHUB_API_BASE}/repos/${owner}/${repo}/git/trees/${sha}?recursive=1`;
  236. try {
  237. const treeData = await makeApiRequest(treeUrl);
  238.  
  239. if (treeData.truncated && (!treeData.tree || treeData.tree.length === 0)) {
  240. // Handle extremely large repos where even the first page is truncated without file list
  241. throw new Error('Repo likely too large for basic tree API. Size unavailable.');
  242. }
  243.  
  244. let totalSize = 0;
  245. if (treeData.tree) {
  246. treeData.tree.forEach(item => {
  247. if (item.type === 'blob' && item.size !== undefined && item.size !== null) {
  248. totalSize += item.size;
  249. }
  250. });
  251. }
  252.  
  253. log(`Calculated size for ${owner}/${repo} (SHA: ${sha}): ${totalSize} bytes. Truncated: ${treeData.truncated}`);
  254. return {
  255. size: totalSize,
  256. truncated: treeData.truncated === true // Ensure boolean
  257. };
  258. } catch (error) {
  259. log(`Error fetching tree size for ${owner}/${repo}:`, error);
  260. // Special handling for empty repos which return 404 for the tree SHA
  261. if (error.message && error.message.includes('404') && error.message.includes('Not Found')) {
  262. log(`Assuming empty repository for ${owner}/${repo} based on 404 for tree SHA ${sha}.`);
  263. return { size: 0, truncated: false };
  264. }
  265. throw error; // Re-throw other errors
  266. }
  267. }
  268.  
  269. async function main() {
  270. const repoInfo = getRepoInfoFromUrl();
  271.  
  272. // Exit if not on a repo page or already processed this exact URL path
  273. if (!repoInfo || (currentRepoInfo && currentRepoInfo.key === repoInfo.key && currentRepoInfo.path === window.location.pathname)) {
  274. // log('Not a repo page or already processed:', window.location.pathname);
  275. return;
  276. }
  277.  
  278. currentRepoInfo = { ...repoInfo, path: window.location.pathname }; // Store owner, repo, key, and full path
  279. log('Detected repository:', currentRepoInfo.key);
  280.  
  281. // Ensure display element exists or create it
  282. updateDisplay('loading', STYLE_LOADING, true);
  283.  
  284. // Check for PAT
  285. if (!getPAT()) {
  286. log('PAT not found.');
  287. updateDisplay('PAT Required', STYLE_ERROR);
  288. promptForPAT(); // Ask user for PAT
  289. // If promptForPAT fails or is cancelled, the display remains 'PAT Required'
  290. return; // Stop processing until PAT is provided
  291. }
  292.  
  293. // --- Caching Logic ---
  294. const cache = getCache();
  295. const cachedData = cache[currentRepoInfo.key];
  296. const now = Date.now();
  297.  
  298. if (cachedData) {
  299. const cacheAge = now - (cachedData.timestamp || 0);
  300. log(`Cache found for ${currentRepoInfo.key}: Age ${Math.round(cacheAge / 1000)}s, SHA ${cachedData.sha}`);
  301.  
  302. // 1. Check if cache is fresh (less than 24 hours)
  303. if (cacheAge < CACHE_EXPIRY_MS) {
  304. log('Cache is fresh (<24h). Using cached size.');
  305. updateDisplay(
  306. `${cachedData.truncated ? '~' : ''}${formatBytes(cachedData.size)}`,
  307. STYLE_SIZE
  308. );
  309. return; // Use fresh cache
  310. }
  311.  
  312. // 2. Cache is older than 24 hours, check if SHA matches current default branch head
  313. log('Cache is stale (>24h). Checking latest SHA...');
  314. updateDisplay('validating', STYLE_LOADING, true);
  315. try {
  316. const latestSha = await fetchLatestDefaultBranchSha(currentRepoInfo.owner, currentRepoInfo.repo);
  317. log(`Latest SHA: ${latestSha}, Cached SHA: ${cachedData.sha}`);
  318.  
  319. if (latestSha === cachedData.sha) {
  320. log('SHA matches. Reusing cached size and updating timestamp.');
  321. // Update timestamp in cache
  322. cachedData.timestamp = now;
  323. setCache(currentRepoInfo.key, cachedData);
  324. updateDisplay(
  325. `${cachedData.truncated ? '~' : ''}${formatBytes(cachedData.size)}`,
  326. STYLE_SIZE
  327. );
  328. return; // Use validated cache
  329. } else {
  330. log('SHA mismatch. Cache invalid. Fetching new size.');
  331. }
  332. } catch (error) {
  333. log('Error validating SHA:', error);
  334. updateDisplay(`Error: ${error.message}`, STYLE_ERROR);
  335. // Optionally clear the stale cache entry if validation fails badly?
  336. // delete cache[currentRepoInfo.key];
  337. // GM_setValue(CACHE_KEY, JSON.stringify(cache));
  338. return; // Stop if we can't validate
  339. }
  340. } else {
  341. log(`No cache found for ${currentRepoInfo.key}.`);
  342. }
  343.  
  344. // --- Fetching New Data ---
  345. updateDisplay('loading', STYLE_LOADING, true);
  346. try {
  347. // We might have already fetched the SHA during cache validation
  348. let latestSha = cachedData?.latestShaChecked; // Reuse if available from failed validation
  349. if (!latestSha) {
  350. latestSha = await fetchLatestDefaultBranchSha(currentRepoInfo.owner, currentRepoInfo.repo);
  351. }
  352.  
  353. const { size, truncated } = await fetchRepoTreeSize(currentRepoInfo.owner, currentRepoInfo.repo, latestSha);
  354.  
  355. // Save to cache
  356. const newData = {
  357. size: size,
  358. sha: latestSha,
  359. timestamp: Date.now(),
  360. truncated: truncated
  361. };
  362. setCache(currentRepoInfo.key, newData);
  363.  
  364. // Display result
  365. updateDisplay(
  366. `${truncated ? '~' : ''}${formatBytes(size)}`,
  367. STYLE_SIZE
  368. );
  369.  
  370. } catch (error) {
  371. log('Error during main fetch process:', error);
  372. let errorMsg = `Error: ${error.message}`;
  373. if (error.message === 'Invalid PAT') {
  374. errorMsg = 'Invalid PAT';
  375. setPAT(''); // Clear invalid PAT
  376. promptForPAT(); // Ask again
  377. } else if (error.message === 'PAT Required') {
  378. errorMsg = 'PAT Required';
  379. promptForPAT();
  380. }
  381. updateDisplay(errorMsg, STYLE_ERROR);
  382. }
  383. }
  384.  
  385. // --- Initialization ---
  386.  
  387. function init() {
  388. log("Script initializing...");
  389.  
  390. // Register menu command to update PAT
  391. GM_registerMenuCommand('Set/Update GitHub PAT for Repo Size', () => {
  392. const currentPatValue = GM_getValue(PAT_KEY, '');
  393. const newPat = prompt('Enter your GitHub Personal Access Token (PAT) for Repo Size Checker (needs repo scope):', currentPatValue);
  394. if (newPat !== null) { // Handle cancel vs empty string
  395. setPAT(newPat); // Validate and save
  396. }
  397. });
  398.  
  399. // Use MutationObserver to detect navigation changes within GitHub (SPA behavior)
  400. // and when the target element appears after load.
  401. observer = new MutationObserver((mutationsList, observer) => {
  402. // Check if the repo title area is present, indicating a potential repo page load/update
  403. if (document.querySelector(TARGET_ELEMENT_SELECTOR) && !document.getElementById(DISPLAY_ELEMENT_ID)) {
  404. // If the display element isn't there but the target is, try running main
  405. log("Target element detected, running main logic.");
  406. main();
  407. } else {
  408. // Also check if the URL path changed significantly enough to warrant a re-check
  409. const newRepoInfo = getRepoInfoFromUrl();
  410. if (newRepoInfo && (!currentRepoInfo || newRepoInfo.key !== currentRepoInfo.key)) {
  411. log("Detected navigation to a new repository page.", newRepoInfo.key);
  412. main();
  413. } else if (!newRepoInfo && currentRepoInfo) {
  414. // Navigated away from a repo page where we were showing info
  415. log("Navigated away from repo page.");
  416. currentRepoInfo = null; // Reset state
  417. if (displayElement) {
  418. displayElement.remove(); // Clean up old display element
  419. displayElement = null;
  420. }
  421. }
  422. }
  423. });
  424.  
  425. // Start observing the body for changes in subtree and child list
  426. observer.observe(document.body, { childList: true, subtree: true });
  427.  
  428. // Initial run in case the page is already loaded
  429. main();
  430. }
  431.  
  432.  
  433. // Make sure the DOM is ready before trying to find elements
  434. if (document.readyState === 'loading') {
  435. document.addEventListener('DOMContentLoaded', init);
  436. } else {
  437. init();
  438. }
  439.  
  440. })();

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址