GitHub Repository Size Checker

Displays the repo size in GitHub (without .git).

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

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

QingJ © 2025

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