agy-git-graph 0.0.0-stage → 1.0.0

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.
@@ -0,0 +1,410 @@
1
+ import { execFile } from 'node:child_process';
2
+ import {
3
+ closeSync, lstatSync, openSync, readlinkSync, readSync, realpathSync, rmSync, statSync,
4
+ } from 'node:fs';
5
+ import { basename, dirname, isAbsolute, posix, relative, resolve, sep, win32 } from 'node:path';
6
+
7
+ const DIFF_LIMIT = 200 * 1024;
8
+ const LOG_FORMAT = '%H%x00%h%x00%P%x00%D%x00%an%x00%ae%x00%at%x00%s';
9
+ const DIFF_OPTIONS = ['--no-color', '--no-ext-diff', '--no-textconv'];
10
+ const CONFLICTS = new Set(['DD', 'AU', 'UD', 'UA', 'DU', 'AA', 'UU']);
11
+
12
+ export class InputError extends Error {}
13
+
14
+ function git(root, args, encoding = 'utf8') {
15
+ return new Promise((resolveOutput, reject) => {
16
+ execFile('git', [
17
+ '--no-pager', '--no-optional-locks', '--literal-pathspecs',
18
+ '-c', 'core.quotepath=false', '-c', 'i18n.logOutputEncoding=utf-8',
19
+ '-C', root, ...args,
20
+ ], { windowsHide: true, maxBuffer: 16 * 1024 * 1024, encoding }, (error, stdout, stderr) => {
21
+ if (error?.code === 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER' &&
22
+ encoding === 'buffer' && stdout.length > DIFF_LIMIT) {
23
+ resolveOutput(stdout);
24
+ } else if (error) {
25
+ const message = stderr.toString().trim();
26
+ reject(message ? new Error(message) : error);
27
+ } else {
28
+ resolveOutput(stdout);
29
+ }
30
+ });
31
+ });
32
+ }
33
+
34
+ export function normalizeDirectory(value) {
35
+ if (typeof value !== 'string' || value.includes('\0')) return '';
36
+ let path = value.trim();
37
+ if (!path) return '';
38
+ if (/^file:\/\//i.test(path)) {
39
+ try {
40
+ const uri = new URL(path);
41
+ if (/%(?:2f|5c)/i.test(uri.pathname)) return '';
42
+ path = decodeURIComponent(uri.pathname);
43
+ if (uri.hostname) path = '//' + uri.hostname + path;
44
+ else if (/^\/[a-z]:\//i.test(path)) path = path.slice(1);
45
+ } catch {
46
+ return '';
47
+ }
48
+ }
49
+ if (/^[\\/]{2}\?[\\/]/.test(path)) {
50
+ path = path.slice(4).replace(/^UNC[\\/]/i, '\\\\');
51
+ }
52
+ if (!path || path.includes('\0')) return '';
53
+ if (process.platform === 'win32' || /^[a-z]:[\\/]|^[\\/]{2}[^\\/]/i.test(path)) {
54
+ path = win32.normalize(path).replace(/^[a-z]:/i, (drive) => drive.toUpperCase());
55
+ return path.length > win32.parse(path).root.length ? path.replace(/[\\]+$/, '') : path;
56
+ }
57
+ return path ? posix.normalize(path).replace(/(.+)\/$/, '$1') : '';
58
+ }
59
+
60
+ export async function validateRepo(repoPath) {
61
+ const path = normalizeDirectory(repoPath);
62
+ if (!path || !isAbsolute(path) || !statSync(path, { throwIfNoEntry: false })?.isDirectory()) {
63
+ throw new InputError('请选择存在的 Git 仓库目录。');
64
+ }
65
+ let root;
66
+ try {
67
+ root = await git(path, ['rev-parse', '--show-toplevel']);
68
+ } catch (error) {
69
+ if (error.code === 'ENOENT') throw new Error('Git is required on PATH.');
70
+ throw new InputError(error.message || '该目录不在 Git 仓库中。');
71
+ }
72
+ return normalizeDirectory(realpathSync(root.replace(/\r?\n$/, '')));
73
+ }
74
+
75
+ function isInside(root, target) {
76
+ const rest = relative(root, target);
77
+ return rest !== '..' && !rest.startsWith('..' + sep) && !isAbsolute(rest);
78
+ }
79
+
80
+ export function validateRelPath(repoRoot, relPath) {
81
+ if (typeof relPath !== 'string' || !relPath || relPath.includes('\0') ||
82
+ isAbsolute(relPath) || win32.isAbsolute(relPath) || /^[a-z]:/i.test(relPath)) {
83
+ throw new InputError('无效的相对文件路径。');
84
+ }
85
+ const parts = relPath.split(process.platform === 'win32' ? /[\\/]/ : /\//);
86
+ if (parts.some((part) => part === '..' || /^\.git$/i.test(part) ||
87
+ (process.platform === 'win32' && /[:]|[. ]$/.test(part) && part !== '.'))) {
88
+ throw new InputError('文件路径必须位于 Git 工作区内。');
89
+ }
90
+ const clean = parts.filter((part) => part && part !== '.').join('/');
91
+ const absolute = resolve(repoRoot, clean);
92
+ if (!clean || !isInside(repoRoot, absolute)) {
93
+ throw new InputError('文件路径必须位于 Git 工作区内。');
94
+ }
95
+ // Check real parents too. The final component may be a Git-tracked symlink.
96
+ for (let parent = dirname(absolute); parent !== repoRoot; parent = dirname(parent)) {
97
+ if (!lstatSync(parent, { throwIfNoEntry: false })) continue;
98
+ if (!isInside(repoRoot, realpathSync(parent))) {
99
+ throw new InputError('文件路径指向 Git 工作区之外。');
100
+ }
101
+ break;
102
+ }
103
+ return clean;
104
+ }
105
+
106
+ export function validateCommitHash(hash) {
107
+ if (typeof hash !== 'string' || !/^[0-9a-f]{4,40}$/i.test(hash)) {
108
+ throw new InputError('无效的提交哈希。');
109
+ }
110
+ return hash.toLowerCase();
111
+ }
112
+
113
+ async function commitHash(root, hash) {
114
+ const checked = validateCommitHash(hash);
115
+ const fullHash = (await git(root, ['rev-parse', '--verify', '--end-of-options', checked + '^{commit}'])
116
+ .catch(() => '')).trim();
117
+ if (!fullHash.startsWith(checked)) throw new InputError('找不到该提交。');
118
+ return fullHash;
119
+ }
120
+
121
+ export async function validateBranchRef(root, branch) {
122
+ if (typeof branch !== 'string' || !branch || branch.startsWith('-') || branch.includes('\0')) {
123
+ throw new InputError('无效的分支。');
124
+ }
125
+ // UI values carry full namespaces to distinguish equally named local and remote branches.
126
+ const explicit = /^refs\/(?:heads|remotes)\//.test(branch);
127
+ const refs = explicit ? [branch] : ['refs/heads/' + branch, 'refs/remotes/' + branch];
128
+ for (const ref of refs) {
129
+ if (await git(root, ['show-ref', '--verify', '--quiet', '--', ref]).then(() => true, () => false)) {
130
+ return ref;
131
+ }
132
+ }
133
+ throw new InputError('找不到该分支。');
134
+ }
135
+
136
+ function optionalRef(root, args) {
137
+ return git(root, args).then((value) => value.trim(), () => '');
138
+ }
139
+
140
+ function getHead(root) {
141
+ return optionalRef(root, ['rev-parse', '--verify', 'HEAD']);
142
+ }
143
+
144
+ export async function getRepoSummary(repoPath) {
145
+ const root = await validateRepo(repoPath);
146
+ const [symbolic, headHash, upstream] = await Promise.all([
147
+ optionalRef(root, ['symbolic-ref', '--quiet', '--short', 'HEAD']),
148
+ getHead(root),
149
+ optionalRef(root, ['rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{u}']),
150
+ ]);
151
+ const counts = upstream && headHash
152
+ ? await optionalRef(root, ['rev-list', '--left-right', '--count', '@{u}...HEAD'])
153
+ : '';
154
+ const [behind = 0, ahead = 0] = counts ? counts.split(/\s+/).map(Number) : [];
155
+ return {
156
+ root, name: basename(root) || root, headHash, upstream, ahead, behind,
157
+ branch: symbolic || headHash.slice(0, 7), detached: !symbolic && Boolean(headHash),
158
+ };
159
+ }
160
+
161
+ export async function getBranches(repoPath) {
162
+ const root = await validateRepo(repoPath);
163
+ const [raw, current] = await Promise.all([
164
+ git(root, ['for-each-ref', '--format=%(refname)%00%(symref)', 'refs/heads', 'refs/remotes']),
165
+ optionalRef(root, ['symbolic-ref', '--quiet', '--short', 'HEAD']),
166
+ ]);
167
+ const local = [];
168
+ const remote = [];
169
+ for (const line of raw.split(/\r?\n/).filter(Boolean)) {
170
+ const [ref, symbolic] = line.split('\0');
171
+ if (symbolic) continue;
172
+ if (ref.startsWith('refs/heads/')) local.push(ref.slice('refs/heads/'.length));
173
+ if (ref.startsWith('refs/remotes/')) remote.push(ref.slice('refs/remotes/'.length));
174
+ }
175
+ return { local, remote, current };
176
+ }
177
+
178
+ async function readStatus(root) {
179
+ const raw = await git(root, ['status', '--porcelain=v1', '-z', '-uall', '--find-renames']);
180
+ const records = raw.split('\0');
181
+ const staged = [];
182
+ const unstaged = [];
183
+ for (let i = 0; i < records.length - 1; i++) {
184
+ const record = records[i];
185
+ const xy = record.slice(0, 2);
186
+ const [index, tree] = xy;
187
+ const path = record.slice(3);
188
+ const dir = posix.dirname(path);
189
+ const item = { path, dir: dir === '.' ? '' : dir, fileName: posix.basename(path) };
190
+ if (/[RC]/.test(xy)) item.origPath = records[++i];
191
+ if (xy === '??') {
192
+ unstaged.push({ ...item, status: '?', untracked: true });
193
+ } else if (CONFLICTS.has(xy)) {
194
+ staged.push({ ...item, status: 'U', conflict: xy });
195
+ unstaged.push({ ...item, status: 'U', conflict: xy });
196
+ } else {
197
+ if (index !== ' ') staged.push({ ...item, status: index });
198
+ if (tree !== ' ') unstaged.push({ ...item, status: tree });
199
+ }
200
+ }
201
+ return { staged, unstaged };
202
+ }
203
+
204
+ export async function getStatus(repoPath) {
205
+ return readStatus(await validateRepo(repoPath));
206
+ }
207
+
208
+ function metadata(fields) {
209
+ const [hash, shortHash, parents, refs, author, email, timestamp, subject] = fields;
210
+ return {
211
+ hash, shortHash, parents: parents ? parents.split(' ') : [], refs,
212
+ author, email, timestamp: Number(timestamp), subject,
213
+ };
214
+ }
215
+
216
+ export async function getCommitLog(repoPath, {
217
+ scope = 'all', branch = '', limit = 80, skip = 0, search = '',
218
+ } = {}) {
219
+ if (!['all', 'current', 'branch'].includes(scope) || !Number.isSafeInteger(limit) ||
220
+ limit < 1 || limit >= 2147483647 || !Number.isSafeInteger(skip) || skip < 0 ||
221
+ skip >= 2147483647 || typeof search !== 'string' || search.includes('\0')) {
222
+ throw new InputError('无效的提交图筛选选项。');
223
+ }
224
+ const root = await validateRepo(repoPath);
225
+ const headHash = await getHead(root);
226
+ const revisions = [];
227
+ if (scope === 'branch') revisions.push(await validateBranchRef(root, branch));
228
+ if (scope === 'current' && headHash) revisions.push('HEAD');
229
+ if (scope === 'all') {
230
+ revisions.push('--all');
231
+ if (headHash) revisions.push('HEAD');
232
+ else if (!(await git(root, ['for-each-ref', '--count=1', '--format=%(refname)'])).trim()) {
233
+ return { commits: [], hasMore: false, headHash };
234
+ }
235
+ }
236
+ if (!revisions.length) return { commits: [], hasMore: false, headHash };
237
+
238
+ const args = [
239
+ 'log', '--date-order', '--topo-order', '--decorate=full', '-z',
240
+ '--format=tformat:' + LOG_FORMAT, '--max-count=' + (limit + 1), '--skip=' + skip,
241
+ ];
242
+ if (search.trim()) args.push('--grep=' + search.trim(), '-i', '--regexp-ignore-case', '--fixed-strings');
243
+ const raw = await git(root, [...args, ...revisions, '--']);
244
+ const fields = raw.split('\0');
245
+ const commits = [];
246
+ for (let i = 0; i + 7 < fields.length; i += 8) commits.push(metadata(fields.slice(i, i + 8)));
247
+ return { commits: commits.slice(0, limit), hasMore: commits.length > limit, headHash };
248
+ }
249
+
250
+ function diffResult(bytes) {
251
+ const truncated = bytes.length > DIFF_LIMIT;
252
+ const diff = new TextDecoder().decode(bytes.subarray(0, DIFF_LIMIT), { stream: truncated });
253
+ const binary = /^(?:Binary files .* differ|GIT binary patch)$/m.test(diff);
254
+ return { diff: binary ? '' : diff, binary, truncated };
255
+ }
256
+
257
+ async function isUntracked(root, path) {
258
+ const raw = await git(root, ['ls-files', '--others', '--exclude-standard', '-z', '--', path]);
259
+ return raw.split('\0').includes(path);
260
+ }
261
+
262
+ function untrackedDiff(root, path) {
263
+ const absolute = resolve(root, path);
264
+ const stat = lstatSync(absolute);
265
+ let bytes;
266
+ if (stat.isSymbolicLink()) {
267
+ bytes = Buffer.from(readlinkSync(absolute));
268
+ } else {
269
+ if (!stat.isFile()) throw new InputError('只能预览普通文件或符号链接。');
270
+ const descriptor = openSync(absolute, 'r');
271
+ try {
272
+ const buffer = Buffer.alloc(DIFF_LIMIT + 1);
273
+ let size = 0;
274
+ while (size < buffer.length) {
275
+ const read = readSync(descriptor, buffer, size, buffer.length - size, null);
276
+ if (!read) break;
277
+ size += read;
278
+ }
279
+ bytes = buffer.subarray(0, size);
280
+ } finally {
281
+ closeSync(descriptor);
282
+ }
283
+ }
284
+ if (bytes.includes(0)) return { binary: true, diff: '', truncated: bytes.length > DIFF_LIMIT };
285
+ const truncated = bytes.length > DIFF_LIMIT;
286
+ const contents = new TextDecoder().decode(bytes.subarray(0, DIFF_LIMIT), { stream: truncated });
287
+ const endsInNewline = contents.endsWith('\n');
288
+ const lines = contents ? contents.split('\n') : [];
289
+ if (endsInNewline) lines.pop();
290
+ const label = /[\t\r\n"\\]/.test(path) ? JSON.stringify('b/' + path) : 'b/' + path;
291
+ const header = ['diff --git /dev/null ' + label, '--- /dev/null', '+++ ' + label];
292
+ if (lines.length) header.push('@@ -0,0 +1,' + lines.length + ' @@');
293
+ const patch = header.concat(lines.map((line) => '+' + line));
294
+ if (lines.length && !endsInNewline && !truncated) patch.push('\');
295
+ const result = diffResult(Buffer.from(patch.join('\n') + '\n'));
296
+ return { ...result, binary: false, truncated: truncated || result.truncated };
297
+ }
298
+
299
+ function pathsForChange(root, path, item) {
300
+ return item?.origPath && /[RC]/.test(item.status)
301
+ ? [validateRelPath(root, item.origPath), path]
302
+ : [path];
303
+ }
304
+
305
+ export async function getWorkingDiff(repoPath, { filePath, staged = false }) {
306
+ const root = await validateRepo(repoPath);
307
+ const path = validateRelPath(root, filePath);
308
+ if (!staged && await isUntracked(root, path)) return untrackedDiff(root, path);
309
+ const status = await readStatus(root);
310
+ const item = (staged ? status.staged : status.unstaged).find((change) => change.path === path);
311
+ const paths = pathsForChange(root, path, item);
312
+ const args = staged ? ['diff', '--cached'] : ['diff'];
313
+ return diffResult(await git(root, [...args, ...DIFF_OPTIONS, '-M', '--', ...paths], 'buffer'));
314
+ }
315
+
316
+ const SHOW_OPTIONS = ['--root', '--diff-merges=first-parent', '-M', ...DIFF_OPTIONS];
317
+
318
+ export async function getCommitDetail(repoPath, { hash }) {
319
+ const root = await validateRepo(repoPath);
320
+ const fullHash = await commitHash(root, hash);
321
+ const [record, stats, names] = await Promise.all([
322
+ git(root, ['show', '-s', '-z', '--decorate=full', '--format=tformat:' + LOG_FORMAT + '%x00%b', fullHash, '--']),
323
+ git(root, ['show', ...SHOW_OPTIONS, '--numstat', '-z', '--format=', fullHash, '--']),
324
+ git(root, ['show', ...SHOW_OPTIONS, '--name-status', '-z', '--format=', fullHash, '--']),
325
+ ]);
326
+ const counts = new Map();
327
+ const entries = stats.split('\0');
328
+ for (let i = 0; i < entries.length - 1; i++) {
329
+ const [added, deleted, ...pathParts] = entries[i].split('\t');
330
+ let path = pathParts.join('\t');
331
+ if (!path) {
332
+ // Renames have old and new NUL-separated paths.
333
+ i += 2;
334
+ path = entries[i];
335
+ }
336
+ const binary = added === '-' || deleted === '-';
337
+ counts.set(path, { added: binary ? null : Number(added), deleted: binary ? null : Number(deleted), binary });
338
+ }
339
+ const fields = names.split('\0');
340
+ const files = [];
341
+ for (let i = 0; i < fields.length - 1;) {
342
+ const status = fields[i++][0];
343
+ const origPath = /[RC]/.test(status) ? fields[i++] : undefined;
344
+ const path = fields[i++];
345
+ files.push({ path, origPath, status, ...counts.get(path) });
346
+ }
347
+ const details = record.split('\0');
348
+ return { ...metadata(details), body: details[8].replace(/\r?\n$/, ''), files };
349
+ }
350
+
351
+ export async function getCommitFileDiff(repoPath, { hash, filePath, origPath }) {
352
+ const root = await validateRepo(repoPath);
353
+ const path = validateRelPath(root, filePath);
354
+ const paths = origPath === undefined ? [path] : [validateRelPath(root, origPath), path];
355
+ const fullHash = await commitHash(root, hash);
356
+ return diffResult(await git(root, ['show', '--format=', '--patch', ...SHOW_OPTIONS, fullHash, '--', ...paths], 'buffer'));
357
+ }
358
+
359
+ function checkedPaths(root, paths) {
360
+ if (!Array.isArray(paths) || paths.length === 0) throw new InputError('请选择文件。');
361
+ return [...new Set(paths.map((path) => validateRelPath(root, path)))];
362
+ }
363
+
364
+ export async function stageFiles(repoPath, { paths, all = false }) {
365
+ const root = await validateRepo(repoPath);
366
+ await git(root, all === true ? ['add', '-A'] : ['add', '--', ...checkedPaths(root, paths)]);
367
+ }
368
+
369
+ export async function unstageFiles(repoPath, { paths, all = false }) {
370
+ const root = await validateRepo(repoPath);
371
+ const head = await getHead(root);
372
+ if (all === true) {
373
+ await git(root, head ? ['reset', '-q', 'HEAD'] : ['rm', '-q', '--cached', '-r', '-f', '--ignore-unmatch', '--', '.']);
374
+ return;
375
+ }
376
+ const targets = checkedPaths(root, paths);
377
+ const { staged } = await readStatus(root);
378
+ const expanded = new Set(targets.flatMap((path) => {
379
+ const item = staged.find((entry) => entry.path === path);
380
+ // A copy does not stage any removal of the source.
381
+ return item?.status === 'R' ? pathsForChange(root, path, item) : [path];
382
+ }));
383
+ const args = head ? ['reset', '-q', 'HEAD'] : ['rm', '-q', '--cached', '-f', '--ignore-unmatch'];
384
+ await git(root, [...args, '--', ...expanded]);
385
+ }
386
+
387
+ export async function discardFile(repoPath, { filePath, untracked = false }) {
388
+ const root = await validateRepo(repoPath);
389
+ const path = validateRelPath(root, filePath);
390
+ if (untracked === true) {
391
+ if (!await isUntracked(root, path)) throw new InputError('该文件已不再是未跟踪文件。');
392
+ const absolute = resolve(root, path);
393
+ const stat = lstatSync(absolute);
394
+ if (!stat.isFile() && !stat.isSymbolicLink()) throw new InputError('只能删除单个文件。');
395
+ rmSync(absolute);
396
+ } else {
397
+ await git(root, ['checkout', '--', path]);
398
+ }
399
+ }
400
+
401
+ export async function createCommit(repoPath, { message, stageAllIfEmpty = false }) {
402
+ if (typeof message !== 'string' || !message.trim() || message.includes('\0')) {
403
+ throw new InputError('请输入提交信息。');
404
+ }
405
+ const root = await validateRepo(repoPath);
406
+ const { staged } = await readStatus(root);
407
+ if (!staged.length && stageAllIfEmpty === true) await git(root, ['add', '-A']);
408
+ await git(root, ['commit', '-m', message.trim()]);
409
+ return { hash: await getHead(root) };
410
+ }
@@ -0,0 +1,83 @@
1
+ export function parseRefs(refs) {
2
+ return (refs || '').split(', ').filter(Boolean).map((ref) => {
3
+ const current = ref.startsWith('HEAD -> ');
4
+ if (ref === 'HEAD' || current) {
5
+ const target = ref.slice('HEAD -> '.length).replace(/^refs\/heads\//, '');
6
+ return { type: 'head', name: current ? 'HEAD -> ' + target : 'HEAD', isCurrent: true };
7
+ }
8
+ if (ref.startsWith('tag: ')) {
9
+ return { type: 'tag', name: ref.slice(5).replace(/^refs\/tags\//, ''), isCurrent: false };
10
+ }
11
+ if (ref.startsWith('refs/tags/')) {
12
+ return { type: 'tag', name: ref.slice('refs/tags/'.length), isCurrent: false };
13
+ }
14
+ if (ref.startsWith('refs/remotes/') || /^(origin|upstream)\//.test(ref)) {
15
+ return { type: 'remote', name: ref.replace(/^refs\/remotes\//, ''), isCurrent: false };
16
+ }
17
+ return { type: 'local', name: ref.replace(/^refs\/heads\//, ''), isCurrent: false };
18
+ });
19
+ }
20
+
21
+ export function buildGraphLayout(commits, headHash) {
22
+ const activeLanes = [];
23
+ const laneColors = [];
24
+ let nextColor = 0;
25
+ let maxLanes = 0;
26
+
27
+ function allocate(hash) {
28
+ const free = activeLanes.indexOf(null);
29
+ const lane = free === -1 ? activeLanes.length : free;
30
+ activeLanes[lane] = hash;
31
+ laneColors[lane] = nextColor++ % 8;
32
+ maxLanes = Math.max(maxLanes, lane + 1);
33
+ return lane;
34
+ }
35
+
36
+ const enrichedCommits = commits.map((commit) => {
37
+ const incoming = activeLanes.flatMap((hash, lane) => hash === commit.hash ? [lane] : []);
38
+ const lane = incoming[0] ?? allocate(commit.hash);
39
+ const colorIndex = laneColors[lane];
40
+ const mergeInEdges = incoming.slice(1).map((fromLane) => {
41
+ activeLanes[fromLane] = null;
42
+ return { fromLane, toLane: lane, colorIndex: laneColors[fromLane] };
43
+ });
44
+ const passThroughLanes = activeLanes.flatMap((hash, index) => {
45
+ return hash !== null && index !== lane ? [{ lane: index, colorIndex: laneColors[index] }] : [];
46
+ });
47
+
48
+ const outLanes = [];
49
+ const branchOutEdges = [];
50
+ const firstParent = commit.parents[0];
51
+ const existingParentLane = firstParent ? activeLanes.indexOf(firstParent) : -1;
52
+ if (firstParent && existingParentLane === -1) {
53
+ activeLanes[lane] = firstParent;
54
+ outLanes.push(lane);
55
+ } else {
56
+ activeLanes[lane] = null;
57
+ if (firstParent) {
58
+ outLanes.push(existingParentLane);
59
+ branchOutEdges.push({ fromLane: lane, toLane: existingParentLane, colorIndex });
60
+ }
61
+ }
62
+
63
+ for (const parent of commit.parents.slice(1)) {
64
+ const existing = activeLanes.indexOf(parent);
65
+ const target = existing === -1 ? allocate(parent) : existing;
66
+ if (outLanes.includes(target)) continue;
67
+ outLanes.push(target);
68
+ branchOutEdges.push({ fromLane: lane, toLane: target, colorIndex: laneColors[target] });
69
+ }
70
+
71
+ return {
72
+ ...commit,
73
+ lane, colorIndex,
74
+ isHead: commit.hash === headHash,
75
+ isMerge: commit.parents.length > 1,
76
+ parsedRefs: parseRefs(commit.refs),
77
+ // Lanes index x coordinates. Incoming edges end at the node; outgoing edges start there.
78
+ graphRow: { lane, colorIndex, inLanes: incoming, outLanes, mergeInEdges, branchOutEdges, passThroughLanes },
79
+ };
80
+ });
81
+
82
+ return { commits: enrichedCommits, maxLanes };
83
+ }
@@ -0,0 +1,50 @@
1
+ import {
2
+ createCommit, discardFile, getBranches, getCommitDetail, getCommitFileDiff, getCommitLog,
3
+ getRepoSummary, getStatus, getWorkingDiff, stageFiles, unstageFiles, validateRepo,
4
+ } from './git.mjs';
5
+ import { buildGraphLayout } from './graph.mjs';
6
+ import { addCustomRepo, discoverWorkspaces, removeCustomRepo } from './workspaces.mjs';
7
+
8
+ // Serialize writes from multiple views of the same worktree; Git retains its own index locking.
9
+ const pendingWrites = new Map();
10
+
11
+ async function writeRepo(repoPath, operation) {
12
+ const root = await validateRepo(repoPath);
13
+ const key = process.platform === 'win32' ? root.toLowerCase() : root;
14
+ const task = (pendingWrites.get(key) || Promise.resolve()).catch(() => {}).then(() => operation(root));
15
+ pendingWrites.set(key, task);
16
+ try {
17
+ return await task;
18
+ } finally {
19
+ if (pendingWrites.get(key) === task) pendingWrites.delete(key);
20
+ }
21
+ }
22
+
23
+ export function createHandlers() {
24
+ const withRepo = (action) => async (data = {}) => {
25
+ return { ok: true, ...await action(data.repoPath, data) };
26
+ };
27
+ const mutate = (action) => withRepo((repoPath, data) => writeRepo(repoPath, (root) => action(root, data)));
28
+
29
+ return {
30
+ '/api/workspaces': async () => ({ ok: true, ...await discoverWorkspaces() }),
31
+ '/api/workspaces/add': async (data = {}) => ({ ok: true, ...await addCustomRepo(data.dirPath ?? data.repoPath) }),
32
+ '/api/workspaces/remove': async (data = {}) => ({ ok: true, ...await removeCustomRepo(data.repoPath) }),
33
+ '/api/repo/state': withRepo(async (repoPath, options) => {
34
+ const [repo, branches, status, log] = await Promise.all([
35
+ getRepoSummary(repoPath), getBranches(repoPath), getStatus(repoPath), getCommitLog(repoPath, options),
36
+ ]);
37
+ return {
38
+ repo, branches, status,
39
+ ...buildGraphLayout(log.commits, log.headHash), hasMore: log.hasMore,
40
+ };
41
+ }),
42
+ '/api/repo/working-diff': withRepo(getWorkingDiff),
43
+ '/api/repo/commit-detail': withRepo(getCommitDetail),
44
+ '/api/repo/commit-file-diff': withRepo(getCommitFileDiff),
45
+ '/api/repo/stage': mutate(stageFiles),
46
+ '/api/repo/unstage': mutate(unstageFiles),
47
+ '/api/repo/discard': mutate(discardFile),
48
+ '/api/repo/commit': mutate(createCommit),
49
+ };
50
+ }