@laoyuehanni/dsh-git-worktree 0.4.11 → 0.4.13

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.
Files changed (74) hide show
  1. package/README.md +1 -1
  2. package/README.zh.md +1 -1
  3. package/lib/client.js +571 -214
  4. package/lib/git.d.ts +7 -12
  5. package/lib/git.js +70 -27
  6. package/lib/history.d.ts +15 -2
  7. package/lib/history.js +113 -27
  8. package/lib/index.d.ts +4 -0
  9. package/lib/index.js +11 -3
  10. package/lib/routes.d.ts +3 -2
  11. package/lib/routes.js +17 -2
  12. package/lib/wire.d.ts +17 -1
  13. package/lib/wire.js +2 -1
  14. package/package.json +1 -1
  15. package/lib/graph-preview/asciidoc-xKuVlNk6.js +0 -5
  16. package/lib/graph-preview/bat-Dx8nnxXE.js +0 -5
  17. package/lib/graph-preview/bibtex-BzgdqG3s.js +0 -5
  18. package/lib/graph-preview/c-BGpbtv2-.js +0 -8
  19. package/lib/graph-preview/clojure-DDsQ0FaV.js +0 -5
  20. package/lib/graph-preview/cmake-DPsCB_V6.js +0 -5
  21. package/lib/graph-preview/cpp-CBYrHpV9.js +0 -27
  22. package/lib/graph-preview/csharp-CFKaLbHg.js +0 -5
  23. package/lib/graph-preview/css-C6zsnaz5.js +0 -8
  24. package/lib/graph-preview/csv-DqIVFkK7.js +0 -5
  25. package/lib/graph-preview/dart-C6DUdjib.js +0 -5
  26. package/lib/graph-preview/diff-Blb4MjsC.js +0 -5
  27. package/lib/graph-preview/dotenv-Dkdv7Sm2.js +0 -5
  28. package/lib/graph-preview/elixir-D0Gskj1z.js +0 -8
  29. package/lib/graph-preview/erlang-BJwlUj8s.js +0 -8
  30. package/lib/graph-preview/fish-D7qAeWQz.js +0 -5
  31. package/lib/graph-preview/fsharp-MCvH12ek.js +0 -8
  32. package/lib/graph-preview/go-aXtTCanQ.js +0 -5
  33. package/lib/graph-preview/graphql-DBbDUzBC.js +0 -19
  34. package/lib/graph-preview/groovy-Bw2Ku4bU.js +0 -5
  35. package/lib/graph-preview/haskell-CfGsE1Cf.js +0 -5
  36. package/lib/graph-preview/hcl-DHg_Osgo.js +0 -5
  37. package/lib/graph-preview/html-DwZ-9Aol.js +0 -15
  38. package/lib/graph-preview/html-derivative-CdrGiVx_.js +0 -8
  39. package/lib/graph-preview/http-B769neBI.js +0 -16
  40. package/lib/graph-preview/ini-C24lZfdM.js +0 -5
  41. package/lib/graph-preview/java-B6HH4GJL.js +0 -8
  42. package/lib/graph-preview/javascript-BXA9Hfas.js +0 -5
  43. package/lib/graph-preview/julia--d6L9eAJ.js +0 -19
  44. package/lib/graph-preview/kotlin-BHE8CoV9.js +0 -5
  45. package/lib/graph-preview/latex-BsyjE6iS.js +0 -12
  46. package/lib/graph-preview/less-BzbdhFUi.js +0 -5
  47. package/lib/graph-preview/log-Dad54gsi.js +0 -5
  48. package/lib/graph-preview/lua-DL6V31K-.js +0 -10
  49. package/lib/graph-preview/make-B2ukzWs3.js +0 -5
  50. package/lib/graph-preview/markdown-CkmxmzqY.js +0 -5
  51. package/lib/graph-preview/mdx-BK9ZufRc.js +0 -5
  52. package/lib/graph-preview/nix-BRl3YduB.js +0 -9
  53. package/lib/graph-preview/perl-DJHPR3L5.js +0 -19
  54. package/lib/graph-preview/php-B74oGaLi.js +0 -21
  55. package/lib/graph-preview/powershell-DvOBVZPr.js +0 -5
  56. package/lib/graph-preview/preview.js +0 -79431
  57. package/lib/graph-preview/proto-ClkOcAW0.js +0 -5
  58. package/lib/graph-preview/python-BjnOIxPe.js +0 -5
  59. package/lib/graph-preview/r-BSNufAtJ.js +0 -8
  60. package/lib/graph-preview/rst-CDCHc-qO.js +0 -25
  61. package/lib/graph-preview/ruby-Dx4dTqam.js +0 -40
  62. package/lib/graph-preview/rust-COBzcmTx.js +0 -5
  63. package/lib/graph-preview/scala-pMGZAs9j.js +0 -5
  64. package/lib/graph-preview/scss-D2N2uO1z.js +0 -8
  65. package/lib/graph-preview/sql-DBa5L-Wg.js +0 -8
  66. package/lib/graph-preview/svelte-DQXUqa3J.js +0 -18
  67. package/lib/graph-preview/swift-DWmMn3lF.js +0 -5
  68. package/lib/graph-preview/system-verilog-DW0KSMVO.js +0 -5
  69. package/lib/graph-preview/toml-B7BHZIqX.js +0 -5
  70. package/lib/graph-preview/vb-eGVhCUXq.js +0 -5
  71. package/lib/graph-preview/verilog-Ma7yBE30.js +0 -5
  72. package/lib/graph-preview/vue-k6e1qQTO.js +0 -32
  73. package/lib/graph-preview/xml-DUa-g8pJ.js +0 -10
  74. package/lib/graph-preview/yaml-B81N8prR.js +0 -5
package/lib/git.d.ts CHANGED
@@ -73,21 +73,16 @@ export type DirExists = (path: string) => boolean;
73
73
  export declare const fsDirExists: DirExists;
