@laoyuehanni/dsh-git-worktree 0.4.5 → 0.4.6-rc.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/lib/routes.js CHANGED
@@ -2,9 +2,10 @@
2
2
  * Route logic as pure functions: query/body in, status+body out. The HTTP
3
3
  * shell (index.ts) owns req/res mechanics; everything testable lives here.
4
4
  */
5
- import { dirname, join, resolve } from 'node:path';
5
+ import { basename, dirname, join, resolve } from 'node:path';
6
6
  import { mkdir, readdir, rm, stat } from 'node:fs/promises';
7
- import { GitError, addWorktree, addWorktreeCutout, createBranch, cutoutBranchName, deleteBranch, fetchAll, fsDirExists, inspectWorktree, isAbsoluteDir, probeRepo, probeWorkspaceGit, removeWorktree, renameBranch, resolveBranch, switchBranch, updateBranch } from './git.js';
7
+ import { runPostCreateCopy } from './copy-files.js';
8
+ import { appendWorktreeExclude, fsExcludeSeams, GitError, addWorktree, addWorktreeCutout, createBranch, cutoutBranchName, deleteBranch, fetchAll, fsDirExists, inspectWorktree, isAbsoluteDir, probeRepo, probeWorkspaceGit, removeWorktree, renameBranch, resolveBranch, switchBranch, updateBranch } from './git.js';
8
9
  import { isAbsoluteConfigPath, sanitizeBranchDir } from './normalize.js';
9
10
  import { resolveRootDir } from './settings.js';
10
11
  /** Real fs-backed one-level directory listing (names only). Plain FILES are
@@ -95,58 +96,136 @@ export async function handleGroupWorktrees(deps, body) {
95
96
  }
96
97
  return { status: 200, body: { facts } };
97
98
  }
99
+ /** The project-internal layout directory name every repository uses. */
100
+ const PROJECT_LAYOUT_DIR = join('.dsh', 'gitworktree');
98
101
  /**
99
- * POST /worktrees-all — git facts for every DIRECT child directory of the
100
- * resolved worktree storage root (the slots this plugin plans as
101
- * `<repoName>-<branch>`). The management dialog's data source: one scan
102
- * answers for all repositories at once, orphan directories included (a
103
- * child that probes as no git repository comes back with null facts rather
104
- * than being dropped — the dialog shows it as unrecognized). A missing
105
- * storage root answers an empty list; per-child probe failures degrade to
106
- * null facts, never a 500 — the dialog must render, not error out. A root
107
- * holding more than {@link SCAN_CHILDREN_LIMIT} children answers its first
108
- * slice plus `truncated`, so a misconfigured rootDir cannot turn one dialog
102
+ * Whether `canonical` sits DIRECTLY inside a `<repo>/.dsh/gitworktree`
103
+ * layout root whose repository actually exists on disk. The layout names its
104
+ * own owner (two levels up must hold a `.git`), so no workspace list is
105
+ * needed to gate the plugin's territory — a plain fs probe decides.
106
+ */
107
+ function insideProjectLayout(canonical, dirExists) {
108
+ const layout = dirname(canonical);
109
+ if (basename(layout) !== 'gitworktree')
110
+ return false;
111
+ const dsh = dirname(layout);
112
+ if (basename(dsh) !== '.dsh')
113
+ return false;
114
+ return dirExists(join(dirname(dsh), '.git'));
115
+ }
116
+ /**
117
+ * POST /worktrees-all — git facts for every DIRECT child directory of the two
118
+ * storage locations the plugin has ever used, merged:
119
+ *
120
+ * - legacy: the resolved central storage root (today a read-only historical
121
+ * location — existing worktrees stay put, `rootDir` still resolves it);
122
+ * - project: `<repo>/.dsh/gitworktree` under every DISTINCT repository root
123
+ * derived from the caller's registered workspace paths (the current
124
+ * layout — its path prefix is what the workspace tree nests under).
125
+ *
126
+ * The management dialog's data source (and, through it, the lazy prune's):
127
+ * one scan answers for all repositories at once, orphan directories included
128
+ * (a child that probes as no git repository comes back with null facts
129
+ * rather than being dropped — the dialog shows it as unrecognized). Missing
130
+ * locations answer their half as an empty list; per-child probe failures
131
+ * degrade to null facts, never a 500 — the dialog must render, not error
132
+ * out. Each location that holds more than {@link SCAN_CHILDREN_LIMIT}
133
+ * children answers its first slice, and any truncation marks the whole
134
+ * response `truncated`, so a misconfigured location cannot turn one dialog
109
135
  * open into thousands of git spawns.
110
136
  * @param deps - host dependencies.
137
+ * @param body - parsed request body: `{ workspaces? }`.
111
138
  */
