Repository navigation
Expand file tree
/
Copy pathgitlines.js
More file actions
441 lines (398 loc) · 19.6 KB
/
Copy pathgitlines.js
File metadata and controls
441 lines (398 loc) · 19.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
// GitLines content script: counts lines of code of the current GitHub repo
// and renders a donut chart into the repository sidebar.
const API = "https://api.github.com";
const RAW = "application/vnd.github.raw+json";
const CACHE_KEY = "gitlinesCache";
const CACHE_MAX_ENTRIES = 30;
// File extension (lowercase, without dot) -> language
const LANGUAGES = {
py: ["Python", "#3572A5"],
js: ["JavaScript", "#f1e05a"], mjs: ["JavaScript", "#f1e05a"], cjs: ["JavaScript", "#f1e05a"], jsx: ["JavaScript", "#f1e05a"],
ts: ["TypeScript", "#3178c6"], tsx: ["TypeScript", "#3178c6"],
html: ["HTML", "#e34c26"], htm: ["HTML", "#e34c26"],
css: ["CSS", "#663399"], scss: ["SCSS", "#c6538c"], sass: ["Sass", "#a53b70"], less: ["Less", "#1d365d"],
vue: ["Vue", "#41b883"], svelte: ["Svelte", "#ff3e00"],
java: ["Java", "#b07219"],
cpp: ["C++", "#f34b7d"], cc: ["C++", "#f34b7d"], cxx: ["C++", "#f34b7d"], hpp: ["C++", "#f34b7d"], hh: ["C++", "#f34b7d"],
c: ["C", "#555555"], h: ["C Header", "#555555"],
cs: ["C#", "#178600"],
php: ["PHP", "#4F5D95"],
rb: ["Ruby", "#701516"],
go: ["Go", "#00ADD8"],
rs: ["Rust", "#dea584"],
swift: ["Swift", "#F05138"],
kt: ["Kotlin", "#A97BFF"], kts: ["Kotlin", "#A97BFF"],
r: ["R", "#198CE7"],
pl: ["Perl", "#0298c3"],
sh: ["Shell", "#89e051"], bash: ["Shell", "#89e051"], zsh: ["Shell", "#89e051"],
bat: ["Batchfile", "#C1F12E"], cmd: ["Batchfile", "#C1F12E"],
ps1: ["PowerShell", "#012456"],
lua: ["Lua", "#000080"],
hs: ["Haskell", "#5e5086"],
scala: ["Scala", "#c22d40"],
dart: ["Dart", "#00B4AB"],
m: ["Objective-C", "#438eff"], mm: ["Objective-C++", "#6866fb"],
jl: ["Julia", "#a270ba"],
sql: ["SQL", "#e38c00"],
yaml: ["YAML", "#cb171e"], yml: ["YAML", "#cb171e"],
json: ["JSON", "#292929"],
xml: ["XML", "#0060ac"],
tex: ["TeX", "#3D6117"],
ipynb: ["Jupyter Notebook", "#DA5B0B"],
gradle: ["Gradle", "#02303a"],
vb: ["Visual Basic", "#945db7"],
groovy: ["Groovy", "#4298b8"],
erl: ["Erlang", "#B83998"],
ex: ["Elixir", "#6e4a7e"], exs: ["Elixir", "#6e4a7e"],
clj: ["Clojure", "#db5855"],
coffee: ["CoffeeScript", "#244776"],
f90: ["Fortran", "#4d41b1"],
zig: ["Zig", "#ec915c"]
};
// Files without a usable extension, matched by lowercase file name
const FILENAMES = {
dockerfile: ["Dockerfile", "#384d54"],
makefile: ["Makefile", "#427819"]
};
// Generated / third-party code that would only inflate the numbers
const SKIPPED = /(^|\/)(node_modules|bower_components|vendor|dist)\/|\.min\.(js|css)$|(^|\/)package-lock\.json$/i;
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
const esc = s => String(s).replace(/[&<>"']/g, c => `&#${c.charCodeAt(0)};`);
const encodePath = p => p.split("/").map(encodeURIComponent).join("/");
function countLines(text) {
if (!text) return 0;
return text.split("\n").length - (text.endsWith("\n") ? 1 : 0);
}
function detectLanguage(path) {
const name = path.slice(path.lastIndexOf("/") + 1).toLowerCase();
if (FILENAMES[name]) return FILENAMES[name];
const dot = name.lastIndexOf(".");
return dot > 0 ? LANGUAGES[name.slice(dot + 1)] : undefined;
}
class ApiError extends Error {
constructor(message, fatal) {
super(message);
this.fatal = fatal;
}
}
function makeClient(token) {
return async function gh(path, accept = "application/vnd.github+json", attempt = 0) {
let res;
try {
res = await fetch(API + path, {
headers: { Authorization: `Bearer ${token}`, Accept: accept }
});
} catch (err) {
if (attempt < 2) {
await delay(1000 * (attempt + 1));
return gh(path, accept, attempt + 1);
}
throw new ApiError(`Network error: ${err.message}`, true);
}
if (res.ok) return res;
const limited = res.status === 403 || res.status === 429;
if (limited && res.headers.get("x-ratelimit-remaining") === "0") {
const reset = new Date(Number(res.headers.get("x-ratelimit-reset")) * 1000);
throw new ApiError(`GitHub API rate limit reached. It resets at ${reset.toLocaleTimeString()}.`, true);
}
// Secondary rate limits and server hiccups are worth a retry
if ((limited || res.status >= 500) && attempt < 2) {
await delay((Number(res.headers.get("retry-after")) || attempt + 1) * 1000);
return gh(path, accept, attempt + 1);
}
if (res.status === 401) {
throw new ApiError("GitHub rejected your API token (401). Please check it in the GitLines popup.", true);
}
throw new ApiError(`GitHub API request failed (${res.status}).`, res.status !== 404);
};
}
async function getBranches(gh, owner, repo, selection) {
const base = `/repos/${owner}/${repo}`;
if (selection.toLowerCase() === "all") {
const branches = [];
// ponytail: capped at 1000 branches, add a setting if anyone needs more
for (let page = 1; page <= 10; page++) {
const batch = await (await gh(`${base}/branches?per_page=100&page=${page}`)).json();
branches.push(...batch);
if (batch.length < 100) break;
}
return branches.map(b => ({ name: b.name, sha: b.commit.sha }));
}
const info = await (await gh(base)).json();
for (const name of [selection, info.default_branch]) {
if (!name) continue;
try {
const b = await (await gh(`${base}/branches/${encodePath(name)}`)).json();
return [{ name: b.name, sha: b.commit.sha }];
} catch (err) {
if (err.fatal) throw err;
}
}
return [];
}
async function readCache(key) {
try {
const { [CACHE_KEY]: cache = {} } = await browser.storage.local.get(CACHE_KEY);
return cache[key];
} catch {
return undefined;
}
}
async function writeCache(key, value) {
try {
const { [CACHE_KEY]: cache = {} } = await browser.storage.local.get(CACHE_KEY);
cache[key] = { ...value, ts: Date.now() };
const keys = Object.keys(cache).sort((a, b) => cache[b].ts - cache[a].ts);
keys.slice(CACHE_MAX_ENTRIES).forEach(k => delete cache[k]);
await browser.storage.local.set({ [CACHE_KEY]: cache });
} catch (err) {
console.warn("GitLines: could not write cache", err);
}
}
// ---------- UI ----------
function ensureStyles() {
if (document.getElementById("gitlines-style")) return;
const style = document.createElement("style");
style.id = "gitlines-style";
style.textContent = `
.gitlines-row .gl-muted { color: var(--fgColor-muted, #59636e); font-size: 12px; }
.gitlines-row .gl-box { padding: 8px 12px; border-radius: 6px; border: 1px solid var(--borderColor-default, #d1d9e0); font-size: 13px; }
.gitlines-row .gl-box.gl-error { border-color: var(--borderColor-danger-emphasis, #cf222e); }
.gitlines-row .gl-box a { color: var(--fgColor-accent, #0969da); }
.gitlines-row .gl-bar { height: 8px; border-radius: 6px; overflow: hidden; background: var(--bgColor-neutral-muted, #818b981f); margin-top: 6px; }
.gitlines-row .gl-bar > span { display: block; height: 100%; width: 0; background: var(--bgColor-success-emphasis, #1f883d); transition: width .2s; }
.gitlines-row .gl-chart { display: flex; align-items: center; gap: 16px; }
.gitlines-row .gl-chart svg { flex: none; }
.gitlines-row .gl-seg { transition: stroke-width .15s; }
.gitlines-row .gl-hit { stroke-opacity: 0.01; cursor: pointer; }
.gitlines-row ul { list-style: none; margin: 0; padding: 0; min-width: 0; }
.gitlines-row li { margin-bottom: 4px; font-size: 12px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.gitlines-row li a { color: inherit; text-decoration: none; }
.gitlines-row li a:hover .gl-lang { color: var(--fgColor-accent, #0969da); }
.gitlines-row .gl-dot { display: inline-block; width: 8px; height: 8px; border-radius: 50%; margin-right: 6px; }
.gitlines-row .gl-lang { font-weight: 600; margin-right: 4px; color: var(--fgColor-default, #1f2328); }
#gitlines-tooltip { position: fixed; display: none; pointer-events: none; padding: 6px 8px; border-radius: 6px;
font-size: 12px; background: rgba(10,10,10,.9); color: #fff; z-index: 9999; white-space: nowrap; }
`;
document.head.appendChild(style);
}
function getTooltip() {
let tip = document.getElementById("gitlines-tooltip");
if (!tip) {
tip = document.createElement("div");
tip.id = "gitlines-tooltip";
document.body.appendChild(tip);
}
return tip;
}
function chartHtml(result) {
const radius = 16, size = 44, c = size / 2;
const circumference = 2 * Math.PI * radius;
let cumulative = 0;
const segments = result.languages.map((l, i) => {
const fraction = l.lines / result.total;
const dash = `stroke-dasharray="${fraction * circumference} ${circumference}" stroke-dashoffset="${-cumulative * circumference}"`;
cumulative += fraction;
return {
seg: `<circle class="gl-seg" data-i="${i}" r="${radius}" cx="${c}" cy="${c}" fill="none" stroke="${l.color}" stroke-width="8" ${dash} transform="rotate(-90 ${c} ${c})"/>`,
hit: `<circle class="gl-hit" data-i="${i}" r="${radius}" cx="${c}" cy="${c}" fill="none" stroke="#000" stroke-width="12" ${dash} transform="rotate(-90 ${c} ${c})"/>`
};
});
const items = result.languages.map(l => `
<li><a href="${esc(l.link)}" target="_blank" rel="noopener" title="${esc(l.files)} files">
<span class="gl-dot" style="background:${l.color}"></span><span class="gl-lang">${esc(l.lang)}</span>
<span class="gl-muted">${l.lines.toLocaleString()} · ${(l.lines / result.total * 100).toFixed(1)}%</span>
</a></li>`).join("");
const notes = [];
if (result.truncated) notes.push("The repository is very large, GitHub only returned part of its file tree.");
if (result.failed) notes.push(`${result.failed.toLocaleString()} files could not be read and are not counted.`);
return `
<p class="gl-muted" style="margin:0 0 12px">
${result.total.toLocaleString()} lines in ${result.files.toLocaleString()} files · ${esc(result.branchLabel)}
</p>
<div class="gl-chart">
<svg width="100" height="100" viewBox="0 0 ${size} ${size}" role="img" aria-label="Lines of code by language">
<circle r="${radius}" cx="${c}" cy="${c}" fill="none" stroke="var(--borderColor-muted, #e1e4e8)" stroke-width="8"/>
${segments.map(s => s.seg).join("")}${segments.map(s => s.hit).join("")}
</svg>
<ul>${items}</ul>
</div>
${notes.map(n => `<p class="gl-muted" style="margin:8px 0 0">${esc(n)}</p>`).join("")}`;
}
function bindChart(body, result) {
const tip = getTooltip();
body.querySelectorAll(".gl-hit").forEach(hit => {
const lang = result.languages[hit.dataset.i];
const seg = body.querySelector(`.gl-seg[data-i="${hit.dataset.i}"]`);
const move = evt => {
tip.textContent = `${lang.lang} — ${lang.lines.toLocaleString()} lines`;
tip.style.display = "block";
const r = tip.getBoundingClientRect();
let left = evt.clientX + 12, top = evt.clientY + 12;
if (left + r.width > window.innerWidth) left = evt.clientX - r.width - 12;
if (top + r.height > window.innerHeight) top = evt.clientY - r.height - 12;
tip.style.left = `${left}px`;
tip.style.top = `${top}px`;
};
hit.addEventListener("mouseenter", evt => { seg.style.strokeWidth = "10"; move(evt); });
hit.addEventListener("mousemove", move);
hit.addEventListener("mouseleave", () => { seg.style.strokeWidth = "8"; tip.style.display = "none"; });
hit.addEventListener("click", () => window.open(lang.link, "_blank", "noopener"));
});
}
const MISSING_KEY_HTML = `
<div class="gl-box">
<strong>GitHub API token missing</strong>
<ol style="margin:6px 0 6px 18px; padding:0">
<li>Click the GitLines icon in your browser toolbar</li>
<li>Paste a GitHub personal access token</li>
<li>Save and reload this page</li>
</ol>
<a href="https://github.com/settings/tokens" target="_blank" rel="noopener">Create a token →</a>
<span class="gl-muted">(no scopes needed for public repos, <code>repo</code> for private ones)</span>
</div>`;
// ---------- main ----------
let current = null; // { row, path } of the analysis currently shown
function findSidebar() {
// Old server-rendered layout, then the React layout with hashed class names
return document.querySelector(".BorderGrid.about-margin")
|| document.querySelector('[class*="PageLayout-Pane"] [class*="borderGrid__"]');
}
function createRow(sidebar) {
const legacy = sidebar.classList.contains("BorderGrid");
const sibling = sidebar.lastElementChild;
const heading = sidebar.querySelector("h2");
const row = document.createElement("div");
row.className = `${legacy ? "BorderGrid-row" : (sibling?.className.replace(/\bHideWhenNarrow\S*/g, "") ?? "")} gitlines-row`;
row.innerHTML = `${legacy ? '<div class="BorderGrid-cell">' : "<div>"}
<h2 class="${esc(legacy ? "h4 mb-3" : heading?.className ?? "")}"><span>Lines of Code</span></h2>
<div class="gl-body"></div></div>`;
return row;
}
async function analyze(row, owner, repo) {
const body = row.querySelector(".gl-body");
const aborted = () => current?.row !== row;
const render = html => { if (!aborted()) body.innerHTML = html; };
const settings = await browser.storage.local.get(["apiKey", "enabled", "concurrentFiles", "branchSelection"]);
if (settings.enabled === false) {
row.hidden = true;
return;
}
const token = (settings.apiKey || "").trim();
if (!token) {
render(MISSING_KEY_HTML);
return;
}
const concurrency = Math.min(20, Math.max(1, parseInt(settings.concurrentFiles, 10) || 5));
const gh = makeClient(token);
render(`<p class="gl-muted" style="margin:0">Loading branches…</p>`);
try {
const branches = await getBranches(gh, owner, repo, (settings.branchSelection || "").trim());
if (!branches.length) {
render(`<p class="gl-muted" style="margin:0">This repository has no branches yet.</p>`);
return;
}
const branchLabel = branches.length === 1 ? `branch ${branches[0].name}` : `${branches.length} branches`;
const cacheKey = `${owner}/${repo}:${branches.map(b => b.sha).join(",")}`.toLowerCase();
let result = await readCache(cacheKey);
if (!result) {
// Collect supported files of all branches, deduplicated by content (blob sha)
const blobs = new Map();
let truncated = false;
for (const branch of branches) {
if (aborted()) return;
render(`<p class="gl-muted" style="margin:0">Reading file tree of ${esc(branch.name)}…</p>`);
const tree = await (await gh(`/repos/${owner}/${repo}/git/trees/${branch.sha}?recursive=1`)).json();
truncated ||= tree.truncated;
for (const item of tree.tree) {
if (item.type !== "blob" || item.mode === "120000" || blobs.has(item.sha) || SKIPPED.test(item.path)) continue;
const language = detectLanguage(item.path);
if (language) blobs.set(item.sha, { ...item, language, commit: branch.sha });
}
}
const files = [...blobs.values()];
render(`
<div class="gl-muted gl-progress-text">Analyzed 0 of ${files.length.toLocaleString()} files</div>
<div class="gl-bar"><span></span></div>`);
const progressText = body.querySelector(".gl-progress-text");
const progressBar = body.querySelector(".gl-bar > span");
// Worker pool: `concurrency` requests in flight at any time
let next = 0, done = 0, failed = 0, stop = null;
const worker = async () => {
while (next < files.length && !stop && !aborted()) {
const file = files[next++];
try {
const res = await gh(`/repos/${owner}/${repo}/git/blobs/${file.sha}`, RAW);
file.lines = countLines(await res.text());
} catch (err) {
if (err.fatal) { stop = err; return; }
failed++;
}
done++;
if (progressText?.isConnected) {
progressText.textContent = `Analyzed ${done.toLocaleString()} of ${files.length.toLocaleString()} files`;
progressBar.style.width = `${Math.floor(done / files.length * 100)}%`;
}
}
};
await Promise.all(Array.from({ length: concurrency }, worker));
if (stop) throw stop;
if (aborted()) return;
const byLang = new Map();
for (const f of files) {
if (!f.lines) continue;
const [lang, color] = f.language;
const entry = byLang.get(lang) || { lang, color, lines: 0, files: 0,
link: `https://github.com/${owner}/${repo}/blob/${f.commit}/${encodePath(f.path)}` };
entry.lines += f.lines;
entry.files++;
byLang.set(lang, entry);
}
const languages = [...byLang.values()].sort((a, b) => b.lines - a.lines);
result = {
languages,
total: languages.reduce((sum, l) => sum + l.lines, 0),
files: languages.reduce((sum, l) => sum + l.files, 0),
truncated, failed, branchLabel
};
// Only cache complete results, so failed files get another try next time
if (!failed) await writeCache(cacheKey, result);
}
if (!result.total) {
render(`<p class="gl-muted" style="margin:0">No supported code files found in ${esc(branchLabel)}.</p>`);
return;
}
render(chartHtml(result));
if (!aborted()) bindChart(body, result);
} catch (err) {
console.error("GitLines:", err);
render(`<div class="gl-box gl-error"><strong>Analysis failed</strong><br>${esc(err.message)}</div>`);
}
}
function update() {
const sidebar = findSidebar();
if (!sidebar) return;
const [, owner, repo] = location.pathname.split("/");
if (!owner || !repo) return;
const path = `${owner}/${repo}`;
if (current && current.path === path) {
// Same repo, the page just re-rendered: put our row back if it got dropped
if (!sidebar.contains(current.row)) sidebar.appendChild(current.row);
return;
}
sidebar.querySelectorAll(".gitlines-row").forEach(r => r.remove()); // stale copies from page snapshots
ensureStyles();
const row = createRow(sidebar);
sidebar.appendChild(row);
current = { row, path };
analyze(row, owner, repo).catch(err => console.error("GitLines:", err));
}
// GitHub navigates without full page loads (Turbo + React), so watch the DOM
// instead of running once.
let scheduled = false;
new MutationObserver(() => {
if (scheduled) return;
scheduled = true;
setTimeout(() => { scheduled = false; update(); }, 250);
}).observe(document.body, { childList: true, subtree: true });
update();