74
74
  /**
75
75
  * Leftover-directory sweeper after `git worktree remove` unregisters but
76
- * fails the final rmdir (Windows EPERM when a process still has the folder
77
- * as cwd). `gone` = deleted; `empty` = still there but vacant (cwd hold);
78
- * `occupied` = still has files — the caller must not pretend removal finished.
76
+ * fails partway through deleting the tree — a Windows hold (EPERM when a
77
+ * process still has the folder as cwd) or a deep path beyond the 260-char
78
+ * limit (`Filename too long`, node_modules chains). `gone` = deleted;
79
+ * `empty` = still there but vacant (cwd hold); `occupied` = still has
80
+ * files — the caller must not pretend removal finished.
79
81
  */
80
82
  export type SweepDir = (path: string) => Promise<'gone' | 'empty' | 'occupied'>;
81
- /** Real leftover sweep: `fs.rm` with Windows EPERM retries, then classify. */
83
+ /** Real leftover sweep: `fs.rm` (extended-length on Windows) with EPERM
84
+ * retries, then classify. */
82
85
  export declare function fsSweepDir(path: string): Promise<'gone' | 'empty' | 'occupied'>;
83
- /**
84
- * Resolve a directory to repository facts, or undefined outside any git
85
- * repository (including the `git` binary missing: ENOENT surfaces as a
86
- * non-zero exit through the seam).
87
- * @param exec - executor seam.
88
- * @param path - absolute directory the workspace reports.
89
- * @param dirExists - existence seam for stale-registration filtering.
90
- */
91
86
  export declare function probeRepo(exec: Exec, path: string, dirExists?: DirExists): Promise<RepoFacts | undefined>;
92
87
  /**
93
88
  * Resolve a branch display name against the authoritative branch list of the
package/lib/git.js CHANGED
@@ -146,12 +146,27 @@ async function gitMaybe(exec, cwd, args) {
146
146
  }
147
147
  /** Real existence check. */
148
148
  export const fsDirExists = path => existsSync(path);
