git-tm 0.4.1 → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -21
- package/README.md +176 -89
- package/package.json +40 -45
- package/src/cli.js +147 -235
- package/src/git.js +690 -213
- package/src/public/app.css +2628 -0
- package/src/public/index.html +78 -88
- package/src/public/js/compare.js +426 -0
- package/src/public/js/detail.js +269 -0
- package/src/public/js/diff.js +328 -0
- package/src/public/js/graph.js +110 -0
- package/src/public/js/history.js +386 -0
- package/src/public/js/insights.js +150 -0
- package/src/public/js/main.js +409 -0
- package/src/public/js/theme.js +5 -0
- package/src/public/js/ui.js +226 -0
- package/src/public/logo.svg +1 -0
- package/src/server.js +207 -103
- package/src/public/app.js +0 -960
- package/src/public/fonts/InterVariable.woff2 +0 -0
- package/src/public/images/logo.png +0 -0
- package/src/public/images/logo.svg +0 -9
- package/src/public/styles.css +0 -1259
package/src/git.js
CHANGED
|
@@ -1,213 +1,690 @@
|
|
|
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
|
-
if (
|
|
132
|
-
|
|
133
|
-
return
|
|
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
|
-
|
|
1
|
+
// Thin, dependency-free wrapper around the git CLI.
|
|
2
|
+
// Every command uses machine-readable output (NUL / record separators) so
|
|
3
|
+
// commit messages, file names and refs with odd characters parse correctly.
|
|
4
|
+
|
|
5
|
+
import { spawn } from "node:child_process";
|
|
6
|
+
import { createHash } from "node:crypto";
|
|
7
|
+
import { readFile, stat } from "node:fs/promises";
|
|
8
|
+
import path from "node:path";
|
|
9
|
+
|
|
10
|
+
export const WORKTREE = "WORKTREE";
|
|
11
|
+
|
|
12
|
+
const GLOBAL_ARGS = [
|
|
13
|
+
"--no-pager",
|
|
14
|
+
"-c", "core.quotepath=off",
|
|
15
|
+
"-c", "color.ui=false",
|
|
16
|
+
"-c", "log.showSignature=false",
|
|
17
|
+
];
|
|
18
|
+
|
|
19
|
+
const MB = 1024 * 1024;
|
|
20
|
+
const RS = "\x1e"; // record separator
|
|
21
|
+
const FS = "\x00"; // field separator
|
|
22
|
+
|
|
23
|
+
export class GitError extends Error {
|
|
24
|
+
constructor(message, status = 500) {
|
|
25
|
+
super(message);
|
|
26
|
+
this.status = status;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Run git and resolve with stdout (string, or Buffer when raw). */
|
|
31
|
+
export function git(cwd, args, { raw = false, input, maxBytes = 64 * MB, timeout = 60_000 } = {}) {
|
|
32
|
+
return new Promise((resolve, reject) => {
|
|
33
|
+
const child = spawn("git", [...GLOBAL_ARGS, ...args], {
|
|
34
|
+
cwd,
|
|
35
|
+
windowsHide: true,
|
|
36
|
+
env: {
|
|
37
|
+
...process.env,
|
|
38
|
+
GIT_TERMINAL_PROMPT: "0",
|
|
39
|
+
GIT_OPTIONAL_LOCKS: "0",
|
|
40
|
+
GIT_PAGER: "cat",
|
|
41
|
+
LC_ALL: "C",
|
|
42
|
+
},
|
|
43
|
+
});
|
|
44
|
+
const out = [];
|
|
45
|
+
const err = [];
|
|
46
|
+
let size = 0;
|
|
47
|
+
let truncated = false;
|
|
48
|
+
let timedOut = false;
|
|
49
|
+
const timer = setTimeout(() => {
|
|
50
|
+
timedOut = true;
|
|
51
|
+
child.kill();
|
|
52
|
+
}, timeout);
|
|
53
|
+
|
|
54
|
+
child.stdout.on("data", (chunk) => {
|
|
55
|
+
if (truncated) return;
|
|
56
|
+
size += chunk.length;
|
|
57
|
+
if (size > maxBytes) {
|
|
58
|
+
truncated = true;
|
|
59
|
+
out.push(chunk.subarray(0, chunk.length - (size - maxBytes)));
|
|
60
|
+
child.kill();
|
|
61
|
+
} else {
|
|
62
|
+
out.push(chunk);
|
|
63
|
+
}
|
|
64
|
+
});
|
|
65
|
+
child.stderr.on("data", (chunk) => err.push(chunk));
|
|
66
|
+
child.on("error", (e) => {
|
|
67
|
+
clearTimeout(timer);
|
|
68
|
+
reject(new GitError(e.code === "ENOENT" ? "git was not found in PATH" : e.message));
|
|
69
|
+
});
|
|
70
|
+
child.on("close", (code) => {
|
|
71
|
+
clearTimeout(timer);
|
|
72
|
+
if (timedOut) return reject(new GitError(`git ${args[0]} timed out`, 504));
|
|
73
|
+
const buf = Buffer.concat(out);
|
|
74
|
+
if (code !== 0 && !truncated) {
|
|
75
|
+
const msg = Buffer.concat(err).toString().trim().split("\n").pop() || `git ${args[0]} failed`;
|
|
76
|
+
return reject(new GitError(msg.replace(/^(fatal|error): /, ""), 400));
|
|
77
|
+
}
|
|
78
|
+
if (raw) return resolve(Object.assign(buf, { truncated }));
|
|
79
|
+
const text = buf.toString("utf8");
|
|
80
|
+
resolve(truncated ? Object.assign(new String(text), { truncated: true }) : text);
|
|
81
|
+
});
|
|
82
|
+
child.stdin.on("error", () => {});
|
|
83
|
+
child.stdin.end(input);
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const tryGit = (cwd, args, opts) => git(cwd, args, opts).catch(() => null);
|
|
88
|
+
|
|
89
|
+
// ---------------------------------------------------------------- validation
|
|
90
|
+
|
|
91
|
+
/** User supplied revision: never let it be parsed as an option. */
|
|
92
|
+
function checkRev(rev) {
|
|
93
|
+
if (typeof rev !== "string" || !rev || rev.length > 512 || rev.startsWith("-") || /[\s\x00-\x1f\x7f]/.test(rev)) {
|
|
94
|
+
throw new GitError(`Invalid revision: ${String(rev).slice(0, 80)}`, 400);
|
|
95
|
+
}
|
|
96
|
+
return rev;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function checkPath(p) {
|
|
100
|
+
if (typeof p !== "string" || p.length > 4096 || p.includes("\0")) throw new GitError("Invalid path", 400);
|
|
101
|
+
return p.replace(/^\/+/, "");
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// ---------------------------------------------------------------- repository
|
|
105
|
+
|
|
106
|
+
export async function openRepo(dir) {
|
|
107
|
+
const inside = await tryGit(dir, ["rev-parse", "--is-bare-repository", "--absolute-git-dir"]);
|
|
108
|
+
if (inside === null) throw new GitError(`Not a git repository: ${dir}`, 400);
|
|
109
|
+
const [bare, gitDir] = inside.trim().split("\n");
|
|
110
|
+
const isBare = bare === "true";
|
|
111
|
+
const root = isBare ? gitDir : (await git(dir, ["rev-parse", "--show-toplevel"])).trim();
|
|
112
|
+
const emptyTree = (await git(root, ["hash-object", "-t", "tree", "--stdin"], { input: "" })).trim();
|
|
113
|
+
return new Repo(path.resolve(root), path.resolve(gitDir), isBare, emptyTree);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** Small LRU for results keyed by immutable object ids. */
|
|
117
|
+
class Cache {
|
|
118
|
+
constructor(limit = 400) {
|
|
119
|
+
this.limit = limit;
|
|
120
|
+
this.map = new Map();
|
|
121
|
+
}
|
|
122
|
+
async get(key, fn) {
|
|
123
|
+
if (this.map.has(key)) {
|
|
124
|
+
const v = this.map.get(key);
|
|
125
|
+
this.map.delete(key);
|
|
126
|
+
this.map.set(key, v);
|
|
127
|
+
return v;
|
|
128
|
+
}
|
|
129
|
+
const pending = fn();
|
|
130
|
+
this.map.set(key, pending);
|
|
131
|
+
if (this.map.size > this.limit) this.map.delete(this.map.keys().next().value);
|
|
132
|
+
try {
|
|
133
|
+
return await pending;
|
|
134
|
+
} catch (e) {
|
|
135
|
+
this.map.delete(key);
|
|
136
|
+
throw e;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
const LOG_FORMAT = ["%H", "%P", "%an", "%ae", "%at", "%cn", "%ce", "%ct", "%D", "%s"].join("%x00") + "%x1e";
|
|
142
|
+
|
|
143
|
+
function parseLog(out) {
|
|
144
|
+
const commits = [];
|
|
145
|
+
for (const rec of out.split(RS)) {
|
|
146
|
+
const r = rec.replace(/^\n/, "");
|
|
147
|
+
if (!r) continue;
|
|
148
|
+
const [hash, parents, an, ae, at, cn, ce, ct, refs, subject] = r.split(FS);
|
|
149
|
+
if (!hash || hash.length < 40) continue;
|
|
150
|
+
commits.push({
|
|
151
|
+
hash,
|
|
152
|
+
parents: parents ? parents.split(" ") : [],
|
|
153
|
+
author: an,
|
|
154
|
+
email: ae,
|
|
155
|
+
date: Number(at),
|
|
156
|
+
committer: cn,
|
|
157
|
+
committerEmail: ce,
|
|
158
|
+
commitDate: Number(ct),
|
|
159
|
+
refs: parseDecorations(refs),
|
|
160
|
+
subject: subject ?? "",
|
|
161
|
+
});
|
|
162
|
+
}
|
|
163
|
+
return commits;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** Parse %D produced with --decorate=full, so local and remote branches are unambiguous. */
|
|
167
|
+
function parseDecorations(s) {
|
|
168
|
+
if (!s) return [];
|
|
169
|
+
const refs = [];
|
|
170
|
+
for (let part of s.split(", ")) {
|
|
171
|
+
part = part.trim();
|
|
172
|
+
let type = null;
|
|
173
|
+
if (part.startsWith("HEAD -> ")) {
|
|
174
|
+
part = part.slice(8);
|
|
175
|
+
type = "head";
|
|
176
|
+
} else if (part === "HEAD") {
|
|
177
|
+
refs.push({ type: "detached", name: "HEAD" });
|
|
178
|
+
continue;
|
|
179
|
+
} else if (part.startsWith("tag: ")) {
|
|
180
|
+
part = part.slice(5);
|
|
181
|
+
}
|
|
182
|
+
if (part.startsWith("refs/heads/")) refs.push({ type: type || "branch", name: part.slice(11) });
|
|
183
|
+
else if (part.startsWith("refs/remotes/") && !part.endsWith("/HEAD")) refs.push({ type: "remote", name: part.slice(13) });
|
|
184
|
+
else if (part.startsWith("refs/tags/")) refs.push({ type: "tag", name: part.slice(10) });
|
|
185
|
+
}
|
|
186
|
+
return refs;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/** Merge `git diff --raw -z` and `--numstat -z` output into one file list. */
|
|
190
|
+
function parseFileChanges(rawOut, numOut) {
|
|
191
|
+
const files = [];
|
|
192
|
+
const raw = rawOut.split(FS);
|
|
193
|
+
for (let i = 0; i < raw.length - 1; ) {
|
|
194
|
+
const meta = raw[i++];
|
|
195
|
+
if (!meta.startsWith(":")) continue;
|
|
196
|
+
const [oldMode, newMode, , , statusField = "M"] = meta.slice(1).split(" ");
|
|
197
|
+
const status = statusField[0];
|
|
198
|
+
const oldPath = raw[i++];
|
|
199
|
+
const newPath = status === "R" || status === "C" ? raw[i++] : oldPath;
|
|
200
|
+
files.push({
|
|
201
|
+
status,
|
|
202
|
+
similarity: statusField.length > 1 ? Number(statusField.slice(1)) : undefined,
|
|
203
|
+
path: newPath,
|
|
204
|
+
oldPath: oldPath !== newPath ? oldPath : undefined,
|
|
205
|
+
oldMode,
|
|
206
|
+
newMode,
|
|
207
|
+
additions: 0,
|
|
208
|
+
deletions: 0,
|
|
209
|
+
binary: false,
|
|
210
|
+
});
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
// numstat -z: "a\td\tpath\0", or for renames "a\td\t\0old\0new\0"
|
|
214
|
+
const byPath = new Map(files.map((f) => [f.path, f]));
|
|
215
|
+
const num = numOut.split(FS);
|
|
216
|
+
for (let i = 0; i < num.length - 1; ) {
|
|
217
|
+
const m = num[i++].match(/^(-|\d+)\t(-|\d+)\t([\s\S]*)$/);
|
|
218
|
+
if (!m) continue;
|
|
219
|
+
let p = m[3];
|
|
220
|
+
if (p === "") {
|
|
221
|
+
i++; // old path
|
|
222
|
+
p = num[i++];
|
|
223
|
+
}
|
|
224
|
+
const f = byPath.get(p);
|
|
225
|
+
if (!f) continue;
|
|
226
|
+
if (m[1] === "-") f.binary = true;
|
|
227
|
+
else {
|
|
228
|
+
f.additions = Number(m[1]);
|
|
229
|
+
f.deletions = Number(m[2]);
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
return files;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
function isBinary(buf) {
|
|
236
|
+
const n = Math.min(buf.length, 8000);
|
|
237
|
+
for (let i = 0; i < n; i++) if (buf[i] === 0) return true;
|
|
238
|
+
return false;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
class Repo {
|
|
242
|
+
constructor(root, gitDir, bare, emptyTree) {
|
|
243
|
+
this.root = root;
|
|
244
|
+
this.gitDir = gitDir;
|
|
245
|
+
this.bare = bare;
|
|
246
|
+
this.emptyTree = emptyTree;
|
|
247
|
+
this.name = path.basename(bare ? root.replace(/[\\/]\.git$/, "").replace(/\.git$/, "") : root);
|
|
248
|
+
this.cache = new Cache();
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
run(args, opts) {
|
|
252
|
+
return git(this.root, args, opts);
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/** Resolve any revision to a full commit id (or WORKTREE). */
|
|
256
|
+
async resolve(rev) {
|
|
257
|
+
if (rev === WORKTREE) {
|
|
258
|
+
if (this.bare) throw new GitError("Bare repositories have no working tree", 400);
|
|
259
|
+
return WORKTREE;
|
|
260
|
+
}
|
|
261
|
+
checkRev(rev);
|
|
262
|
+
const out = await tryGit(this.root, ["rev-parse", "--verify", "--quiet", `${rev}^{commit}`]);
|
|
263
|
+
if (out) return out.trim();
|
|
264
|
+
// Like `git checkout`: a branch that only exists on one remote resolves to it.
|
|
265
|
+
const remote = /^[\w./-]+$/.test(rev) ? await tryGit(this.root, ["for-each-ref", "--format=%(objectname)", `refs/remotes/*/${rev}`]) : null;
|
|
266
|
+
const hits = remote ? [...new Set(remote.trim().split("\n").filter(Boolean))] : [];
|
|
267
|
+
if (hits.length === 1) return (await this.run(["rev-parse", "--verify", `${hits[0]}^{commit}`])).trim();
|
|
268
|
+
throw new GitError(`Unknown revision: ${rev}`, 404);
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
// ---------------------------------------------------------- overview
|
|
272
|
+
|
|
273
|
+
async info() {
|
|
274
|
+
const [branch, head, refsOut, remoteUrl, statusOut, version] = await Promise.all([
|
|
275
|
+
tryGit(this.root, ["symbolic-ref", "--quiet", "--short", "HEAD"]),
|
|
276
|
+
tryGit(this.root, ["rev-parse", "--verify", "--quiet", "HEAD"]),
|
|
277
|
+
this.run([
|
|
278
|
+
"for-each-ref",
|
|
279
|
+
"--sort=-creatordate",
|
|
280
|
+
"--format=%(refname)%00%(objectname)%00%(*objectname)%00%(upstream:short)%00%(upstream:track,nobracket)%00%(creatordate:unix)%00%(contents:subject)",
|
|
281
|
+
"refs/heads",
|
|
282
|
+
"refs/remotes",
|
|
283
|
+
"refs/tags",
|
|
284
|
+
]),
|
|
285
|
+
tryGit(this.root, ["config", "--get", "remote.origin.url"]),
|
|
286
|
+
this.bare ? null : tryGit(this.root, ["status", "--porcelain=v1", "-z", "--untracked-files=normal"]),
|
|
287
|
+
tryGit(this.root, ["version"]),
|
|
288
|
+
]);
|
|
289
|
+
|
|
290
|
+
const branches = [];
|
|
291
|
+
const remotes = [];
|
|
292
|
+
const tags = [];
|
|
293
|
+
for (const line of refsOut.split("\n")) {
|
|
294
|
+
if (!line) continue;
|
|
295
|
+
const [ref, oid, peeled, upstream, track, date, subject] = line.split(FS);
|
|
296
|
+
const target = peeled || oid;
|
|
297
|
+
if (ref.startsWith("refs/heads/")) {
|
|
298
|
+
const t = { ahead: 0, behind: 0, gone: track === "gone" };
|
|
299
|
+
for (const m of track.matchAll(/(ahead|behind) (\d+)/g)) t[m[1]] = Number(m[2]);
|
|
300
|
+
branches.push({ name: ref.slice(11), target, upstream: upstream || null, ...t, date: Number(date) });
|
|
301
|
+
} else if (ref.startsWith("refs/remotes/")) {
|
|
302
|
+
const name = ref.slice(13);
|
|
303
|
+
if (name.endsWith("/HEAD")) continue;
|
|
304
|
+
const slash = name.indexOf("/");
|
|
305
|
+
remotes.push({ name, remote: name.slice(0, slash), short: name.slice(slash + 1), target, date: Number(date) });
|
|
306
|
+
} else if (ref.startsWith("refs/tags/")) {
|
|
307
|
+
tags.push({ name: ref.slice(10), target, annotated: Boolean(peeled), message: peeled ? subject : "", date: Number(date) });
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
let changes = 0;
|
|
312
|
+
if (statusOut) {
|
|
313
|
+
const parts = statusOut.split(FS);
|
|
314
|
+
for (let i = 0; i < parts.length; i++) {
|
|
315
|
+
if (!parts[i]) continue;
|
|
316
|
+
changes++;
|
|
317
|
+
if (parts[i][0] === "R" || parts[i][0] === "C") i++; // rename source follows
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
return {
|
|
322
|
+
name: this.name,
|
|
323
|
+
root: this.root,
|
|
324
|
+
bare: this.bare,
|
|
325
|
+
branch: branch ? branch.trim() : null,
|
|
326
|
+
head: head ? head.trim() : null,
|
|
327
|
+
branches,
|
|
328
|
+
remotes,
|
|
329
|
+
tags,
|
|
330
|
+
changes,
|
|
331
|
+
emptyTree: this.emptyTree,
|
|
332
|
+
remoteUrl: webUrl(remoteUrl?.trim()),
|
|
333
|
+
gitVersion: version?.trim().replace(/^git version /, "") ?? null,
|
|
334
|
+
};
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
/** Cheap fingerprint the UI polls to notice repository changes. */
|
|
338
|
+
async fingerprint() {
|
|
339
|
+
const [refs, head, sym, index] = await Promise.all([
|
|
340
|
+
this.run(["for-each-ref", "--format=%(objectname) %(refname)"]),
|
|
341
|
+
tryGit(this.root, ["rev-parse", "--quiet", "--verify", "HEAD"]),
|
|
342
|
+
tryGit(this.root, ["symbolic-ref", "--quiet", "HEAD"]),
|
|
343
|
+
stat(path.join(this.gitDir, "index")).then((s) => s.mtimeMs, () => 0),
|
|
344
|
+
]);
|
|
345
|
+
return createHash("sha1").update(`${refs}|${head}|${sym}|${index}`).digest("hex");
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
// ---------------------------------------------------------- history
|
|
349
|
+
|
|
350
|
+
/**
|
|
351
|
+
* One page of history.
|
|
352
|
+
* ref: revision to start from (default: every branch, remote and tag).
|
|
353
|
+
* message / author / code (pickaxe) / path narrow the result.
|
|
354
|
+
*/
|
|
355
|
+
async log({ ref, skip = 0, limit = 300, message, author, code, path: p, follow = false } = {}) {
|
|
356
|
+
const max = Math.min(2000, Math.max(1, limit | 0));
|
|
357
|
+
const args = ["log", "--decorate=full", `--format=${LOG_FORMAT}`, "--date-order", `--skip=${Math.max(0, skip | 0)}`, `--max-count=${max}`];
|
|
358
|
+
const filtered = Boolean(message || author || code || (p && follow));
|
|
359
|
+
if (message) args.push("--fixed-strings", "--regexp-ignore-case", `--grep=${message}`);
|
|
360
|
+
if (author) args.push("--regexp-ignore-case", `--author=${escapeRegex(author)}`);
|
|
361
|
+
if (code) args.push(`-S${code}`);
|
|
362
|
+
if (p && follow) args.push("--follow");
|
|
363
|
+
else if (p && !filtered) args.push("--parents"); // rewritten parents keep the graph connected
|
|
364
|
+
if (ref) {
|
|
365
|
+
args.push(await this.resolve(ref));
|
|
366
|
+
} else {
|
|
367
|
+
const head = await tryGit(this.root, ["rev-parse", "--verify", "--quiet", "HEAD"]);
|
|
368
|
+
if (!head && !(await this.hasRefs())) return { commits: [], graph: true, done: true };
|
|
369
|
+
if (head) args.push("HEAD");
|
|
370
|
+
args.push("--branches", "--remotes", "--tags");
|
|
371
|
+
}
|
|
372
|
+
args.push("--");
|
|
373
|
+
if (p) args.push(checkPath(p));
|
|
374
|
+
const out = await this.run(args);
|
|
375
|
+
const commits = parseLog(String(out));
|
|
376
|
+
return { commits, graph: !filtered, done: commits.length < max };
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
async hasRefs() {
|
|
380
|
+
const out = await tryGit(this.root, ["for-each-ref", "--count=1", "--format=x", "refs/heads", "refs/remotes", "refs/tags"]);
|
|
381
|
+
return Boolean(out && out.trim());
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
async commit(rev) {
|
|
385
|
+
const hash = await this.resolve(rev);
|
|
386
|
+
if (hash === WORKTREE) return this.worktreeCommit();
|
|
387
|
+
return this.cache.get(`commit:${hash}`, async () => {
|
|
388
|
+
const out = await this.run(["show", "-s", "--decorate=full", "--format=%H%x00%P%x00%an%x00%ae%x00%at%x00%cn%x00%ce%x00%ct%x00%D%x00%B", hash]);
|
|
389
|
+
const [h, parents, an, ae, at, cn, ce, ct, refs, ...body] = out.split(FS);
|
|
390
|
+
const message = body.join("").replace(/\s+$/, "");
|
|
391
|
+
const nl = message.indexOf("\n");
|
|
392
|
+
return {
|
|
393
|
+
hash: h,
|
|
394
|
+
parents: parents ? parents.split(" ") : [],
|
|
395
|
+
author: an,
|
|
396
|
+
email: ae,
|
|
397
|
+
date: Number(at),
|
|
398
|
+
committer: cn,
|
|
399
|
+
committerEmail: ce,
|
|
400
|
+
commitDate: Number(ct),
|
|
401
|
+
refs: parseDecorations(refs),
|
|
402
|
+
subject: nl === -1 ? message : message.slice(0, nl),
|
|
403
|
+
body: nl === -1 ? "" : message.slice(nl + 1).replace(/^\n+/, ""),
|
|
404
|
+
};
|
|
405
|
+
});
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
async worktreeCommit() {
|
|
409
|
+
const head = await tryGit(this.root, ["rev-parse", "--verify", "--quiet", "HEAD"]);
|
|
410
|
+
return {
|
|
411
|
+
hash: WORKTREE,
|
|
412
|
+
parents: head ? [head.trim()] : [],
|
|
413
|
+
subject: "Uncommitted changes",
|
|
414
|
+
body: "",
|
|
415
|
+
author: "",
|
|
416
|
+
email: "",
|
|
417
|
+
date: Math.floor(Date.now() / 1000),
|
|
418
|
+
refs: [],
|
|
419
|
+
};
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
/** Branches and tags whose history contains a commit. */
|
|
423
|
+
async containedIn(rev) {
|
|
424
|
+
const hash = await this.resolve(rev);
|
|
425
|
+
const out = await this.run(
|
|
426
|
+
["for-each-ref", "--contains", hash, "--format=%(refname)", "refs/heads", "refs/remotes", "refs/tags"],
|
|
427
|
+
{ timeout: 20_000 },
|
|
428
|
+
);
|
|
429
|
+
const res = { branches: [], remotes: [], tags: [] };
|
|
430
|
+
for (const r of out.split("\n")) {
|
|
431
|
+
if (r.startsWith("refs/heads/")) res.branches.push(r.slice(11));
|
|
432
|
+
else if (r.startsWith("refs/remotes/") && !r.endsWith("/HEAD")) res.remotes.push(r.slice(13));
|
|
433
|
+
else if (r.startsWith("refs/tags/")) res.tags.push(r.slice(10));
|
|
434
|
+
}
|
|
435
|
+
return res;
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
// ---------------------------------------------------------- diffs
|
|
439
|
+
|
|
440
|
+
/** `from` may be "" (the empty tree, for root commits); `to` may be WORKTREE. */
|
|
441
|
+
async endpoints(from, to) {
|
|
442
|
+
const a = from ? await this.resolve(from) : this.emptyTree;
|
|
443
|
+
const b = await this.resolve(to);
|
|
444
|
+
if (a === WORKTREE) throw new GitError("The working tree can only be the target of a comparison", 400);
|
|
445
|
+
return [a, b];
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
diffArgs(a, b, extra) {
|
|
449
|
+
return b === WORKTREE ? ["diff", ...extra, a] : ["diff", ...extra, a, b];
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
async files(from, to, { ignoreWhitespace = false } = {}) {
|
|
453
|
+
const [a, b] = await this.endpoints(from, to);
|
|
454
|
+
const compute = async () => {
|
|
455
|
+
const ws = ignoreWhitespace ? ["-w"] : [];
|
|
456
|
+
const [raw, num] = await Promise.all([
|
|
457
|
+
this.run(this.diffArgs(a, b, ["--raw", "-z", "-M", "--no-abbrev"])),
|
|
458
|
+
this.run(this.diffArgs(a, b, ["--numstat", "-z", "-M", ...ws])),
|
|
459
|
+
]);
|
|
460
|
+
const files = parseFileChanges(raw, num);
|
|
461
|
+
if (b === WORKTREE) {
|
|
462
|
+
const untracked = await this.run(["ls-files", "--others", "--exclude-standard", "-z"]);
|
|
463
|
+
for (const p of untracked.split(FS)) {
|
|
464
|
+
if (p) files.push({ status: "?", path: p, additions: 0, deletions: 0, binary: false });
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
return files;
|
|
468
|
+
};
|
|
469
|
+
const files = b === WORKTREE ? await compute() : await this.cache.get(`files:${a}:${b}:${ignoreWhitespace}`, compute);
|
|
470
|
+
let additions = 0;
|
|
471
|
+
let deletions = 0;
|
|
472
|
+
for (const f of files) {
|
|
473
|
+
additions += f.additions;
|
|
474
|
+
deletions += f.deletions;
|
|
475
|
+
}
|
|
476
|
+
return { from: a, to: b, files, additions, deletions };
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
async patch(from, to, file, oldFile, { ignoreWhitespace = false, context = 3 } = {}) {
|
|
480
|
+
const [a, b] = await this.endpoints(from, to);
|
|
481
|
+
const p = checkPath(file);
|
|
482
|
+
const paths = oldFile && oldFile !== file ? [checkPath(oldFile), p] : [p];
|
|
483
|
+
const ctx = Math.min(100000, Math.max(0, context | 0));
|
|
484
|
+
const compute = async () => {
|
|
485
|
+
const args = this.diffArgs(a, b, ["-M", `-U${ctx}`, "--no-ext-diff", ...(ignoreWhitespace ? ["-w"] : [])]);
|
|
486
|
+
const out = await this.run([...args, "--", ...paths], { maxBytes: 4 * MB });
|
|
487
|
+
return { patch: String(out), truncated: Boolean(out.truncated) };
|
|
488
|
+
};
|
|
489
|
+
if (b === WORKTREE) {
|
|
490
|
+
const res = await compute();
|
|
491
|
+
if (!res.patch) {
|
|
492
|
+
const tracked = await tryGit(this.root, ["ls-files", "--error-unmatch", "--", p]);
|
|
493
|
+
if (tracked === null) return this.untrackedPatch(p);
|
|
494
|
+
}
|
|
495
|
+
return res;
|
|
496
|
+
}
|
|
497
|
+
return this.cache.get(`patch:${a}:${b}:${paths.join("\0")}:${ignoreWhitespace}:${ctx}`, compute);
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
async untrackedPatch(p) {
|
|
501
|
+
const full = path.resolve(this.root, p);
|
|
502
|
+
if (!full.startsWith(this.root + path.sep)) throw new GitError("Invalid path", 400);
|
|
503
|
+
const buf = await readFile(full).catch(() => null);
|
|
504
|
+
if (!buf) return { patch: "", truncated: false };
|
|
505
|
+
if (isBinary(buf)) return { patch: `Binary files /dev/null and b/${p} differ\n`, truncated: false };
|
|
506
|
+
const text = buf.subarray(0, 2 * MB).toString("utf8");
|
|
507
|
+
if (!text) return { patch: "", truncated: false };
|
|
508
|
+
const lines = text.replace(/\n$/, "").split("\n");
|
|
509
|
+
return {
|
|
510
|
+
patch: `--- /dev/null\n+++ b/${p}\n@@ -0,0 +1,${lines.length} @@\n` + lines.map((l) => "+" + l).join("\n") + "\n",
|
|
511
|
+
truncated: buf.length > 2 * MB,
|
|
512
|
+
};
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
/**
|
|
516
|
+
* What happens when you move from commit `from` to commit `to`:
|
|
517
|
+
* added - commits only in `to` (applied by the move), newest first
|
|
518
|
+
* removed - commits only in `from` (undone by the move), newest first
|
|
519
|
+
* path - snapshots to step through, in order: back from `from` along
|
|
520
|
+
* its first parents to the common ancestor, then forward along
|
|
521
|
+
* `to`'s first parents. The last entry is `to`.
|
|
522
|
+
*/
|
|
523
|
+
async range(from, to) {
|
|
524
|
+
const a = await this.resolve(from);
|
|
525
|
+
const b = await this.resolve(to);
|
|
526
|
+
const empty = { added: [], removed: [], path: [], addedCount: 0, removedCount: 0, mergeBase: null };
|
|
527
|
+
if (a === WORKTREE || b === WORKTREE || a === b) return empty;
|
|
528
|
+
const log = (...args) => this.run(["log", "--decorate=full", `--format=${LOG_FORMAT}`, ...args]).then(parseLog);
|
|
529
|
+
const LIMIT = "--max-count=500";
|
|
530
|
+
const [counts, baseOut, added, removed, down, up] = await Promise.all([
|
|
531
|
+
this.run(["rev-list", "--left-right", "--count", `${a}...${b}`]),
|
|
532
|
+
tryGit(this.root, ["merge-base", a, b]),
|
|
533
|
+
log("--date-order", LIMIT, b, `^${a}`),
|
|
534
|
+
log("--date-order", LIMIT, a, `^${b}`),
|
|
535
|
+
log("--first-parent", LIMIT, a, `^${b}`),
|
|
536
|
+
log("--first-parent", LIMIT, b, `^${a}`),
|
|
537
|
+
]);
|
|
538
|
+
const [removedCount, addedCount] = counts.trim().split(/\s+/).map(Number);
|
|
539
|
+
const mergeBase = baseOut ? baseOut.trim() : null;
|
|
540
|
+
|
|
541
|
+
const path = down.slice(1); // stepping back from `from` (itself excluded)
|
|
542
|
+
if (down.length && mergeBase && mergeBase !== b) path.push((await log("-1", mergeBase))[0]);
|
|
543
|
+
path.push(...up.reverse()); // then forward to `to`
|
|
544
|
+
if (!path.length || path[path.length - 1].hash !== b) path.push((await log("-1", b))[0]);
|
|
545
|
+
|
|
546
|
+
return { added, removed, path, addedCount, removedCount, mergeBase };
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
// ---------------------------------------------------------- browsing
|
|
550
|
+
|
|
551
|
+
async tree(rev, dir = "") {
|
|
552
|
+
const hash = await this.resolve(rev);
|
|
553
|
+
if (hash === WORKTREE) throw new GitError("Pick a commit to browse", 400);
|
|
554
|
+
const d = checkPath(dir).replace(/\/+$/, "");
|
|
555
|
+
return this.cache.get(`tree:${hash}:${d}`, async () => {
|
|
556
|
+
const out = await this.run(["ls-tree", "-z", "-l", hash, ...(d ? ["--", d + "/"] : [])]);
|
|
557
|
+
const entries = [];
|
|
558
|
+
for (const rec of out.split(FS)) {
|
|
559
|
+
if (!rec) continue;
|
|
560
|
+
const tab = rec.indexOf("\t");
|
|
561
|
+
const [mode, type, oid, size] = rec.slice(0, tab).split(/\s+/);
|
|
562
|
+
const full = rec.slice(tab + 1);
|
|
563
|
+
entries.push({ name: full.split("/").pop(), path: full, type, mode, oid, size: size === "-" ? null : Number(size) });
|
|
564
|
+
}
|
|
565
|
+
const order = { tree: 0, commit: 1, blob: 2 };
|
|
566
|
+
entries.sort((x, y) => order[x.type] - order[y.type] || x.name.localeCompare(y.name));
|
|
567
|
+
return { rev: hash, path: d, entries };
|
|
568
|
+
});
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
async blob(rev, file) {
|
|
572
|
+
const hash = await this.resolve(rev);
|
|
573
|
+
if (hash === WORKTREE) throw new GitError("Pick a commit to browse", 400);
|
|
574
|
+
const p = checkPath(file);
|
|
575
|
+
return this.cache.get(`blob:${hash}:${p}`, async () => {
|
|
576
|
+
const spec = `${hash}:${p}`;
|
|
577
|
+
const size = Number((await this.run(["cat-file", "-s", spec])).trim());
|
|
578
|
+
const limit = 2 * MB;
|
|
579
|
+
const buf = await this.run(["cat-file", "blob", spec], { raw: true, maxBytes: limit });
|
|
580
|
+
if (isBinary(buf)) return { path: p, size, binary: true, content: "" };
|
|
581
|
+
return { path: p, size, binary: false, truncated: size > limit, content: buf.toString("utf8") };
|
|
582
|
+
});
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
async blame(rev, file) {
|
|
586
|
+
const hash = await this.resolve(rev);
|
|
587
|
+
if (hash === WORKTREE) throw new GitError("Pick a commit to blame", 400);
|
|
588
|
+
const p = checkPath(file);
|
|
589
|
+
return this.cache.get(`blame:${hash}:${p}`, async () => {
|
|
590
|
+
const out = await this.run(["blame", "--porcelain", "-w", hash, "--", p], { maxBytes: 32 * MB, timeout: 120_000 });
|
|
591
|
+
const commits = {};
|
|
592
|
+
const lines = [];
|
|
593
|
+
let cur = null;
|
|
594
|
+
for (const line of out.split("\n")) {
|
|
595
|
+
if (line.startsWith("\t")) {
|
|
596
|
+
lines.push(cur);
|
|
597
|
+
continue;
|
|
598
|
+
}
|
|
599
|
+
const head = line.match(/^([0-9a-f]{40,64}) \d+ \d+/);
|
|
600
|
+
if (head) {
|
|
601
|
+
cur = head[1];
|
|
602
|
+
commits[cur] ??= {};
|
|
603
|
+
continue;
|
|
604
|
+
}
|
|
605
|
+
const sp = line.indexOf(" ");
|
|
606
|
+
const key = line.slice(0, sp);
|
|
607
|
+
const val = line.slice(sp + 1);
|
|
608
|
+
if (key === "author") commits[cur].author = val;
|
|
609
|
+
else if (key === "author-mail") commits[cur].email = val.replace(/^<|>$/g, "");
|
|
610
|
+
else if (key === "author-time") commits[cur].date = Number(val);
|
|
611
|
+
else if (key === "summary") commits[cur].subject = val;
|
|
612
|
+
}
|
|
613
|
+
return { rev: hash, path: p, lines, commits };
|
|
614
|
+
});
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
// ---------------------------------------------------------- insights
|
|
618
|
+
|
|
619
|
+
async insights(ref) {
|
|
620
|
+
const target = ref ? await this.resolve(ref) : null;
|
|
621
|
+
const key = `insights:${target ?? "*"}:${await this.fingerprint()}`;
|
|
622
|
+
return this.cache.get(key, async () => {
|
|
623
|
+
const args = ["log", "--format=%at%x00%aN%x00%aE", "--use-mailmap", "--no-merges"];
|
|
624
|
+
if (target) args.push(target);
|
|
625
|
+
else if (await this.hasRefs()) args.push("--branches", "--remotes", "--tags");
|
|
626
|
+
else return emptyInsights();
|
|
627
|
+
const out = await this.run(args, { maxBytes: 512 * MB, timeout: 180_000 });
|
|
628
|
+
const days = {};
|
|
629
|
+
const punch = Array.from({ length: 7 }, () => Array(24).fill(0));
|
|
630
|
+
const people = new Map();
|
|
631
|
+
let first = Infinity;
|
|
632
|
+
let last = 0;
|
|
633
|
+
let total = 0;
|
|
634
|
+
for (const line of out.split("\n")) {
|
|
635
|
+
if (!line) continue;
|
|
636
|
+
const [t, name, email] = line.split(FS);
|
|
637
|
+
const ts = Number(t);
|
|
638
|
+
total++;
|
|
639
|
+
if (ts < first) first = ts;
|
|
640
|
+
if (ts > last) last = ts;
|
|
641
|
+
const d = new Date(ts * 1000);
|
|
642
|
+
const day = `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
|
|
643
|
+
days[day] = (days[day] || 0) + 1;
|
|
644
|
+
punch[d.getDay()][d.getHours()]++;
|
|
645
|
+
const k = (email || name).toLowerCase();
|
|
646
|
+
const p = people.get(k) || { name, email, commits: 0, first: ts, last: ts };
|
|
647
|
+
p.commits++;
|
|
648
|
+
if (ts < p.first) p.first = ts;
|
|
649
|
+
if (ts > p.last) p.last = ts;
|
|
650
|
+
people.set(k, p);
|
|
651
|
+
}
|
|
652
|
+
const contributors = [...people.values()].sort((a, b) => b.commits - a.commits);
|
|
653
|
+
return {
|
|
654
|
+
total,
|
|
655
|
+
first: total ? first : null,
|
|
656
|
+
last: total ? last : null,
|
|
657
|
+
days,
|
|
658
|
+
punch,
|
|
659
|
+
contributorCount: contributors.length,
|
|
660
|
+
contributors: contributors.slice(0, 100),
|
|
661
|
+
};
|
|
662
|
+
});
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
// ---------------------------------------------------------- network
|
|
666
|
+
|
|
667
|
+
fetch() {
|
|
668
|
+
return this.run(["fetch", "--all", "--prune", "--quiet"], { timeout: 180_000 });
|
|
669
|
+
}
|
|
670
|
+
}
|
|
671
|
+
|
|
672
|
+
function emptyInsights() {
|
|
673
|
+
return { total: 0, first: null, last: null, days: {}, punch: Array.from({ length: 7 }, () => Array(24).fill(0)), contributorCount: 0, contributors: [] };
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
const pad = (n) => String(n).padStart(2, "0");
|
|
677
|
+
|
|
678
|
+
function escapeRegex(s) {
|
|
679
|
+
return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
/** Turn a remote URL into a browsable https URL (GitHub, GitLab, ...). */
|
|
683
|
+
export function webUrl(url) {
|
|
684
|
+
if (!url) return null;
|
|
685
|
+
let m = url.match(/^(?:ssh:\/\/)?[\w.-]+@([\w.-]+)(?::\d+)?[:/](.+?)(?:\.git)?\/?$/);
|
|
686
|
+
if (m) return `https://${m[1]}/${m[2]}`;
|
|
687
|
+
m = url.match(/^https?:\/\/(?:[^@/]+@)?([^/]+)\/(.+?)(?:\.git)?\/?$/);
|
|
688
|
+
if (m) return `https://${m[1]}/${m[2]}`;
|
|
689
|
+
return null;
|
|
690
|
+
}
|