Github 仓库大小

在 github 搜索和存储库页面上的存储库名称旁边添加存储库大小

当前为 2024-09-09 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Github Repo Size+
  3. // @name:zh-CN Github 仓库大小
  4. // @description:zh-CN 在 github 搜索和存储库页面上的存储库名称旁边添加存储库大小
  5. // @name:ar Github حجم المستودع
  6. // @description:ar يخرج github أضف حجم المستودع بجوار اسم المستودع في صفحات البحث والمستودع
  7. // @name:bg Github Размер на склада
  8. // @description:bg съществуват github Добавете размер на хранилището до името на хранилището на страниците за търсене и хранилище
  9. // @name:cs Github Velikost skladu
  10. // @description:cs existovat github Přidejte velikost úložiště vedle názvu úložiště na stránkách vyhledávání a úložiště
  11. // @name:da Github Lagerstørrelse
  12. // @description:da eksistere github Tilføj lagerstørrelse ud for lagernavn på søge- og lagersider
  13. // @name:de Github Lagergröße
  14. // @description:de existieren github Fügen Sie auf Such- und Repository-Seiten neben dem Repository-Namen die Repository-Größe hinzu
  15. // @name:el Github Μέγεθος αποθήκης
  16. // @description:el υπάρχω github Προσθέστε μέγεθος αποθετηρίου δίπλα στο όνομα χώρου αποθήκευσης στις σελίδες αναζήτησης και αποθετηρίου
  17. // @name:en Github Warehouse size
  18. // @description:en exist github Add repository size next to repository name on search and repository pages
  19. // @name:eo Github Grando de magazeno
  20. // @description:eo ekzisti github Aldonu deponejan grandecon apud la nomo de deponejo sur serĉo kaj deponejo paĝoj
  21. // @name:es Github Tamaño del almacén
  22. // @description:es existir github Agregue el tamaño del repositorio junto al nombre del repositorio en las páginas de búsqueda y repositorio
  23. // @name:fi Github Varaston koko
  24. // @description:fi olemassa github Lisää arkiston koko arkiston nimen viereen haku- ja arkistosivuilla
  25. // @name:fr Github Taille de l’entrepôt
  26. // @description:fr exister github Ajouter la taille du référentiel à côté du nom du référentiel sur les pages de recherche et du référentiel
  27. // @name:he Github גודל המחסן
  28. // @description:he לְהִתְקַיֵם github הוסף גודל מאגר ליד שם המאגר בדפי החיפוש והמאגר
  29. // @name:hr Github Veličina skladišta
  30. // @description:hr postojati github Dodajte veličinu repozitorija pored naziva repozitorija na stranicama pretraživanja i repozitorija
  31. // @name:hu Github Raktár mérete
  32. // @description:hu létezik github Adja hozzá a lerakat méretét a lerakat neve mellett a keresési és lerakatoldalakon
  33. // @name:id Github Ukuran gudang
  34. // @description:id ada github Tambahkan ukuran repositori di sebelah nama repositori pada halaman pencarian dan repositori
  35. // @name:it Github Dimensioni del magazzino
  36. // @description:it esistere github Aggiungi la dimensione del repository accanto al nome del repository nelle pagine di ricerca e del repository
  37. // @name:ja Github 倉庫のサイズ
  38. // @description:ja 存在する github 検索ページとリポジトリ ページでリポジトリ名の横にリポジトリ サイズを追加します
  39. // @name:ka Github საწყობის ზომა
  40. // @description:ka არსებობს github საძიებო და საცავის გვერდებზე საცავის სახელის გვერდით დაამატეთ საცავის ზომა
  41. // @name:ko Github 창고 규모
  42. // @description:ko 존재하다 github 검색 및 저장소 페이지의 저장소 이름 옆에 저장소 크기 추가
  43. // @name:nl Github Grootte van magazijn
  44. // @description:nl bestaan github Voeg de repositorygrootte toe naast de repositorynaam op zoek- en repositorypagina’s
  45. // @name:nb Github Lagerstørrelse
  46. // @description:nb eksistere github Legg til depotstørrelse ved siden av depotnavnet på søke- og depotsidene
  47. // @name:pl Github Wielkość magazynu
  48. // @description:pl istnieć github Dodaj rozmiar repozytorium obok nazwy repozytorium na stronach wyszukiwania i repozytorium
  49. // @name:pt-BR Github Tamanho do armazém
  50. // @description:pt-BR existir github Adicione o tamanho do repositório próximo ao nome do repositório nas páginas de pesquisa e do repositório
  51. // @name:ro Github Dimensiunea depozitului
  52. // @description:ro exista github Adăugați dimensiunea depozitului lângă numele depozitului pe paginile de căutare și depozit
  53. // @name:ru Github Размер склада
  54. // @description:ru существовать github Добавьте размер репозитория рядом с именем репозитория на страницах поиска и репозитория.
  55. // @name:sk Github Veľkosť skladu
  56. // @description:sk existujú github Pridajte veľkosť úložiska vedľa názvu úložiska na stránkach vyhľadávania a úložiska
  57. // @name:sr Github Величина магацина
  58. // @description:sr постоје github Додајте величину спремишта поред имена спремишта на страницама претраге и спремишта
  59. // @name:sv Github Lagerstorlek
  60. // @description:sv existera github Lägg till förvarsstorlek bredvid förvarets namn på sök- och förvarssidor
  61. // @name:th Github ขนาดคลังสินค้า
  62. // @description:th มีอยู่ github เพิ่มขนาดที่เก็บถัดจากชื่อที่เก็บในหน้าการค้นหาและที่เก็บ
  63. // @name:tr Github Depo boyutu
  64. // @description:tr var olmak github Arama ve depo sayfalarında depo adının yanına depo boyutunu ekleyin
  65. // @name:ug Github ئامبارنىڭ چوڭلۇقى
  66. // @description:ug مەۋجۇت github ئىزدەش ۋە ئامبار بېتىدىكى ئامبار نامىنىڭ يېنىغا ئامبار چوڭلۇقى قوشۇڭ
  67. // @name:uk Github Розмір складу
  68. // @description:uk існують github Додайте розмір сховища поруч із назвою сховища на сторінках пошуку та сховища
  69. // @name:vi Github Kích thước kho
  70. // @description:vi hiện hữu github Thêm kích thước kho lưu trữ bên cạnh tên kho lưu trữ trên các trang tìm kiếm và kho lưu trữ
  71. // @name:zh-TW Github 倉庫大小
  72. // @description:zh-TW 在 github 搜尋和儲存庫頁面上的儲存庫名稱旁邊新增儲存庫大小
  73. // @name:zh-HK Github 倉庫大小
  74. // @description:zh-HK 在 github 搜尋和儲存庫頁面上的儲存庫名稱旁邊新增儲存庫大小
  75. // @name:fr-CA Github Taille de l’entrepôt
  76. // @description:fr-CA exister github Ajouter la taille du référentiel à côté du nom du référentiel sur les pages de recherche et du référentiel
  77. // @namespace https://github.com/qinwuyuan-cn
  78. // @description Adds the repo size next to the repo name on github search and repo pages
  79. // @version 0.1.2.53
  80. // @author mshll & 人民的勤务员 <toniaiwanowskiskr47@gmail.com>
  81. // @match *://github.com/search*
  82. // @match *://github.com/*/*
  83. // @match *://github.com/*?tab=repositories*
  84. // @grant none
  85. // @grant GM_getValue
  86. // @grant GM_setValue
  87. // @grant GM_addStyle
  88. // @grant GM_registerMenuCommand
  89. // @grant none
  90. // @icon https://github.githubassets.com/pinned-octocat.svg
  91. // @license MIT
  92. // @source https://github.com/qinwuyuan-cn/UserScripts
  93. // @supportURL https://github.com/ChinaGodMan/UserScripts/issues
  94. // @homepageURL https://github.com/ChinaGodMan/UserScripts
  95. // ==/UserScript==
  96. "use strict"
  97. //! Generate a new public access token from https://github.com/settings/tokens and insert it here
  98. //*Note: to be able to see the size of your private repos, you need to select the `repo` scope when generating the token
  99. let TOKEN = GM_getValue('githubToken', "")
  100. GM_addStyle(`
  101. .modal-overlay{position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.5);display:flex;justify-content:center;align-items:center;z-index:1000;}
  102. .modal-content{background:white;padding:20px;border-radius:8px;width:400px;box-shadow:0 4px 15px rgba(0,0,0,0.2);position:relative;}
  103. .modal-title{margin:0 0 10px 0;font-size:20px;}
  104. .modal-description{margin-bottom:20px;font-size:14px;color:#666;}
  105. .modal-description a{color:#007bff;text-decoration:underline;}
  106. #github-token-input{width:100%;padding:8px;border:1px solid #ccc;border-radius:4px;margin-bottom:20px;font-size:14px;}
  107. #save-token{background-color:#28a745;color:white;border:none;padding:10px 20px;cursor:pointer;border-radius:4px;margin-right:10px;}
  108. #cancel-token{background-color:#dc3545;color:white;border:none;padding:10px 20px;cursor:pointer;border-radius:4px;}
  109. `)
  110. function createModal() {
  111. const modalHTML = `
  112. <div class="modal-overlay">
  113. <div class="modal-content">
  114. <h2 class="modal-title">Set GitHub Token</h2>
  115. <p class="modal-description">
  116. Enter your GitHub personal access token with "repo" scope.
  117. <a href="https://github.com/settings/tokens/new?description=GitHub%20Repo%20Size%20UserScript&scopes=repo" target="_blank" rel="noopener noreferrer">
  118. Click here to create a new token
  119. </a>
  120. </p>
  121. <input type="text" id="github-token-input" placeholder="Enter your GitHub personal access token">
  122. <button id="save-token">Save</button>
  123. <button id="cancel-token" class="cancel">Cancel</button>
  124. </div>
  125. </div>
  126. `
  127. const modalContainer = document.createElement('div')
  128. modalContainer.innerHTML = modalHTML
  129. document.body.appendChild(modalContainer)
  130. const input = document.getElementById('github-token-input')
  131. input.value = GM_getValue('githubToken', '')
  132. document.getElementById('save-token').addEventListener('click', () => {
  133. const token = input.value.trim()
  134. if (token) {
  135. GM_setValue('githubToken', token)
  136. modalContainer.remove()
  137. TOKEN = token
  138. }
  139. })
  140. document.getElementById('cancel-token').addEventListener('click', () => modalContainer.remove())
  141. }
  142. GM_registerMenuCommand('Set GitHub Token', function () {
  143. createModal()
  144. })
  145. const getPageType = () => {
  146. const { pathname, search } = window.location
  147. const params = new URLSearchParams(search)
  148. const [, username, repo] = pathname.split("/")
  149. const q = params.get("q")?.toLocaleLowerCase()
  150. const type = params.get("type")?.toLocaleLowerCase()
  151. if (window.location.pathname.split('/').pop() === "repositories") return "list-view-container"
  152. if (window.location.href.includes("?tab=repositories")) return "user-repositories"
  153. if (username && repo) return "repo"
  154. if (q && type === "code") return "code_search"
  155. if (q) return "search"
  156. }
  157. const addSizeToRepos = () => {
  158. const pageType = getPageType()
  159. // Get the repo selector based on the page type
  160. let repoSelector
  161. switch (pageType) {
  162. case "repo"://仓库详情界面
  163. repoSelector = "#repository-container-header strong a"
  164. break
  165. case "list-view-container"://ORG下的仓库列表
  166. repoSelector = 'div[data-testid="list-view-item-title-container"] h4 a'
  167. break
  168. case "user-repositories"://用户资料页面的仓库TAB
  169. repoSelector = '#user-repositories-list h3 a'
  170. break
  171. case "search"://搜索
  172. repoSelector = 'div[data-testid="results-list"] .search-title a'
  173. break
  174. case "code_search"://代码搜索
  175. repoSelector = 'div[data-testid="results-list"] .search-title a'
  176. break
  177. default:
  178. return
  179. }
  180. function extractPath(input) {
  181. const thirdSlashIndex = input.indexOf('/', input.indexOf('/', input.indexOf('/') + 1) + 1)
  182. if (thirdSlashIndex !== -1) {
  183. return input.substring(0, thirdSlashIndex)
  184. }
  185. return input
  186. }
  187. // Get all the repo links
  188. document.querySelectorAll(repoSelector).forEach(async (elem) => {
  189. // Get json data from github api to extract the size
  190. const tkn = TOKEN
  191. var href = elem.getAttribute("href")
  192. href = extractPath(href)
  193. console.log(href)
  194. const headers = tkn ? { authorization: `token ${tkn}` } : {}
  195. const jsn = await (
  196. await fetch(`https://api.github.com/repos${href}`, {
  197. headers: headers,
  198. })
  199. ).json()
  200. // If JSON failed to load, skip
  201. if (jsn.message) return
  202. // Get parent element to append the size to
  203. let parent = elem.parentElement
  204. if (pageType === "repo") {
  205. parent = elem.parentElement.parentElement
  206. }
  207. // Create the size container
  208. let sizeContainer = parent.querySelector(`#mshll-repo-size`)
  209. if (sizeContainer === null) {
  210. sizeContainer = document.createElement("span")
  211. sizeContainer.id = "mshll-repo-size"
  212. sizeContainer.classList.add("Label", "Label--info", "v-align-middle", "ml-1")
  213. sizeContainer.setAttribute("title", "Repository size")
  214. sizeContainer.innerText = "-"
  215. // Create the size icon
  216. let sizeSVG = document.createElementNS("http://www.w3.org/2000/svg", "svg")
  217. sizeSVG.setAttribute("aria-hidden", "true")
  218. sizeSVG.setAttribute("viewBox", "-4 -4 22 22")
  219. sizeSVG.setAttribute("width", "16")
  220. sizeSVG.setAttribute("height", "16")
  221. sizeSVG.setAttribute("fill", "currentColor")
  222. sizeSVG.setAttribute("data-view-component", "true")
  223. sizeSVG.classList.add("octicon", "octicon-file-directory", "mr-1")
  224. let sizeSVGPath = document.createElementNS("http://www.w3.org/2000/svg", "path")
  225. sizeSVGPath.setAttribute("fill-rule", "evenodd")
  226. sizeSVGPath.setAttribute("d", "M1 3.5c0-.626.292-1.165.7-1.59.406-.422.956-.767 1.579-1.041C4.525.32 6.195 0 8 0c1.805 0 3.475.32 4.722.869.622.274 1.172.62 1.578 1.04.408.426.7.965.7 1.591v9c0 .626-.292 1.165-.7 1.59-.406.422-.956.767-1.579 1.041C11.476 15.68 9.806 16 8 16c-1.805 0-3.475-.32-4.721-.869-.623-.274-1.173-.62-1.579-1.04-.408-.426-.7-.965-.7-1.591Zm1.5 0c0 .133.058.318.282.551.227.237.591.483 1.101.707C4.898 5.205 6.353 5.5 8 5.5c1.646 0 3.101-.295 4.118-.742.508-.224.873-.471 1.1-.708.224-.232.282-.417.282-.55 0-.133-.058-.318-.282-.551-.227-.237-.591-.483-1.101-.707C11.102 1.795 9.647 1.5 8 1.5c-1.646 0-3.101.295-4.118.742-.508.224-.873.471-1.1.708-.224.232-.282.417-.282.55Zm0 4.5c0 .133.058.318.282.551.227.237.591.483 1.101.707C4.898 9.705 6.353 10 8 10c1.646 0 3.101-.295 4.118-.742.508-.224.873-.471 1.1-.708.224-.232.282-.417.282-.55V5.724c-.241.15-.503.286-.778.407C11.475 6.68 9.805 7 8 7c-1.805 0-3.475-.32-4.721-.869a6.15 6.15 0 0 1-.779-.407Zm0 2.225V12.5c0 .133.058.318.282.55.227.237.592.484 1.1.708 1.016.447 2.471.742 4.118.742 1.647 0 3.102-.295 4.117-.742.51-.224.874-.47 1.101-.707.224-.233.282-.418.282-.551v-2.275c-.241.15-.503.285-.778.406-1.247.549-2.917.869-4.722.869-1.805 0-3.475-.32-4.721-.869a6.327 6.327 0 0 1-.779-.406Z")
  227. sizeSVG.appendChild(sizeSVGPath)
  228. // Convert the size to human readable
  229. const sizes = ["B", "KB", "MB", "GB", "TB"]
  230. const size = jsn.size * 1024 // Github API returns size in KB so convert to bytes
  231. let i = parseInt(Math.floor(Math.log(size) / Math.log(1024)))
  232. const humanReadableSize = (size / Math.pow(1024, i)).toFixed(1) + " " + sizes[i]
  233. // Insert the size into the size container
  234. sizeContainer.innerHTML = `${humanReadableSize}`
  235. sizeContainer.prepend(sizeSVG)
  236. // Insert the size container into the DOM
  237. if (pageType === "code_search") {
  238. parent.style.direction = 'ltr'
  239. }
  240. parent.appendChild(sizeContainer)
  241. }
  242. })
  243. }
  244. window.addSizeToRepos = addSizeToRepos
  245. // Add the size to the repos on the page
  246. //addSizeToRepos()
  247. window.onload = function () {
  248. addSizeToRepos()
  249. }
  250. // Watch for URL changes
  251. let lastUrl = location.href
  252. new MutationObserver(() => {
  253. const url = location.href
  254. if (url !== lastUrl) {
  255. lastUrl = url
  256. setTimeout(function () {
  257. //NOTE - 此处增加延时了,就这样得了
  258. addSizeToRepos()
  259. }, 1500)
  260. }
  261. }).observe(document, { subtree: true, childList: true })