149
- /** Real leftover sweep: `fs.rm` with Windows EPERM retries, then classify. */
149
+ /**
150
+ * Windows extended-length form (`\\?\…`) of a path: the prefix skips the
151
+ * 260-char normalization that makes deep node_modules chains unlink-fail —
152
+ * exactly the shape `git worktree remove` gave up on. POSIX paths and
153
+ * already extended paths pass through.
154
+ */
155
+ function asExtendedLengthPath(path) {
156
+ if (process.platform !== 'win32')
157
+ return path;
158
+ const abs = resolve(path);
159
+ if (abs.startsWith('\\\\?\\'))
160
+ return abs;
161
+ return abs.startsWith('\\\\') ? `\\\\?\\UNC${abs.slice(1)}` : `\\\\?\\${abs}`;
162
+ }
163
+ /** Real leftover sweep: `fs.rm` (extended-length on Windows) with EPERM
164
+ * retries, then classify. */
150
165
  export async function fsSweepDir(path) {
151
166
  if (!existsSync(path))
152
167
  return 'gone';
153
168
  try {
154
- await rm(path, { recursive: true, force: true, maxRetries: 8, retryDelay: 100 });
169
+ await rm(asExtendedLengthPath(path), { recursive: true, force: true, maxRetries: 8, retryDelay: 100 });
155
170
  }
156
171
  catch {
157
172
  // Retries exhausted; classify whatever is still on disk.
@@ -165,13 +180,15 @@ export async function fsSweepDir(path) {
165
180
  return 'occupied';
166
181
  }
167
182
  }
168
- /** stderr of a git rmdir that lost to an OS file lock (not git's dirty check). */
183
+ /** stderr of a git rmdir that lost to the OS (not git's dirty check): an
184
+ * open handle on the tree, or a deep path past the 260-char limit. */
169
185
  function isDirBusyGitError(error) {
170
186
  const text = error.stderr;
171
187
  return /permission denied/i.test(text)
172
188
  || /\bEPERM\b/i.test(text)
173
189
  || /\bEACCES\b/i.test(text)
174
- || /\bEBUSY\b/i.test(text);
190
+ || /\bEBUSY\b/i.test(text)
191
+ || /filename too long/i.test(text);
175
192
  }
176
193
  /**
177
194
  * Whether a directory IS the main worktree of its repository: exactly when
@@ -213,43 +230,49 @@ function isMainWorktree(toplevel, gitDir) {
213
230
  * @param path - absolute directory the workspace reports.
214
231
  * @param dirExists - existence seam for stale-registration filtering.
215
232
  */
233
+ /** One process for the three facts both probes need. On Windows each git
234
+ * spawn costs tens of milliseconds before it does any work, so folding
235
+ * these flags is the difference between one round trip and three. */
236
+ const REV_PARSE_FACTS = ['rev-parse', '--show-toplevel', '--git-common-dir', '--abbrev-ref', 'HEAD'];
216
237
  export async function probeRepo(exec, path, dirExists = fsDirExists) {
217
- const top = await gitMaybe(exec, path, ['rev-parse', '--show-toplevel']);
218
- if (top === undefined)
238
+ const probed = await gitMaybe(exec, path, REV_PARSE_FACTS);
239
+ if (probed === undefined)
240
+ return undefined;
241
+ const [top = '', common = '', branchName = ''] = probed.split('\n').map(line => line.trim());
242
+ if (top === '' || common === '')
219
243
  return undefined;
220
- const commonDir = await gitMaybe(exec, path, ['rev-parse', '--git-common-dir']);
221
244
  // repoName comes from the shared .git location: a linked worktree's own
222
245
  // toplevel would name the branch folder, not the repository. Both git
223
246
  // outputs carry forward slashes on Windows — normalize every derived path.
224
- const toplevel = normalize(top.trim());
225
- const gitDir = commonDir !== undefined && commonDir.trim() !== ''
226
- ? normalize(resolve(path, commonDir.trim()))
227
- : resolve(toplevel, '.git');
247
+ const toplevel = normalize(top);
248
+ const gitDir = normalize(resolve(path, common));
228
249
  // Main worktree, not the queried directory: a linked worktree's
229
250
  // `--show-toplevel` is its own folder, which `git worktree remove` then
230
251
  // destroys (including `.git`). Later `worktree list` / `worktree prune`
231
252
  // must still run in a living git dir — the shared checkout
232
253
  // (`dirname(--git-common-dir)`), same grouping key as probeWorkspaceGit.
233
254
  const repoRoot = dirname(gitDir);
255
+ // Branch list and worktree list do not depend on each other. listBranches
256
+ // itself overlaps the local and remote ref walks.
257
+ const [branches, worktrees] = await Promise.all([
258
+ listBranches(exec, repoRoot),
259
+ listWorktrees(exec, repoRoot),
260
+ ]);
234
261
  return {
235
262
  repoRoot,
236
263
  repoName: basename(dirname(gitDir)),
237
264
  toplevel,
238
265
  main: isMainWorktree(toplevel, gitDir),
239
- currentBranch: await currentBranch(exec, path),
240
- branches: await listBranches(exec, repoRoot),
266
+ // `--abbrev-ref HEAD` prints the synthetic `HEAD` when detached or unborn,
267
+ // which is the same answer an empty `branch --show-current` used to map to.
268
+ currentBranch: branchName === '' || branchName === 'HEAD' ? 'HEAD' : branchName,
269
+ branches,
241
270
  // A stale registration (directory removed behind git's back) must not
242
271
  // reach the UI as a real worktree — it would disable branch rows for a
243
272
  // folder that no longer exists.
244
- worktrees: (await listWorktrees(exec, repoRoot)).filter(w => dirExists(w.path)),
273
+ worktrees: worktrees.filter(w => dirExists(w.path)),
245
274
  };
246
275
  }
247
- /** Currently checked-out branch of a directory; `HEAD` when detached or unborn. */
248
- async function currentBranch(exec, cwd) {
249
- const name = await gitMaybe(exec, cwd, ['branch', '--show-current']);
250
- const trimmed = name?.trim() ?? '';
251
- return trimmed === '' ? 'HEAD' : trimmed;
252
- }
253
276
  /**
254
277
  * Local branches (each carrying its ahead/behind vs the upstream when one
255
278
  * exists) plus remote-only branches across EVERY remote (`<remote>/HEAD`
@@ -260,7 +283,10 @@ async function currentBranch(exec, cwd) {
260
283
  * UI distinguish unpublished branches from synchronized and deleted ones.
261
284
  */
262
285
  async function listBranches(exec, repoRoot) {
263
- const localOut = await git(exec, repoRoot, ['for-each-ref', 'refs/heads', '--format=%(refname:short)%(upstream:track)%09%(upstream:short)']);
286
+ const [localOut, remoteOut] = await Promise.all([
287
+ git(exec, repoRoot, ['for-each-ref', 'refs/heads', '--format=%(refname:short)%(upstream:track)%09%(upstream:short)']),
288
+ gitMaybe(exec, repoRoot, ['for-each-ref', 'refs/remotes', '--format=%(refname:short)']),
289
+ ]);
264
290
  const entries = [];
265
291
  for (const line of localOut.split('\n')) {
266
292
  const [label = '', upstream = ''] = line.split('\t');
@@ -285,7 +311,6 @@ async function listBranches(exec, repoRoot) {
285
311
  entry.behind = Number(behind[1]);
286
312
  entries.push(entry);
287
313
  }
288
- const remoteOut = await gitMaybe(exec, repoRoot, ['for-each-ref', 'refs/remotes', '--format=%(refname:short)']);
289
314
  if (remoteOut !== undefined) {
290
315
  // Local names as a Set: the twin lookup runs once per remote row, and a
291
316
  // linear scan over the assembled list would make the loop quadratic —
@@ -570,8 +595,11 @@ export async function fetchAll(exec, repoRoot, live) {
570
595
  throw new CancelledError();
571
596
  if (result.code !== 0) {
572
597
  failure ??= { code: result.code, messages: [] };
573
- // git's words without the thousand progress redraws before them.
574
- failure.messages.push(stripProgress(result.stderr));
598
+ // git's words without the thousand progress redraws before them, and
599
+ // under a head that names the remote and its address: `git fetch --all`
600
+ // itself reports neither, and a remote whose address was moved out
601
+ // from under it is the failure the user must act on.
602
+ failure.messages.push(`remote "${remote}" (url: ${await remoteUrl(exec, repoRoot, remote)})\n${stripProgress(result.stderr)}`);
575
603
  }
576
604
  }
577
605
  // The error names the command the user knows, not the per-remote plumbing.
@@ -580,6 +608,19 @@ export async function fetchAll(exec, repoRoot, live) {
580
608
  }
581
609
  /** The fetch every plain sync runs. */
582
610
  const FETCH_ARGS = ['fetch', '--all', '--prune'];
611
+ /**
612
+ * The address one remote points at. Read only after that remote's fetch
613
+ * failed: the address is the one fact the failure message needs, and a
614
+ * healthy fetch never pays for it.
615
+ * @param exec - executor seam.
616
+ * @param repoRoot - main worktree directory.
617
+ * @param remote - remote name.
618
+ * @returns the remote's address, or an empty string when git cannot say.
619
+ */
620
+ async function remoteUrl(exec, repoRoot, remote) {
621
+ const url = await gitMaybe(exec, repoRoot, ['remote', 'get-url', remote]);
622
+ return url?.trim() ?? '';
623
+ }
583
624
  /**
584
625
  * The remotes `git fetch --all` would visit: all of them except those marked
585
626
  * `remote.<name>.skipFetchAll` — a live run walks them itself.
@@ -711,8 +752,10 @@ export async function removeWorktree(exec, repoRoot, worktreePath, force, dirExi
711
752
  }
712
753
  catch (error) {
713
754
  // Windows: git often unregisters the worktree and empties the tree,
714
- // then fails the last rmdir (`Permission denied`) because some process
715
- // still has the folder as cwd. `--force` does not help — that flag only
755
+ // then fails a deletion — the last rmdir lost to an open handle
756
+ // (`Permission denied`, a process holding the folder as cwd), or an
757
+ // unlink hit a deep path past the 260-char limit (`Filename too long`,
758
+ // node_modules chains). `--force` does not help — that flag only
716
759
  // bypasses dirty/lock checks, not OS handles. Relist from `repoRoot`
717
760
  // (the main checkout, which still has `.git`); listing from the target
718
761
  // path would throw "not a git repository" once git has stripped its
@@ -762,7 +805,7 @@ export async function removeWorktree(exec, repoRoot, worktreePath, force, dirExi
762
805
  * binary surfaces the same way — a non-zero exit through the seam).
763
806
  */
764
807
  export async function probeWorkspaceGit(exec, path) {
765
- const out = await gitMaybe(exec, path, ['rev-parse', '--show-toplevel', '--git-common-dir', '--abbrev-ref', 'HEAD']);
808
+ const out = await gitMaybe(exec, path, REV_PARSE_FACTS);
766
809
  if (out === undefined)
767
810
  return undefined;
768
811
  const lines = out.split('\n').map(line => line.trim());
package/lib/history.d.ts CHANGED
@@ -1,7 +1,20 @@
1
1
  import { type Exec } from './git.js';
2
- import type { CommitDetail, CommitHistory } from './wire.js';
2
+ import type { AuthorList, CommitDetail, CommitHistory } from './wire.js';
3
3
  export declare const HISTORY_PAGE_SIZE = 100;
4
+ /** Drops cached author lists. Tests use this so one file cannot leak into the next. */
5
+ export declare function resetAuthorCache(): void;
6
+ /** Drop one repository's author lists. An in-flight walk started earlier
7
+ * still finishes for its caller, but it does not refill the cache. */
8
+ export declare function invalidateAuthorCache(cwd: string): void;
9
+ /** Every author name reachable from the branch, not only the loaded page.
10
+ * The same repository path and tip reuse one in-memory list and share one in-flight walk.
11
+ * `fresh` drops that repository's lists first: fetch, update, and an explicit reload
12
+ * pass it because a branch ref can move, or a shallow history can grow, without the
13
+ * caller knowing the previous tip is stale. */
14
+ export declare function readAuthors(exec: Exec, cwd: string, ref: string, tip?: string, fresh?: boolean): Promise<AuthorList>;
4
15
  /** Resolve only an explicit branch ref or HEAD, then use immutable OIDs for paging. */
5
16
  export declare function readHistory(exec: Exec, cwd: string, ref: string, tip?: string, offset?: number): Promise<CommitHistory>;
6
- /** No patches in this response; even a large commit only exposes one file name. */
17
+ /** No patches in this response; even a large commit only exposes one file name.
18
+ * Metadata and first-parent numstat come from one `git show`: a second
19
+ * process was another full spawn on top of a diff that show already computed. */
7
20
  export declare function readCommit(exec: Exec, cwd: string, oid: string): Promise<CommitDetail>;
package/lib/history.js CHANGED
@@ -1,7 +1,30 @@
1
1
  import { GitError } from './git.js';
2
2
  export const HISTORY_PAGE_SIZE = 100;
3
+ /** Distinct author lists kept per repository path and pinned tip. */
4
+ const AUTHOR_CACHE_LIMIT = 32;
3
5
  const FORMAT = '%H%x00%P%x00%an%x00%aI%x00%s';
4
6
  const OID = /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/;
7
+ const authorCache = new Map();
8
+ const authorInflight = new Map();
9
+ const authorEpochs = new Map();
10
+ /** Drops cached author lists. Tests use this so one file cannot leak into the next. */
11
+ export function resetAuthorCache() {
12
+ authorCache.clear();
13
+ authorInflight.clear();
14
+ authorEpochs.clear();
15
+ }
16
+ /** Drop one repository's author lists. An in-flight walk started earlier
17
+ * still finishes for its caller, but it does not refill the cache. */
18
+ export function invalidateAuthorCache(cwd) {
19
+ const prefix = `${cwd}\0`;
20
+ for (const key of authorCache.keys())
21
+ if (key.startsWith(prefix))
22
+ authorCache.delete(key);
23
+ for (const key of authorInflight.keys())
24
+ if (key.startsWith(prefix))
25
+ authorInflight.delete(key);
26
+ authorEpochs.set(cwd, (authorEpochs.get(cwd) ?? 0) + 1);
27
+ }
5
28
  async function run(exec, cwd, args) {
6
29
  const result = await exec('git', args, { cwd, nonInteractive: true });
7
30
  if (result.code !== 0)
@@ -12,30 +35,92 @@ function commit(fields) {
12
35
  const [oid = '', parents = '', author = '', date = '', subject = ''] = fields;
13
36
  return { oid, parents: parents.split(' ').filter(Boolean), author, date, subject };
14
37
  }
15
- /** Resolve only an explicit branch ref or HEAD, then use immutable OIDs for paging. */
16
- export async function readHistory(exec, cwd, ref, tip, offset = 0) {
38
+ /** Explicit branch ref or HEAD, pinned to an immutable commit once known. Null is an unborn branch. */
39
+ async function resolveHistoryTip(exec, cwd, ref, tip) {
17
40
  if (ref !== 'HEAD' && !/^refs\/(heads|remotes)\/.+/.test(ref))
18
41
  throw new Error('An explicit branch ref is required');
19
42
  if (tip !== undefined && !OID.test(tip))
20
43
  throw new Error('Invalid history tip');
44
+ if (tip !== undefined) {
45
+ if (ref !== 'HEAD')
46
+ await run(exec, cwd, ['check-ref-format', ref]);
47
+ return tip;
48
+ }
49
+ // Validating the ref and resolving it do not depend on each other. On
50
+ // Windows the spawn itself is most of a local call, so they share one round.
51
+ const format = ref === 'HEAD' ? Promise.resolve('') : run(exec, cwd, ['check-ref-format', ref]);
52
+ const pending = exec('git', ['rev-parse', '--verify', '--end-of-options', `${ref}^{commit}`], { cwd, nonInteractive: true });
53
+ const [, result] = await Promise.all([format, pending]);
54
+ if (result.code !== 0) {
55
+ // An unborn current branch is a useful empty, other missing refs are errors.
56
+ const head = await run(exec, cwd, ['symbolic-ref', '-q', 'HEAD']).catch(() => '');
57
+ if (head.trim() && (ref === 'HEAD' || ref === head.trim()))
58
+ return null;
59
+ throw new GitError(['rev-parse', ref], result.code, result.stderr);
60
+ }
61
+ const resolved = result.stdout.trim();
62
+ if (!OID.test(resolved))
63
+ throw new Error('Invalid resolved history tip');
64
+ return resolved;
65
+ }
66
+ function rememberAuthors(key, authors) {
67
+ authorCache.delete(key);
68
+ authorCache.set(key, authors);
69
+ while (authorCache.size > AUTHOR_CACHE_LIMIT) {
70
+ const oldest = authorCache.keys().next().value;
71
+ if (oldest === undefined)
72
+ break;
73
+ authorCache.delete(oldest);
74
+ }
75
+ return authors;
76
+ }
77
+ /** Every author name reachable from the branch, not only the loaded page.
78
+ * The same repository path and tip reuse one in-memory list and share one in-flight walk.
79
+ * `fresh` drops that repository's lists first: fetch, update, and an explicit reload
80
+ * pass it because a branch ref can move, or a shallow history can grow, without the
81
+ * caller knowing the previous tip is stale. */
82
+ export async function readAuthors(exec, cwd, ref, tip, fresh = false) {
83
+ const resolved = await resolveHistoryTip(exec, cwd, ref, tip);
84
+ if (resolved === null)
85
+ return { tip: null, authors: [] };
86
+ if (fresh)
87
+ invalidateAuthorCache(cwd);
88
+ const key = `${cwd}\0${resolved}`;
89
+ const epoch = authorEpochs.get(cwd) ?? 0;
90
+ const cached = authorCache.get(key);
91
+ if (cached)
92
+ return { tip: resolved, authors: rememberAuthors(key, cached) };
93
+ let pending = authorInflight.get(key);
94
+ if (!pending) {
95
+ let current;
96
+ current = run(exec, cwd, ['log', '-z', '--no-show-signature', '--encoding=UTF-8', '--format=%an', resolved, '--']).then(out => {
97
+ const names = new Set();
98
+ for (const name of out.split('\0'))
99
+ if (name)
100
+ names.add(name);
101
+ const sorted = [...names].sort((a, b) => a.localeCompare(b));
102
+ if (authorInflight.get(key) === current)
103
+ authorInflight.delete(key);
104
+ if ((authorEpochs.get(cwd) ?? 0) !== epoch)
105
+ return sorted;
106
+ return rememberAuthors(key, sorted);
107
+ }, error => {
108
+ if (authorInflight.get(key) === current)
109
+ authorInflight.delete(key);
110
+ throw error;
111
+ });
112
+ pending = current;
113
+ authorInflight.set(key, pending);
114
+ }
115
+ return { tip: resolved, authors: await pending };
116
+ }
117
+ /** Resolve only an explicit branch ref or HEAD, then use immutable OIDs for paging. */
118
+ export async function readHistory(exec, cwd, ref, tip, offset = 0) {
21
119
  if (!Number.isSafeInteger(offset) || offset < 0 || offset > 1_000_000)
22
120
  throw new Error('Invalid history offset');
23
- if (ref !== 'HEAD')
24
- await run(exec, cwd, ['check-ref-format', ref]);
25
- let resolved = tip;
26
- if (resolved === undefined) {
27
- const result = await exec('git', ['rev-parse', '--verify', '--end-of-options', `${ref}^{commit}`], { cwd, nonInteractive: true });
28
- if (result.code !== 0) {
29
- // An unborn current branch is a useful empty, other missing refs are errors.
30
- const head = await run(exec, cwd, ['symbolic-ref', '-q', 'HEAD']).catch(() => '');
31
- if (head.trim() && (ref === 'HEAD' || ref === head.trim()))
32
- return { tip: null, commits: [], next: null };
33
- throw new GitError(['rev-parse', ref], result.code, result.stderr);
34
- }
35
- resolved = result.stdout.trim();
36
- if (!OID.test(resolved))
37
- throw new Error('Invalid resolved history tip');
38
- }
121
+ const resolved = await resolveHistoryTip(exec, cwd, ref, tip);
122
+ if (resolved === null)
123
+ return { tip: null, commits: [], next: null };
39
124
  const out = await run(exec, cwd, ['log', '--topo-order', '--no-show-signature', '--encoding=UTF-8', '-z', `--format=${FORMAT}`,
40
125
  `--max-count=${HISTORY_PAGE_SIZE + 1}`, `--skip=${offset}`, resolved, '--']);
41
126
  const fields = out.split('\0');
@@ -47,23 +132,24 @@ export async function readHistory(exec, cwd, ref, tip, offset = 0) {
47
132
  const more = commits.length > HISTORY_PAGE_SIZE;
48
133
  return { tip: resolved, commits: commits.slice(0, HISTORY_PAGE_SIZE), next: more ? offset + HISTORY_PAGE_SIZE : null };
49
134
  }
50
- /** No patches in this response; even a large commit only exposes one file name. */
135
+ /** No patches in this response; even a large commit only exposes one file name.
136
+ * Metadata and first-parent numstat come from one `git show`: a second
137
+ * process was another full spawn on top of a diff that show already computed. */
51
138
  export async function readCommit(exec, cwd, oid) {
52
139
  if (!OID.test(oid))
53
140
  throw new Error('Invalid commit OID');
54
- const out = await run(exec, cwd, ['show', '-s', '--no-show-signature', '--encoding=UTF-8', `--format=${FORMAT}%x00%b`, oid, '--']);
141
+ const out = await run(exec, cwd, ['show', '--first-parent', '--no-show-signature', '--encoding=UTF-8', '--numstat', '--no-renames', '--no-relative', `--format=${FORMAT}%x00%b`, '-z', oid, '--']);
55
142
  const fields = out.split('\0');
56
143
  const info = commit(fields);
57
- const parent = info.parents[0];
58
- const stats = await run(exec, cwd, parent === undefined
59
- ? ['diff-tree', '--root', '--no-commit-id', '-r', '--numstat', '--no-renames', '--no-relative', '-z', oid, '--']
60
- : ['diff', '--numstat', '--no-renames', '--no-relative', '-z', parent, oid, '--']);
61
144
  let files = 0, added = 0, removed = 0, binaryFiles = 0;
62
145
  let firstFile = null;
63
- for (const entry of stats.split('\0')) {
64
- if (!entry)
146
+ // The format record ends at the body. Numstat rows follow, each NUL-terminated,
147
+ // with a leading newline on the first row where show separates the message.
148
+ for (const entry of fields.slice(6)) {
149
+ const text = entry.replace(/^\n/, '');
150
+ if (!text)
65
151
  continue;
66
- const match = /^(\d+|-)\t(\d+|-)\t([\s\S]+)$/.exec(entry);
152
+ const match = /^(\d+|-)\t(\d+|-)\t([\s\S]+)$/.exec(text);
67
153
  if (!match)
68
154
  continue;
69
155
  files++;
package/lib/index.d.ts CHANGED
@@ -17,6 +17,8 @@ export interface Config {
17
17
  /** Fetch every remote before creating a worktree; absent = off. A failed
18
18
  * fetch never blocks the creation (see the /worktree route). */
19
19
  fetchBeforeCreate?: Volatile<boolean> | boolean;
20
+ /** Open the commit graph when the composer branch button is clicked; absent = off. */
21
+ openGraphByDefault?: Volatile<boolean> | boolean;
20
22
  /** Prune stale worktrees lazily after each creation; absent = off. */
21
23
  autoPruneWorktrees?: Volatile<boolean> | boolean;
22
24
  /** Global cap the lazy prune trims down to (valid git worktrees only);
@@ -54,6 +56,8 @@ export interface SectionConfig {
54
56
  groupSidebar?: boolean;
55
57
  /** Fetch every remote before creating a worktree; absent = off. */
56
58
  fetchBeforeCreate?: boolean;
59
+ /** Open the commit graph from the composer branch button; absent = off. */
60
+ openGraphByDefault?: boolean;
57
61
  /** Prune stale worktrees lazily after each creation; absent = off. */
58
62
  autoPruneWorktrees?: boolean;
59
63
  /** Global cap the lazy prune trims down to; absent = 30. */
package/lib/index.js CHANGED
@@ -10,8 +10,8 @@ import z from '@deepseek-ai/schemastery';
10
10
  import { childProcessExec } from './git.js';
11
11
  import { handleCreateBranch, handleCreateWorktree, handleDeleteBranch, handleEnsureDirectory, handleFetch, handleGroupWorktrees, handleHead, handleInspectWorktree, handlePathExists, handlePush, handlePushPlan, handlePushPreview, handlePurgeDirectory, handleRemoveWorktree, handleRenameBranch, handleStatus, handleSwitch, handleUpdate, handleWorktreesAll, } from './routes.js';
12
12
  import { validateRootDir } from './settings.js';
13
- import { handleHistory, handleCommit } from './routes.js';
14
- import { ROUTE_HISTORY, ROUTE_COMMIT } from './wire.js';
13
+ import { handleAuthors, handleHistory, handleCommit } from './routes.js';
14
+ import { ROUTE_AUTHORS, ROUTE_HISTORY, ROUTE_COMMIT } from './wire.js';
15
15
  import { streamRoute } from './stream.js';
16
16
  import { ROUTE_BRANCH, ROUTE_BRANCH_DELETE, ROUTE_BRANCH_RENAME, ROUTE_ENSURE_DIRECTORY, ROUTE_EXISTS, ROUTE_FETCH, ROUTE_GROUP, ROUTE_HEAD, ROUTE_INSPECT, ROUTE_PUSH, ROUTE_PUSH_PLAN, ROUTE_PUSH_PREVIEW, ROUTE_PURGE, ROUTE_REMOVE, ROUTE_STATUS, ROUTE_SWITCH, ROUTE_UPDATE, ROUTE_WORKTREE, ROUTE_WORKTREES_ALL } from './wire.js';
17
17
  export const name = 'dsh-git-worktree';
@@ -37,13 +37,14 @@ export const Config = z.object({
37
37
  rootDir: z.string().volatile(),
38
38
  groupSidebar: z.boolean().default(true).volatile(),
39
39
  fetchBeforeCreate: z.boolean().default(false).volatile(),
40
+ openGraphByDefault: z.boolean().default(false).volatile(),
40
41
  autoPruneWorktrees: z.boolean().default(false).volatile(),
41
42
  keepWorktrees: z.number().default(KEEP_WORKTREES_DEFAULT).volatile(),
42
43
  postCreateCopyFiles: z.array(z.string()).default([]).volatile(),
43
44
  });
44
45
  /** Reject stale or misspelled config keys before defaults can hide them. */
45
46
  export function validateConfig(config) {
46
- const unknown = Object.keys(config).find(key => key !== 'rootDir' && key !== 'groupSidebar' && key !== 'fetchBeforeCreate' && key !== 'autoPruneWorktrees' && key !== 'keepWorktrees' && key !== 'postCreateCopyFiles');
47
+ const unknown = Object.keys(config).find(key => key !== 'rootDir' && key !== 'groupSidebar' && key !== 'fetchBeforeCreate' && key !== 'openGraphByDefault' && key !== 'autoPruneWorktrees' && key !== 'keepWorktrees' && key !== 'postCreateCopyFiles');
47
48
  if (unknown !== undefined) {
48
49
  throw new Error(`GitWorktreeConfig: unknown key "${unknown}"`);
49
50
  }
@@ -59,6 +60,10 @@ export function validateConfig(config) {
59
60
  if (fetchBeforeCreate !== undefined && typeof fetchBeforeCreate !== 'boolean') {
60
61
  throw new Error('GitWorktreeConfig: "fetchBeforeCreate" must be a boolean');
61
62
  }
63
+ const openGraphByDefault = readVolatile(config.openGraphByDefault);
64
+ if (openGraphByDefault !== undefined && typeof openGraphByDefault !== 'boolean') {
65
+ throw new Error('GitWorktreeConfig: "openGraphByDefault" must be a boolean');
66
+ }
62
67
  const autoPruneWorktrees = readVolatile(config.autoPruneWorktrees);
63
68
  if (autoPruneWorktrees !== undefined && typeof autoPruneWorktrees !== 'boolean') {
64
69
  throw new Error('GitWorktreeConfig: "autoPruneWorktrees" must be a boolean');
@@ -95,6 +100,7 @@ export function sectionOf(config) {
95
100
  const postCreateCopyFiles = readVolatile(config.postCreateCopyFiles);
96
101
  const groupSidebar = readVolatile(config.groupSidebar);
97
102
  const fetchBeforeCreate = readVolatile(config.fetchBeforeCreate);
103
+ const openGraphByDefault = readVolatile(config.openGraphByDefault);
98
104
  const autoPruneWorktrees = readVolatile(config.autoPruneWorktrees);
99
105
  const keepWorktrees = readVolatile(config.keepWorktrees);
100
106
  return {
@@ -104,6 +110,7 @@ export function sectionOf(config) {
104
110
  // unset can always fall back to them.
105
111
  groupSidebar: groupSidebar ?? true,
106
112
  fetchBeforeCreate: fetchBeforeCreate ?? false,
113
+ openGraphByDefault: openGraphByDefault ?? false,
107
114
  autoPruneWorktrees: autoPruneWorktrees ?? false,
108
115
  keepWorktrees: keepWorktrees ?? KEEP_WORKTREES_DEFAULT,
109
116
  };
@@ -206,6 +213,7 @@ export function apply(ctx, config = {}) {
206
213
  } }), 'git-worktree: head route');
207
214
  postRoute(ROUTE_WORKTREE, 'worktree', handleCreateWorktree);
208
215
  postRoute(ROUTE_HISTORY, 'history', handleHistory);
216
+ postRoute(ROUTE_AUTHORS, 'authors', handleAuthors);
209
217
  postRoute(ROUTE_COMMIT, 'commit', handleCommit);
210
218
  postRoute(ROUTE_SWITCH, 'switch', handleSwitch);
211
219
  postRoute(ROUTE_BRANCH, 'branch', handleCreateBranch);
package/lib/routes.d.ts CHANGED
@@ -4,7 +4,7 @@
4
4
  */
5
5
  import { type CopyFilesSeams } from './copy-files.js';
6
6
  import { type DirExists, type ExcludeSeams, type Exec } from './git.js';
7
- import type { CommitHistory, CommitDetail } from './wire.js';
7
+ import type { AuthorList, CommitHistory, CommitDetail } from './wire.js';
8
8
  import type { CreateBranchResult, CreateWorktreeResult, EnsureDirectoryResult, FetchResult, GroupWorkspacesResult, HeadStatus, InspectWorktreeResult, PathExistsResult, PushPlan, PushPreview, PushResult, PurgeDirectoryResult, RemoveWorktreeResult, RepoStatus, RouteError, SwitchResult, SyncEvent, UpdateResult, WorktreesAllResult } from './wire.js';
9
9
  /** Everything the handlers need from the host half. */
10
10
  export interface RouteDeps {
@@ -47,7 +47,7 @@ export declare function fsMkdirRecursive(path: string): Promise<void>;
47
47
  /** One route outcome: HTTP status plus the JSON body. */
48
48
  export interface RouteOutcome {
49
49
  status: number;
50
- body: CommitHistory | CommitDetail | PushPlan | PushPreview | PushResult | RepoStatus | HeadStatus | CreateWorktreeResult | SwitchResult | CreateBranchResult | FetchResult | UpdateResult | GroupWorkspacesResult | InspectWorktreeResult | RemoveWorktreeResult | PathExistsResult | EnsureDirectoryResult | WorktreesAllResult | PurgeDirectoryResult | RouteError;
50
+ body: AuthorList | CommitHistory | CommitDetail | PushPlan | PushPreview | PushResult | RepoStatus | HeadStatus | CreateWorktreeResult | SwitchResult | CreateBranchResult | FetchResult | UpdateResult | GroupWorkspacesResult | InspectWorktreeResult | RemoveWorktreeResult | PathExistsResult | EnsureDirectoryResult | WorktreesAllResult | PurgeDirectoryResult | RouteError;
51
51
  }
52
52
  /**
53
53
  * POST /group — git belonging facts for a batch of workspace directories.
@@ -112,6 +112,7 @@ export declare function handleStatus(deps: RouteDeps, path: string | undefined):
112
112
  */
113
113
  export declare function handleHead(path: string | undefined): Promise<RouteOutcome>;
114
114
  export declare function handleHistory(deps: RouteDeps, body: unknown): Promise<RouteOutcome>;
115
+ export declare function handleAuthors(deps: RouteDeps, body: unknown): Promise<RouteOutcome>;
115
116
  export declare function handleCommit(deps: RouteDeps, body: unknown): Promise<RouteOutcome>;
116
117
  /**
117
118
  * POST /worktree — create or reuse the worktree for a branch, then report the
package/lib/routes.js CHANGED
@@ -7,7 +7,7 @@ import { mkdir, readdir, rm, stat } from 'node:fs/promises';
7
7
  import { runPostCreateCopy } from './copy-files.js';
8
8
  import { appendWorktreeExclude, fsExcludeSeams, CancelledError, GitError, addWorktree, addWorktreeCutout, createBranch, cutoutBranchName, deleteBranch, fetchAll, fsDirExists, inspectWorktree, isAbsoluteDir, probeRepo, probeWorkspaceGit, removeWorktree, renameBranch, resolveBranch, switchBranch, updateBranch } from './git.js';
9
9
  import { readCheckedOutBranch } from './head.js';
10
- import { readHistory, readCommit } from './history.js';
10
+ import { invalidateAuthorCache, readAuthors, readHistory, readCommit } from './history.js';
11
11
  import { openPush, previewPush, pushBranch } from './push.js';
12
12
  import { isAbsoluteConfigPath, sanitizeBranchDir } from './normalize.js';
13
13
  import { createProgressReader } from './progress.js';
@@ -378,7 +378,7 @@ function isOutcome(value) {
378
378
  return typeof value === 'object' && value !== null && 'status' in value && 'body' in value;
379
379
  }
380
380
  export async function handleHistory(deps, body) {
381
- const parsed = readBody(body, ['repoPath', 'ref'], [], ['tip', 'offset']);
381
+ const parsed = readBody(body, ['repoPath', 'ref'], ['freshAuthors'], ['tip', 'offset']);
382
382
  if (isOutcome(parsed))
383
383
  return parsed;
384
384
  if (!isAbsoluteDir(parsed.repoPath))
@@ -386,12 +386,27 @@ export async function handleHistory(deps, body) {
386
386
  if (parsed.offset !== undefined && !/^\d+$/.test(parsed.offset))
387
387
  return fail(400, 'Invalid history offset');
388
388
  try {
389
+ if (parsed.freshAuthors === true)
390
+ invalidateAuthorCache(parsed.repoPath);
389
391
  return { status: 200, body: await readHistory(deps.exec, parsed.repoPath, parsed.ref, parsed.tip, Number(parsed.offset ?? 0)) };
390
392
  }
391
393
  catch (error) {
392
394
  return fail(400, error instanceof Error ? error.message : String(error));
393
395
  }
394
396
  }
397
+ export async function handleAuthors(deps, body) {
398
+ const parsed = readBody(body, ['repoPath', 'ref'], ['fresh'], ['tip']);
399
+ if (isOutcome(parsed))
400
+ return parsed;
401
+ if (!isAbsoluteDir(parsed.repoPath))
402
+ return fail(400, '"repoPath" must be an absolute directory');
403
+ try {
404
+ return { status: 200, body: await readAuthors(deps.exec, parsed.repoPath, parsed.ref, parsed.tip, parsed.fresh === true) };
405
+ }
406
+ catch (error) {
407
+ return fail(400, error instanceof Error ? error.message : String(error));
408
+ }
409
+ }
395
410
  export async function handleCommit(deps, body) {
396
411
  const parsed = readBody(body, ['repoPath', 'oid']);
397
412
  if (isOutcome(parsed))
package/lib/wire.d.ts CHANGED
@@ -11,8 +11,9 @@ export declare const ROUTE_STATUS = "/plugin/git-worktree/status";
11
11
  /** GET ROUTE_PREFIX/head?path=<absolute dir> — checked-out branch only.
12
12
  * A file read of HEAD, not a git process. */
13
13
  export declare const ROUTE_HEAD = "/plugin/git-worktree/head";
14
- /** Read-only POSTs: bounded history and one commit's full message/summary. */
14
+ /** Read-only POSTs: bounded history, every author on that history, and one commit's full message/summary. */
15
15
  export declare const ROUTE_HISTORY = "/plugin/git-worktree/history";
16
+ export declare const ROUTE_AUTHORS = "/plugin/git-worktree/authors";
16
17
  export declare const ROUTE_COMMIT = "/plugin/git-worktree/commit";
17
18
  export interface HistoryBody {
18
19
  repoPath: string;
@@ -21,6 +22,8 @@ export interface HistoryBody {
21
22
  /** Subsequent pages stay pinned to the first response's tip. */
22
23
  tip?: string;
23
24
  offset?: string;
25
+ /** The branch moved or the user reloaded: drop cached author lists for this repository. */
26
+ freshAuthors?: boolean;
24
27
  }
25
28
  export interface HistoryCommit {
26
29
  oid: string;
@@ -34,6 +37,19 @@ export interface CommitHistory {
34
37
  commits: HistoryCommit[];
35
38
  next: number | null;
36
39
  }
40
+ /** Distinct `%an` names reachable from a branch tip. */
41
+ export interface AuthorsBody {
42
+ repoPath: string;
43
+ ref: string;
44
+ /** Pins the list to the history response's tip. */
45
+ tip?: string;
46
+ /** Drop this repository's cached author lists and walk again. */
47
+ fresh?: boolean;
48
+ }
49
+ export interface AuthorList {
50
+ tip: string | null;
51
+ authors: readonly string[];
52
+ }
37
53
  export interface CommitDetail extends HistoryCommit {
38
54
  body: string;
39
55
  /** Summary relative to the first parent (empty tree for a root). */
package/lib/wire.js CHANGED
@@ -11,8 +11,9 @@ export const ROUTE_STATUS = `${ROUTE_PREFIX}/status`;
11
11
  /** GET ROUTE_PREFIX/head?path=<absolute dir> — checked-out branch only.
12
12
  * A file read of HEAD, not a git process. */
13
13
  export const ROUTE_HEAD = `${ROUTE_PREFIX}/head`;
14
- /** Read-only POSTs: bounded history and one commit's full message/summary. */
14
+ /** Read-only POSTs: bounded history, every author on that history, and one commit's full message/summary. */
15
15
  export const ROUTE_HISTORY = `${ROUTE_PREFIX}/history`;
16
+ export const ROUTE_AUTHORS = `${ROUTE_PREFIX}/authors`;
16
17
  export const ROUTE_COMMIT = `${ROUTE_PREFIX}/commit`;
17
18
  /** POST ROUTE_PREFIX/worktree — create-or-reuse a worktree for a branch. */
18
19
  export const ROUTE_WORKTREE = `${ROUTE_PREFIX}/worktree`;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@laoyuehanni/dsh-git-worktree",
3
- "version": "0.4.11",
3
+ "version": "0.4.13",
4
4
  "description": "DSH plugin: branch visibility and git worktree isolation for Web UI sessions",
5
5
  "keywords": [
6
6
  "dsh",