112
- export async function handleWorktreesAll(deps) {
113
- const rootDir = resolveRootDir(deps.sectionRootDir(), deps.home(), deps.envHome());
139
+ export async function handleWorktreesAll(deps, body) {
140
+ if (typeof body !== 'object' || body === null || Array.isArray(body))
141
+ return fail(400, 'request body must be a JSON object');
142
+ const workspacesRaw = body.workspaces ?? [];
143
+ if (!Array.isArray(workspacesRaw))
144
+ return fail(400, 'body key "workspaces" must be an array of absolute directories');
145
+ const unknownKeys = Object.keys(body).filter(key => key !== 'workspaces');
146
+ if (unknownKeys.length > 0)
147
+ return fail(400, `unknown body key "${unknownKeys[0]}"`);
148
+ const workspaces = [];
149
+ for (const candidate of workspacesRaw) {
150
+ if (typeof candidate !== 'string' || !isAbsoluteDir(candidate))
151
+ return fail(400, 'body key "workspaces" must be an array of absolute directories');
152
+ if (!workspaces.includes(candidate))
153
+ workspaces.push(candidate);
154
+ }
155
+ if (workspaces.length > GROUP_PATHS_LIMIT)
156
+ return fail(400, `body key "workspaces" accepts at most ${String(GROUP_PATHS_LIMIT)} distinct directories`);
114
157
  const listDir = deps.listDir ?? fsListDir;
115
- const listed = await listDir(rootDir);
116
- const truncated = listed.length > SCAN_CHILDREN_LIMIT;
117
- const children = truncated ? listed.slice(0, SCAN_CHILDREN_LIMIT) : listed;
118
158
  const facts = [];
119
- for (let start = 0; start < children.length; start += GROUP_BATCH_SIZE) {
120
- const batch = children.slice(start, start + GROUP_BATCH_SIZE);
121
- const probed = await Promise.all(batch.map(async (child) => {
122
- const path = join(rootDir, child);
159
+ let truncated = false;
160
+ const scanLocation = async (root, source) => {
161
+ const listed = await listDir(root);
162
+ if (listed.length > SCAN_CHILDREN_LIMIT) {
163
+ truncated = true;
164
+ listed.length = SCAN_CHILDREN_LIMIT;
165
+ }
166
+ for (let start = 0; start < listed.length; start += GROUP_BATCH_SIZE) {
167
+ const batch = listed.slice(start, start + GROUP_BATCH_SIZE);
168
+ const probed = await Promise.all(batch.map(async (child) => {
169
+ const path = join(root, child);
170
+ try {
171
+ const gitFacts = await probeWorkspaceGit(deps.exec, path);
172
+ return gitFacts === undefined
173
+ ? { path, repoName: null, branch: null, source }
174
+ : { path, repoName: gitFacts.repoName, branch: gitFacts.branch, source };
175
+ }
176
+ catch {
177
+ return { path, repoName: null, branch: null, source };
178
+ }
179
+ }));
180
+ facts.push(...probed);
181
+ }
182
+ };
183
+ const legacyRoot = resolveRootDir(deps.sectionRootDir(), deps.home(), deps.envHome());
184
+ await scanLocation(legacyRoot, 'legacy');
185
+ const statDirectory = deps.statDirectory ?? fsStatDirectory;
186
+ const legacyRootExists = await statDirectory(legacyRoot);
187
+ // Project half: one belonging probe per DISTINCT workspace path (bounded
188
+ // batches, same as /group), then one scan per DISTINCT repository root.
189
+ const repoRoots = new Set();
190
+ for (let start = 0; start < workspaces.length; start += GROUP_BATCH_SIZE) {
191
+ const batch = workspaces.slice(start, start + GROUP_BATCH_SIZE);
192
+ const probed = await Promise.all(batch.map(async (path) => {
123
193
  try {
124
- const gitFacts = await probeWorkspaceGit(deps.exec, path);
125
- return gitFacts === undefined
126
- ? { path, repoName: null, branch: null }
127
- : { path, repoName: gitFacts.repoName, branch: gitFacts.branch };
194
+ return await probeWorkspaceGit(deps.exec, path);
128
195
  }
129
196
  catch {
130
- return { path, repoName: null, branch: null };
197
+ return undefined;
131
198
  }
132
199
  }));
133
- facts.push(...probed);
200
+ for (const workspaceFacts of probed) {
201
+ if (workspaceFacts !== undefined)
202
+ repoRoots.add(workspaceFacts.repoRoot);
203
+ }
204
+ }
205
+ for (const repoRoot of repoRoots) {
206
+ await scanLocation(join(repoRoot, PROJECT_LAYOUT_DIR), 'project');
134
207
  }
135
- return { status: 200, body: { worktrees: facts, ...truncated ? { truncated } : {} } };
208
+ return { status: 200, body: { worktrees: facts, legacyRoot, legacyRootExists, ...truncated ? { truncated } : {} } };
136
209
  }
137
210
  /** Real fs-backed recursive force rm (Windows file-lock retries included). */
138
211
  export async function fsRmRecursive(path) {
139
212
  await rm(path, { recursive: true, force: true, maxRetries: 8, retryDelay: 100 });
140
213
  }
214
+ /** Create the layout root through the deps seam (tests substitute a no-op). */
215
+ function mkdirSlot(deps, layoutRoot) {
216
+ const mkdirRecursive = deps.mkdirRecursive ?? fsMkdirRecursive;
217
+ return mkdirRecursive(layoutRoot);
218
+ }
141
219
  /**
142
- * POST /purge — delete a NON-git directory sitting DIRECTLY inside the
143
- * resolved worktree storage root: the orphaned leftover a half-failed
144
- * `worktree remove` can leave behind (git registration and the .git file
145
- * already gone, contents stranded on disk). Triple-gated: one level below
146
- * the root (resolved forms, same slot boundary as /ensure-directory), a
147
- * real directory, and NOT a git repository — anything git still recognizes
148
- * must go through /remove, where the removal carries the session-archive
149
- * and unregistration half. Deletion is a plain recursive force rm.
220
+ * POST /purge — delete a NON-git directory sitting DIRECTLY inside one of the
221
+ * plugin's two storage layouts: the legacy central root or a repository's
222
+ * `.dsh/gitworktree`. The orphaned leftover a half-failed `worktree remove`
223
+ * can leave behind (git registration and the .git file already gone,
224
+ * contents stranded on disk). Triple-gated: one level below a storage
225
+ * location (resolved forms, same slot boundary as /ensure-directory), a real
226
+ * directory, and NOT a git repository — anything git still recognizes must
227
+ * go through /remove, where the removal carries the session-archive and
228
+ * unregistration half. Deletion is a plain recursive force rm.
150
229
  * @param deps - host dependencies.
151
230
  * @param body - parsed request body: `{ path }`.
152
231
  */
@@ -163,8 +242,8 @@ export async function handlePurgeDirectory(deps, body) {
163
242
  }
164
243
  const rootDir = resolveRootDir(deps.sectionRootDir(), deps.home(), deps.envHome());
165
244
  const canonical = resolve(path);
166
- if (dirname(canonical) !== resolve(rootDir)) {
167
- return fail(400, `"${canonical}" is outside the worktree storage root "${resolve(rootDir)}"`);
245
+ if (dirname(canonical) !== resolve(rootDir) && !insideProjectLayout(canonical, deps.dirExists ?? fsDirExists)) {
246
+ return fail(400, `"${canonical}" is outside the plugin's worktree storage locations`);
168
247
  }
169
248
  const statDirectory = deps.statDirectory ?? fsStatDirectory;
170
249
  if (!(await statDirectory(canonical))) {
@@ -280,9 +359,14 @@ function isOutcome(value) {
280
359
  return typeof value === 'object' && value !== null && 'status' in value && 'body' in value;
281
360
  }
282
361
  /**
283
- * POST /worktree 鈥?create or reuse the worktree for a branch, then report the
284
- * directory so the client can register it as a workspace. With `cutout: true`
285
- * the branch is the CURRENT checkout (occupied by the main worktree, so git
362
+ * POST /worktree — create or reuse the worktree for a branch, then report the
363
+ * directory so the client can register it as a workspace. The worktree lands
364
+ * at `<repo>/.dsh/gitworktree/<branch>` (path prefix = repository, so the
365
+ * native workspace tree nests it under its repository automatically); an
366
+ * existing registration for the branch ANYWHERE is reused first (the
367
+ * repository-wide worktree list is location-independent — legacy-central
368
+ * worktrees keep being returned, never duplicated). With `cutout: true` the
369
+ * branch is the CURRENT checkout (occupied by the main worktree, so git
286
370
  * refuses to add it): a new branch is cut out of it (`<branch>-wt`, first
287
371
  * free `-wt<N>` suffix) and isolated in the fresh worktree instead.
288
372
  * @param deps - host dependencies.
@@ -297,15 +381,18 @@ export async function handleCreateWorktree(deps, body) {
297
381
  return fail(400, '"repoPath" must be an absolute directory');
298
382
  if (branch.trim() === '')
299
383
  return fail(400, '"branch" must be non-empty');
300
- const configured = deps.sectionRootDir()?.trim();
301
- if (configured !== undefined && configured !== '' && !isAbsoluteConfigPath(configured)) {
302
- return fail(400, `configured rootDir "${String(deps.sectionRootDir())}" is not an absolute path`);
303
- }
304
384
  try {
305
385
  const facts = await probeRepo(deps.exec, repoPath, deps.dirExists);
306
386
  if (facts === undefined)
307
387
  return fail(400, `"${repoPath}" is not inside a git repository`);
308
- const rootDir = resolveRootDir(deps.sectionRootDir(), deps.home(), deps.envHome());
388
+ // Local-ignore first, creation second: the rule is harmless when the
389
+ // creation later fails (the directory simply does not exist), while the
390
+ // reverse order leaves a created worktree visible as untracked on the
391
+ // next `git status` when the write fails. A write failure never blocks
392
+ // the creation — the worktree cannot be rolled back — it rides the
393
+ // successful response as `excludeWarning` for the client to toast.
394
+ const excludeWarning = await appendWorktreeExclude(deps.excludeSeams ?? fsExcludeSeams, facts.repoRoot);
395
+ const layoutRoot = join(facts.repoRoot, PROJECT_LAYOUT_DIR);
309
396
  // Optional pre-create remote sync — but only when the branch actually
310
397
  // consumes remote data: a LOCAL branch's worktree (or an existing twin)
311
398
  // never reads the fetched refs, so the resolve runs first and the fetch
@@ -326,6 +413,7 @@ export async function handleCreateWorktree(deps, body) {
326
413
  }
327
414
  }
328
415
  }
416
+ const warnings = { ...fetchWarning === undefined ? {} : { fetchWarning }, ...excludeWarning === undefined ? {} : { excludeWarning } };
329
417
  if (cutout === true) {
330
418
  // An explicit name skips the `-wt` suffix walk and is used verbatim —
331
419
  // both for the branch and the storage folder. A leading dash would
@@ -335,31 +423,38 @@ export async function handleCreateWorktree(deps, body) {
335
423
  if (custom !== undefined && custom !== '') {
336
424
  if (custom.startsWith('-'))
337
425
  return fail(400, '"name" must not start with "-"');
338
- const target = join(rootDir, `${facts.repoName}-${sanitizeBranchDir(custom)}`);
339
- await mkdir(rootDir, { recursive: true });
426
+ const target = join(layoutRoot, sanitizeBranchDir(custom));
427
+ await mkdirSlot(deps, layoutRoot);
340
428
  await addWorktreeCutout(deps.exec, facts.repoRoot, branch, custom, target);
341
- return { status: 200, body: { path: target, created: true, ...fetchWarning === undefined ? {} : { fetchWarning } } };
429
+ const copyWarning = await runPostCreateCopy(deps, facts.repoRoot, target);
430
+ const copyWarnObj = copyWarning !== undefined ? { copyWarning } : {};
431
+ return { status: 200, body: { path: target, created: true, ...warnings, ...copyWarnObj } };
342
432
  }
343
433
  // The new branch name must be known before the folder name can be
344
- // computed: the folder carries `<repoName>-<NEW branch>`. The name
345
- // must be free in BOTH namespaces — the branch table and the storage
346
- // folder: a leftover folder of a since-deleted branch would otherwise
347
- // fail `worktree add` with a bare "already exists", so the suffix
348
- // walk probes the folder too.
434
+ // computed: the folder carries the NEW branch's directory name. The
435
+ // name must be free in BOTH namespaces — the branch table and the
436
+ // storage folder: a leftover folder of a since-deleted branch would
437
+ // otherwise fail `worktree add` with a bare "already exists", so the
438
+ // suffix walk probes the folder too.
349
439
  const dirExists = deps.dirExists ?? fsDirExists;
350
- const newBranch = await cutoutBranchName(deps.exec, facts.repoRoot, branch, (candidate) => dirExists(join(rootDir, `${facts.repoName}-${sanitizeBranchDir(candidate)}`)));
351
- const target = join(rootDir, `${facts.repoName}-${sanitizeBranchDir(newBranch)}`);
352
- await mkdir(rootDir, { recursive: true });
440
+ const newBranch = await cutoutBranchName(deps.exec, facts.repoRoot, branch, (candidate) => dirExists(join(layoutRoot, sanitizeBranchDir(candidate))));
441
+ const target = join(layoutRoot, sanitizeBranchDir(newBranch));
442
+ await mkdirSlot(deps, layoutRoot);
353
443
  await addWorktreeCutout(deps.exec, facts.repoRoot, branch, newBranch, target);
354
- return { status: 200, body: { path: target, created: true, ...fetchWarning === undefined ? {} : { fetchWarning } } };
444
+ const copyWarning = await runPostCreateCopy(deps, facts.repoRoot, target);
445
+ const copyWarnObj = copyWarning !== undefined ? { copyWarning } : {};
446
+ return { status: 200, body: { path: target, created: true, ...warnings, ...copyWarnObj } };
355
447
  }
356
- // The folder name carries the belonging itself: `<repoName>-<branch>` —
357
- // the sidebar group title (the folder basename) then reads as the parent
358
- // repository plus the branch instead of a bare branch word.
359
- const target = join(rootDir, `${facts.repoName}-${sanitizeBranchDir(branch)}`);
360
- await mkdir(rootDir, { recursive: true });
448
+ // The folder name carries the branch: `<repo>/.dsh/gitworktree/<branch>`.
449
+ const target = join(layoutRoot, sanitizeBranchDir(branch));
450
+ await mkdirSlot(deps, layoutRoot);
361
451
  const result = await addWorktree(deps.exec, facts.repoRoot, branch, target, deps.dirExists);
362
- return { status: 200, body: { ...result, ...fetchWarning === undefined ? {} : { fetchWarning } } };
452
+ let copyWarning;
453
+ if (result.created) {
454
+ copyWarning = await runPostCreateCopy(deps, facts.repoRoot, result.path);
455
+ }
456
+ const copyWarnObj = copyWarning !== undefined ? { copyWarning } : {};
457
+ return { status: 200, body: { ...result, ...warnings, ...copyWarnObj } };
363
458
  }
364
459
  catch (error) {
365
460
  if (error instanceof GitError)
@@ -679,23 +774,26 @@ export async function handlePathExists(deps, body) {
679
774
  exists[path] = await statDirectory(path).catch(() => false);
680
775
  }));
681
776
  // Rebuildability is a STORAGE-SLOT fact, not a general one: only a missing
682
- // path sitting DIRECTLY inside the resolved worktree root is a slot this
683
- // plugin planned, so recreating the empty directory is safe self-healing
684
- // (its sessions reattach by realpath once the folder is back). Paths
685
- // outside the root are the user's own territory — never rebuilt here.
777
+ // path sitting DIRECTLY inside one of the plugin's storage locations (the
778
+ // legacy root, or a repository's `.dsh/gitworktree`) is a slot this plugin
779
+ // planned, so recreating the empty directory is safe self-healing (its
780
+ // sessions reattach by realpath once the folder is back). Paths outside
781
+ // both are the user's own territory — never rebuilt here.
686
782
  const rootDir = resolveRootDir(deps.sectionRootDir(), deps.home(), deps.envHome());
783
+ const dirExists = deps.dirExists ?? fsDirExists;
687
784
  const rebuildable = {};
688
785
  for (const path of distinct) {
689
786
  if (exists[path])
690
787
  continue;
691
- rebuildable[path] = dirname(resolve(path)) === resolve(rootDir);
788
+ rebuildable[path] = dirname(resolve(path)) === resolve(rootDir) || insideProjectLayout(resolve(path), dirExists);
692
789
  }
693
790
  return { status: 200, body: { exists, ...Object.values(rebuildable).some(Boolean) ? { rebuildable } : {} } };
694
791
  }
695
792
  /**
696
793
  * POST /ensure-directory — recreate a MISSING worktree storage slot
697
- * (`mkdir -p`). Strictly gated to paths sitting DIRECTLY inside the resolved
698
- * worktree storage root: those slots were planned and created by this plugin,
794
+ * (`mkdir -p`). Strictly gated to paths sitting DIRECTLY inside one of the
795
+ * plugin's two storage layouts (the legacy central root, or a repository's
796
+ * `.dsh/gitworktree`): those slots were planned and created by this plugin,
699
797
  * so rebuilding the empty folder is self-healing (historical sessions
700
798
  * reattach automatically once realpath matches again — DSH keeps the
701
799
  * workspace accounting and filters membership by the session header's cwd).
@@ -717,10 +815,10 @@ export async function handleEnsureDirectory(deps, body) {
717
815
  }
718
816
  const rootDir = resolveRootDir(deps.sectionRootDir(), deps.home(), deps.envHome());
719
817
  const canonical = resolve(path);
720
- // Exactly one level below the root, compared on resolved forms so `..`
721
- // and spelling drift cannot escape the slot boundary.
722
- if (dirname(canonical) !== resolve(rootDir)) {
723
- return fail(400, `"${canonical}" is outside the worktree storage root "${resolve(rootDir)}"`);
818
+ // Exactly one level below a storage location, compared on resolved forms
819
+ // so `..` and spelling drift cannot escape the slot boundary.
820
+ if (dirname(canonical) !== resolve(rootDir) && !insideProjectLayout(canonical, deps.dirExists ?? fsDirExists)) {
821
+ return fail(400, `"${canonical}" is outside the plugin's worktree storage locations`);
724
822
  }
725
823
  const mkdirRecursive = deps.mkdirRecursive ?? fsMkdirRecursive;
726
824
  try {
package/lib/settings.d.ts CHANGED
@@ -6,11 +6,6 @@
6
6
  * the legacy file is read once at startup and its value migrated across (the
7
7
  * renamed file stays behind as a backup).
8
8
  */
9
- /** The persisted document shape the pre-0.3 plugin read and wrote on its own. */
10
- export interface LegacySettings {
11
- /** Worktree storage root; '' selected the default ~/.dsh/gitworktree. */
12
- rootDir: string;
13
- }
14
9
  /**
15
10
  * Resolve the effective worktree storage root: an explicit non-blank `rootDir`
16
11
  * wins; otherwise `$DSH_HOME/gitworktree` (a blank `$DSH_HOME` counts as
@@ -27,25 +22,3 @@ export declare function resolveRootDir(rootDir: string | undefined, home: string
27
22
  * @param rootDir - the resolved section value.
28
23
  */
29
24
  export declare function validateRootDir(rootDir: string | undefined): void;
30
- /**
31
- * Decide what a legacy-file migration should store, if anything: the legacy
32
- * root only crosses over when it names a directory (blank kept the default,
33
- * which the section's absence already expresses) and the user layer has not
34
- * recorded its own choice (key presence, not a value comparison — an override
35
- * equal to the legacy value is still the user's own doing and must not be
36
- * rewritten).
37
- * @param legacy - the legacy file's stored value.
38
- * @param userLayer - the namespace's raw user layer, when one exists.
39
- * @returns the rootDir to write, or undefined to leave the section alone.
40
- */
41
- export declare function planLegacyMigration(legacy: LegacySettings, userLayer: Record<string, unknown> | undefined): string | undefined;
42
- /**
43
- * Load the legacy settings document.
44
- * @param file - absolute settings file path.
45
- * @returns the stored value, or the default when absent/unreadable/invalid.
46
- */
47
- export declare function loadLegacySettings(file: string): Promise<LegacySettings>;
48
- /** Resolve the legacy settings file location for a home directory. */
49
- export declare function settingsFileOf(home: string): string;
50
- /** The backup name a migrated legacy file is renamed to (never deleted). */
51
- export declare function migratedFileOf(file: string): string;
package/lib/settings.js CHANGED
@@ -6,7 +6,6 @@
6
6
  * the legacy file is read once at startup and its value migrated across (the
7
7
  * renamed file stays behind as a backup).
8
8
  */
9
- import { readFile } from 'node:fs/promises';
10
9
  import { join } from 'node:path';
11
10
  import { isAbsoluteConfigPath } from './normalize.js';
12
11
  /**
@@ -40,52 +39,3 @@ export function validateRootDir(rootDir) {
40
39
  throw new Error(`rootDir "${rootDir}" is not an absolute path`);
41
40
  }
42
41
  }
43
- /**
44
- * Decide what a legacy-file migration should store, if anything: the legacy
45
- * root only crosses over when it names a directory (blank kept the default,
46
- * which the section's absence already expresses) and the user layer has not
47
- * recorded its own choice (key presence, not a value comparison — an override
48
- * equal to the legacy value is still the user's own doing and must not be
49
- * rewritten).
50
- * @param legacy - the legacy file's stored value.
51
- * @param userLayer - the namespace's raw user layer, when one exists.
52
- * @returns the rootDir to write, or undefined to leave the section alone.
53
- */
54
- export function planLegacyMigration(legacy, userLayer) {
55
- if (userLayer !== undefined && Object.hasOwn(userLayer, 'rootDir'))
56
- return undefined;
57
- const value = legacy.rootDir.trim();
58
- return value === '' ? undefined : value;
59
- }
60
- /**
61
- * Load the legacy settings document.
62
- * @param file - absolute settings file path.
63
- * @returns the stored value, or the default when absent/unreadable/invalid.
64
- */
65
- export async function loadLegacySettings(file) {
66
- let raw;
67
- try {
68
- raw = await readFile(file, 'utf8');
69
- }
70
- catch {
71
- return { rootDir: '' };
72
- }
73
- try {
74
- const parsed = JSON.parse(raw);
75
- if (typeof parsed !== 'object' || parsed === null)
76
- return { rootDir: '' };
77
- const rootDir = parsed.rootDir;
78
- return typeof rootDir === 'string' ? { rootDir } : { rootDir: '' };
79
- }
80
- catch {
81
- return { rootDir: '' };
82
- }
83
- }
84
- /** Resolve the legacy settings file location for a home directory. */
85
- export function settingsFileOf(home) {
86
- return join(home, '.dsh', 'git-worktree', 'settings.json');
87
- }
88
- /** The backup name a migrated legacy file is renamed to (never deleted). */
89
- export function migratedFileOf(file) {
90
- return `${file}.migrated`;
91
- }
package/lib/wire.d.ts CHANGED
@@ -110,6 +110,16 @@ export interface CreateWorktreeResult {
110
110
  * never consumes the fetch), this carries git's stderr summary for the
111
111
  * client to toast. */
112
112
  fetchWarning?: string;
113
+ /** Present only when the idempotent write of `/.dsh/gitworktree/` into
114
+ * `<repo>/.git/info/exclude` failed: the worktree was created anyway (it
115
+ * cannot be rolled back), so the SOURCE REPOSITORY now shows an untracked
116
+ * `.dsh/` directory — the client must toast this or the user's next
117
+ * `git status` reads as a mystery. */
118
+ excludeWarning?: string;
119
+ /** Present only when copying declared configuration files into the new
120
+ * worktree failed for one or more files: the worktree was created anyway,
121
+ * this carries a summary of the failed copies for the client to toast. */
122
+ copyWarning?: string;
113
123
  }
114
124
  /** POST switch request body. */
115
125
  export interface SwitchBody {
@@ -275,7 +285,7 @@ export interface PathExistsResult {
275
285
  /** POST ensure-directory request body. */
276
286
  export interface EnsureDirectoryBody {
277
287
  /** The missing directory to create (absolute; must sit directly inside the
278
- * worktree storage root). */
288
+ * legacy storage root or a repository's `.dsh/gitworktree`). */
279
289
  path: string;
280
290
  }
281
291
  /** POST ensure-directory response body. */
@@ -284,7 +294,15 @@ export interface EnsureDirectoryResult {
284
294
  * present as a directory). */
285
295
  created: boolean;
286
296
  }
287
- /** One direct child directory of the worktree storage root. */
297
+ /** POST worktrees-all request body (all-optional for shape compatibility). */
298
+ export interface WorktreesAllBody {
299
+ /** Absolute directories of the REGISTERED workspaces, from which the host
300
+ * derives the repository-root set to scan `<repo>/.dsh/gitworktree` under
301
+ * (each probed once, deduplicated). Absent/empty scans only the legacy
302
+ * storage root. */
303
+ workspaces?: string[];
304
+ }
305
+ /** One direct child directory of a worktree storage location. */
288
306
  export interface WorktreeScanEntry {
289
307
  /** Absolute directory path. */
290
308
  path: string;
@@ -295,20 +313,33 @@ export interface WorktreeScanEntry {
295
313
  /** Branch checked out by the directory; null = unrecognized, detached, or
296
314
  * unborn HEAD. */
297
315
  branch: string | null;
298
- }
299
- /** POST worktrees-all response body — one entry per DIRECT child of the
300
- * resolved storage root; the root's absence answers an empty list. */
316
+ /** Where the directory lives: `project` = inside `<repo>/.dsh/gitworktree`
317
+ * (the current layout, auto-nested under its repository by the workspace
318
+ * tree), `legacy` = inside the historical central storage root. */
319
+ source: 'legacy' | 'project';
320
+ }
321
+ /** POST worktrees-all response body — one entry per DIRECT child of each
322
+ * scanned storage location; a missing location answers its half as an empty
323
+ * list. */
301
324
  export interface WorktreesAllResult {
302
325
  worktrees: WorktreeScanEntry[];
303
- /** Present and true when the storage root held more children than the
304
- * scan probes: the list is the first slice, and the client says so rather
305
- * than presenting a truncated scan as the whole picture. */
326
+ /** The resolved LEGACY storage root (historical central location): kept
327
+ * read-only in the settings card so existing users can still find where
328
+ * their old worktrees live. */
329
+ legacyRoot: string;
330
+ /** False when the legacy root does not exist on disk — "未使用" rather
331
+ * than hiding the field. */
332
+ legacyRootExists: boolean;
333
+ /** Present and true when either scanned location held more children than
334
+ * the scan probes: the list is the first slice, and the client says so
335
+ * rather than presenting a truncated scan as the whole picture. */
306
336
  truncated?: boolean;
307
337
  }
308
338
  /** POST purge request body. */
309
339
  export interface PurgeDirectoryBody {
310
340
  /** The leftover directory to delete (absolute; must sit directly inside
311
- * the worktree storage root AND have no git identity). */
341
+ * the legacy storage root or a repository's `.dsh/gitworktree`, AND have
342
+ * no git identity). */
312
343
  path: string;
313
344
  }
314
345
  /** POST purge response body. */