@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/index.js CHANGED
@@ -1,64 +1,73 @@
1
1
  /**
2
- * dsh-git-worktree host half. Owns the worktree storage-root settings section
3
- * (the `git-worktree` namespace in the dsh settings document, registered
4
- * through SettingsProvider.installSection with the composition entry as its
5
- * base layer) and — while a webServer service exists — the HTTP routes the browser
6
- * half fetches. A stored root edit takes effect live: the routes read the
7
- * section source per request, so no restart and no route re-registration.
8
- *
9
- * The legacy ~/.dsh/git-worktree/settings.json value migrates into the
10
- * namespace once, when a settings service first attaches and the user layer
11
- * has recorded no choice of its own; the renamed file stays behind as a
12
- * backup. Headless profiles lose only the routes: nothing else in the plugin
13
- * has a browser dependency.
2
+ * dsh-git-worktree host half. Exposes volatile configuration fields projected
3
+ * through the settings service (the `git-worktree` profile entry in the active
4
+ * dsh profile) and — while a webServer service exists — the HTTP routes the
5
+ * browser half fetches. Config edits persist into the profile patch and take
6
+ * effect live via the loader.
14
7
  */
15
8
  import { homedir } from 'node:os';
16
- import { rename } from 'node:fs/promises';
17
9
  import z from '@deepseek-ai/schemastery';
18
10
  import { childProcessExec } from './git.js';
19
11
  import { handleCreateBranch, handleCreateWorktree, handleDeleteBranch, handleEnsureDirectory, handleFetch, handleGroupWorktrees, handleInspectWorktree, handlePathExists, handlePurgeDirectory, handleRemoveWorktree, handleRenameBranch, handleStatus, handleSwitch, handleUpdate, handleWorktreesAll, } from './routes.js';
20
- import { loadLegacySettings, migratedFileOf, planLegacyMigration, settingsFileOf, validateRootDir, } from './settings.js';
12
+ import { validateRootDir } from './settings.js';
21
13
  import { ROUTE_BRANCH, ROUTE_BRANCH_DELETE, ROUTE_BRANCH_RENAME, ROUTE_ENSURE_DIRECTORY, ROUTE_EXISTS, ROUTE_FETCH, ROUTE_GROUP, ROUTE_INSPECT, ROUTE_PURGE, ROUTE_REMOVE, ROUTE_STATUS, ROUTE_SWITCH, ROUTE_UPDATE, ROUTE_WORKTREE, ROUTE_WORKTREES_ALL } from './wire.js';
22
14
  export const name = 'dsh-git-worktree';
23
15
  export const inject = [];
24
16
  /** Largest accepted request body (bytes) — these payloads are a few strings. */
25
17
  const BODY_LIMIT = 64 * 1024;
18
+ function readVolatile(value) {
19
+ if (value === undefined)
20
+ return undefined;
21
+ if (typeof value === 'object' && value !== null && 'get' in value && typeof value.get === 'function') {
22
+ return value.get();
23
+ }
24
+ return value;
25
+ }
26
+ /** The shipped prune cap (whole storage root, valid git worktrees only). */
27
+ export const KEEP_WORKTREES_DEFAULT = 30;
26
28
  /**
27
29
  * Cordis resolves the composition entry's config through this schema before
28
- * `apply` runs (official plugin-config convention: export the `Config` type
29
- * and a same-named Schemastery schema). It fills the `groupSidebar` default;
30
- * `rootDir` passes through untouched — its absence stays observable so the
31
- * settings section keeps spelling the resolved default. Constraints the
32
- * schema cannot express still fail loudly in validateConfig below (absolute
33
- * path; unknown keys — schemastery keeps extras instead of rejecting them).
30
+ * `apply` runs. In dsh 0.1.7+, fields marked with `.volatile()` are projected
31
+ * by the settings service into live configuration forms.
34
32
  */
35
33
  export const Config = z.object({
36
- rootDir: z.string(),
37
- groupSidebar: z.boolean().default(true),
38
- fetchBeforeCreate: z.boolean().default(false),
39
- autoPruneWorktrees: z.boolean().default(false),
40
- keepWorktrees: z.number(),
34
+ rootDir: z.string().volatile(),
35
+ groupSidebar: z.boolean().default(true).volatile(),
36
+ fetchBeforeCreate: z.boolean().default(false).volatile(),
37
+ autoPruneWorktrees: z.boolean().default(false).volatile(),
38
+ keepWorktrees: z.number().default(KEEP_WORKTREES_DEFAULT).volatile(),
39
+ postCreateCopyFiles: z.array(z.string()).default([]).volatile(),
41
40
  });
42
41
  /** Reject stale or misspelled config keys before defaults can hide them. */
43
42
  export function validateConfig(config) {
44
- const unknown = Object.keys(config).find(key => key !== 'rootDir' && key !== 'groupSidebar' && key !== 'fetchBeforeCreate' && key !== 'autoPruneWorktrees' && key !== 'keepWorktrees');
43
+ const unknown = Object.keys(config).find(key => key !== 'rootDir' && key !== 'groupSidebar' && key !== 'fetchBeforeCreate' && key !== 'autoPruneWorktrees' && key !== 'keepWorktrees' && key !== 'postCreateCopyFiles');
45
44
  if (unknown !== undefined) {
46
45
  throw new Error(`GitWorktreeConfig: unknown key "${unknown}"`);
47
46
  }
48
- if (config.rootDir !== undefined && (typeof config.rootDir !== 'string' || config.rootDir.length === 0)) {
47
+ const root = readVolatile(config.rootDir);
48
+ if (root !== undefined && (typeof root !== 'string' || root.length === 0)) {
49
49
  throw new Error('GitWorktreeConfig: "rootDir" must be a non-empty string');
50
50
  }
51
- if (config.groupSidebar !== undefined && typeof config.groupSidebar !== 'boolean') {
51
+ const groupSidebar = readVolatile(config.groupSidebar);
52
+ if (groupSidebar !== undefined && typeof groupSidebar !== 'boolean') {
52
53
  throw new Error('GitWorktreeConfig: "groupSidebar" must be a boolean');
53
54
  }
54
- if (config.fetchBeforeCreate !== undefined && typeof config.fetchBeforeCreate !== 'boolean') {
55
+ const fetchBeforeCreate = readVolatile(config.fetchBeforeCreate);
56
+ if (fetchBeforeCreate !== undefined && typeof fetchBeforeCreate !== 'boolean') {
55
57
  throw new Error('GitWorktreeConfig: "fetchBeforeCreate" must be a boolean');
56
58
  }
57
- if (config.autoPruneWorktrees !== undefined && typeof config.autoPruneWorktrees !== 'boolean') {
59
+ const autoPruneWorktrees = readVolatile(config.autoPruneWorktrees);
60
+ if (autoPruneWorktrees !== undefined && typeof autoPruneWorktrees !== 'boolean') {
58
61
  throw new Error('GitWorktreeConfig: "autoPruneWorktrees" must be a boolean');
59
62
  }
60
- validateKeepWorktrees(config.keepWorktrees);
61
- validateRootDir(config.rootDir);
63
+ const postCreateCopyFiles = readVolatile(config.postCreateCopyFiles);
64
+ if (postCreateCopyFiles !== undefined) {
65
+ if (!Array.isArray(postCreateCopyFiles) || !postCreateCopyFiles.every(item => typeof item === 'string')) {
66
+ throw new Error('GitWorktreeConfig: "postCreateCopyFiles" must be an array of strings');
67
+ }
68
+ }
69
+ validateKeepWorktrees(readVolatile(config.keepWorktrees));
70
+ validateRootDir(root);
62
71
  }
63
72
  /**
64
73
  * The prune cap must be an integer >= 1: 0 would read as "create then
@@ -75,103 +84,49 @@ export function validateKeepWorktrees(value) {
75
84
  }
76
85
  /** The settings namespace this plugin serves; its browser card spells the same string. */
77
86
  export const GIT_WORKTREE_NS = 'git-worktree';
78
- /** Schema resolving the `git-worktree` settings section. */
79
- export const sectionSchema = z.object({
80
- rootDir: z.string(),
81
- groupSidebar: z.boolean(),
82
- fetchBeforeCreate: z.boolean(),
83
- autoPruneWorktrees: z.boolean(),
84
- keepWorktrees: z.number(),
85
- });
86
- /** The shipped prune cap (whole storage root, valid git worktrees only). */
87
- export const KEEP_WORKTREES_DEFAULT = 30;
88
87
  /** The section-shaped view of a config: absent keys stay absent
89
88
  * (`exactOptionalPropertyTypes`) except the switches, which spell their
90
89
  * shipped defaults so a user-layer unset can always fall back to them. */
91
90
  export function sectionOf(config) {
91
+ const rootDir = readVolatile(config.rootDir);
92
+ const postCreateCopyFiles = readVolatile(config.postCreateCopyFiles);
93
+ const groupSidebar = readVolatile(config.groupSidebar);
94
+ const fetchBeforeCreate = readVolatile(config.fetchBeforeCreate);
95
+ const autoPruneWorktrees = readVolatile(config.autoPruneWorktrees);
96
+ const keepWorktrees = readVolatile(config.keepWorktrees);
92
97
  return {
93
- ...(config.rootDir === undefined ? {} : { rootDir: config.rootDir }),
98
+ ...(rootDir === undefined ? {} : { rootDir }),
99
+ ...(postCreateCopyFiles === undefined ? {} : { postCreateCopyFiles }),
94
100
  // The composition layer spells the shipped defaults so a user-layer
95
101
  // unset can always fall back to them.
96
- groupSidebar: config.groupSidebar ?? true,
97
- fetchBeforeCreate: config.fetchBeforeCreate ?? false,
98
- autoPruneWorktrees: config.autoPruneWorktrees ?? false,
99
- keepWorktrees: config.keepWorktrees ?? KEEP_WORKTREES_DEFAULT,
102
+ groupSidebar: groupSidebar ?? true,
103
+ fetchBeforeCreate: fetchBeforeCreate ?? false,
104
+ autoPruneWorktrees: autoPruneWorktrees ?? false,
105
+ keepWorktrees: keepWorktrees ?? KEEP_WORKTREES_DEFAULT,
100
106
  };
101
107
  }
102
108
  /**
103
- * Plugin apply: install the settings section, migrate any legacy stored root
104
- * into it, then mount routes on any webServer that comes and goes.
109
+ * Plugin apply: mount the settings presentation policy and HTTP routes on any
110
+ * webServer that comes and goes.
105
111
  * @param ctx - host cordis context.
106
- * @param config - the composition entry config (the section's base layer).
112
+ * @param config - the composition entry config.
107
113
  */
108
114
  export function apply(ctx, config = {}) {
109
115
  validateConfig(config);
110
- // The section source: the composition entry until a settings service
111
- // attaches, then `setSource` repoints it at the resolved settings scope.
112
- // A thunk, not a snapshot — reads see the current resolution at call time,
113
- // so the routes follow a stored edit without re-registering anything.
114
- let sectionSource = () => sectionOf(config);
116
+ const currentConfig = () => ctx.fiber?.config ?? config;
115
117
  const deps = () => ({
116
118
  exec: childProcessExec,
117
- sectionRootDir: () => sectionSource().rootDir,
118
- sectionFetchBeforeCreate: () => sectionSource().fetchBeforeCreate,
119
+ sectionRootDir: () => readVolatile(currentConfig().rootDir),
120
+ sectionFetchBeforeCreate: () => readVolatile(currentConfig().fetchBeforeCreate),
121
+ sectionPostCreateCopyFiles: () => readVolatile(currentConfig().postCreateCopyFiles),
119
122
  home: () => homedir(),
120
123
  envHome: () => process.env.DSH_HOME,
121
124
  });
122
- // Host 0.1.2 hosts section installation on the provider itself: the same
123
- // composition-entry base, validate, setSource, and onChange hooks ride
124
- // `SettingsProvider.installSection`, reached through a settings injection.
125
- // The registration is an effect on this plugin's fiber either way, so a
126
- // late-attaching settings service is handled by the injection itself.
125
+ // In dsh 0.1.7+, the settings service projects volatile Config fields into forms.
126
+ // We configure auto: false to inform the host that this plugin provides its own
127
+ // dedicated configuration card (via `plugins.bundle.config`).
127
128
  ctx.inject(['settings'], (settingsCtx) => {
128
- settingsCtx.settings.installSection(ctx, GIT_WORKTREE_NS, sectionSchema, sectionOf(config), {
129
- validate: value => {
130
- validateRootDir(value.rootDir);
131
- if (value.groupSidebar !== undefined && typeof value.groupSidebar !== 'boolean') {
132
- throw new Error('groupSidebar must be a boolean');
133
- }
134
- if (value.fetchBeforeCreate !== undefined && typeof value.fetchBeforeCreate !== 'boolean') {
135
- throw new Error('fetchBeforeCreate must be a boolean');
136
- }
137
- if (value.autoPruneWorktrees !== undefined && typeof value.autoPruneWorktrees !== 'boolean') {
138
- throw new Error('autoPruneWorktrees must be a boolean');
139
- }
140
- validateKeepWorktrees(value.keepWorktrees);
141
- },
142
- setSource: (source) => { sectionSource = source; },
143
- onChange: () => {
144
- // The storage root takes effect live: the routes read the section
145
- // source per request, so a committed edit needs no action here.
146
- },
147
- });
148
- });
149
- // One-shot legacy migration: the pre-0.3 plugin persisted its own
150
- // ~/.dsh/git-work-tree/settings.json. Registered after installSection
151
- // so the namespace is on the ledger by the time this fiber runs; a failure
152
- // (or a user layer that already chose) leaves both documents exactly as
153
- // they are, and the next startup retries.
154
- ctx.inject(['settings'], (sctx) => {
155
- const file = settingsFileOf(homedir());
156
- void (async () => {
157
- const legacy = await loadLegacySettings(file);
158
- const descriptor = sctx.settings.describe().find(d => d.ns === GIT_WORKTREE_NS);
159
- if (descriptor === undefined)
160
- return;
161
- const user = descriptor.user;
162
- const userLayer = typeof user === 'object' && user !== null ? user : undefined;
163
- const planned = planLegacyMigration(legacy, userLayer);
164
- if (planned === undefined)
165
- return;
166
- try {
167
- await sctx.settings.update(GIT_WORKTREE_NS, { rootDir: planned });
168
- await rename(file, migratedFileOf(file));
169
- console.log(`[git-worktree] legacy settings migrated to the settings document (${planned})`);
170
- }
171
- catch (error) {
172
- console.warn('[git-worktree] legacy settings migration failed:', error instanceof Error ? error.message : String(error));
173
- }
174
- })();
129
+ settingsCtx.effect(() => settingsCtx.settings.configure({ auto: false }, ctx.fiber), 'git-worktree: settings presentation policy');
175
130
  });
176
131
  ctx.inject(['webServer'], (webCtx) => {
177
132
  /** Send one outcome as JSON; no-store because repo facts are point-in-time. */
package/lib/routes.d.ts CHANGED
@@ -2,7 +2,8 @@
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 { type DirExists, type Exec } from './git.js';
5
+ import { type CopyFilesSeams } from './copy-files.js';
6
+ import { type DirExists, type ExcludeSeams, type Exec } from './git.js';
6
7
  import type { CreateBranchResult, CreateWorktreeResult, EnsureDirectoryResult, FetchResult, GroupWorkspacesResult, InspectWorktreeResult, PathExistsResult, PurgeDirectoryResult, RemoveWorktreeResult, RepoStatus, RouteError, SwitchResult, UpdateResult, WorktreesAllResult } from './wire.js';
7
8
  /** Everything the handlers need from the host half. */
8
9
  export interface RouteDeps {
@@ -11,12 +12,18 @@ export interface RouteDeps {
11
12
  sectionRootDir: () => string | undefined;
12
13
  /** Whether a worktree creation syncs the remotes first (absent = off). */
13
14
  sectionFetchBeforeCreate: () => boolean | undefined;
15
+ /** Post-create configuration files to copy when .worktreeinclude is absent. */
16
+ sectionPostCreateCopyFiles?: () => string[] | undefined;
14
17
  /** User home directory seam. */
15
18
  home: () => string;
16
19
  /** `$DSH_HOME` environment value seam. */
17
20
  envHome: () => string | undefined;
18
21
  /** Worktree-registration existence seam (tests substitute). */
19
22
  dirExists?: DirExists;
23
+ /** Local-ignore write seams (tests substitute). */
24
+ excludeSeams?: ExcludeSeams;
25
+ /** Post-create file copy seams (tests substitute). */
26
+ copyFilesSeams?: CopyFilesSeams;
20
27
  /** Directory probe seam over fs.stat (true = exists AND is a directory);
21
28
  * tests substitute. */
22
29
  statDirectory?: (path: string) => Promise<boolean>;
@@ -52,31 +59,41 @@ export interface RouteOutcome {
52
59
  */
53
60
  export declare function handleGroupWorktrees(deps: RouteDeps, body: unknown): Promise<RouteOutcome>;
54
61
  /**
55
- * POST /worktrees-all — git facts for every DIRECT child directory of the
56
- * resolved worktree storage root (the slots this plugin plans as
57
- * `<repoName>-<branch>`). The management dialog's data source: one scan
58
- * answers for all repositories at once, orphan directories included (a
59
- * child that probes as no git repository comes back with null facts rather
60
- * than being dropped — the dialog shows it as unrecognized). A missing
61
- * storage root answers an empty list; per-child probe failures degrade to
62
- * null facts, never a 500 — the dialog must render, not error out. A root
63
- * holding more than {@link SCAN_CHILDREN_LIMIT} children answers its first
64
- * slice plus `truncated`, so a misconfigured rootDir cannot turn one dialog
62
+ * POST /worktrees-all — git facts for every DIRECT child directory of the two
63
+ * storage locations the plugin has ever used, merged:
64
+ *
65
+ * - legacy: the resolved central storage root (today a read-only historical
66
+ * location — existing worktrees stay put, `rootDir` still resolves it);
67
+ * - project: `<repo>/.dsh/gitworktree` under every DISTINCT repository root
68
+ * derived from the caller's registered workspace paths (the current
69
+ * layout — its path prefix is what the workspace tree nests under).
70
+ *
71
+ * The management dialog's data source (and, through it, the lazy prune's):
72
+ * one scan answers for all repositories at once, orphan directories included
73
+ * (a child that probes as no git repository comes back with null facts
74
+ * rather than being dropped — the dialog shows it as unrecognized). Missing
75
+ * locations answer their half as an empty list; per-child probe failures
76
+ * degrade to null facts, never a 500 — the dialog must render, not error
77
+ * out. Each location that holds more than {@link SCAN_CHILDREN_LIMIT}
78
+ * children answers its first slice, and any truncation marks the whole
79
+ * response `truncated`, so a misconfigured location cannot turn one dialog
65
80
  * open into thousands of git spawns.
66
81
  * @param deps - host dependencies.
82
+ * @param body - parsed request body: `{ workspaces? }`.
67
83
  */
68
- export declare function handleWorktreesAll(deps: RouteDeps): Promise<RouteOutcome>;
84
+ export declare function handleWorktreesAll(deps: RouteDeps, body: unknown): Promise<RouteOutcome>;
69
85
  /** Real fs-backed recursive force rm (Windows file-lock retries included). */
70
86
  export declare function fsRmRecursive(path: string): Promise<void>;
71
87
  /**
72
- * POST /purge — delete a NON-git directory sitting DIRECTLY inside the
73
- * resolved worktree storage root: the orphaned leftover a half-failed
74
- * `worktree remove` can leave behind (git registration and the .git file
75
- * already gone, contents stranded on disk). Triple-gated: one level below
76
- * the root (resolved forms, same slot boundary as /ensure-directory), a
77
- * real directory, and NOT a git repository — anything git still recognizes
78
- * must go through /remove, where the removal carries the session-archive
79
- * and unregistration half. Deletion is a plain recursive force rm.
88
+ * POST /purge — delete a NON-git directory sitting DIRECTLY inside one of the
89
+ * plugin's two storage layouts: the legacy central root or a repository's
90
+ * `.dsh/gitworktree`. The orphaned leftover a half-failed `worktree remove`
91
+ * can leave behind (git registration and the .git file already gone,
92
+ * contents stranded on disk). Triple-gated: one level below a storage
93
+ * location (resolved forms, same slot boundary as /ensure-directory), a real
94
+ * directory, and NOT a git repository — anything git still recognizes must
95
+ * go through /remove, where the removal carries the session-archive and
96
+ * unregistration half. Deletion is a plain recursive force rm.
80
97
  * @param deps - host dependencies.
81
98
  * @param body - parsed request body: `{ path }`.
82
99
  */
@@ -88,9 +105,14 @@ export declare function handlePurgeDirectory(deps: RouteDeps, body: unknown): Pr
88
105
  */
89
106
  export declare function handleStatus(deps: RouteDeps, path: string | undefined): Promise<RouteOutcome>;
90
107
  /**
91
- * POST /worktree 鈥?create or reuse the worktree for a branch, then report the
92
- * directory so the client can register it as a workspace. With `cutout: true`
93
- * the branch is the CURRENT checkout (occupied by the main worktree, so git
108
+ * POST /worktree — create or reuse the worktree for a branch, then report the
109
+ * directory so the client can register it as a workspace. The worktree lands
110
+ * at `<repo>/.dsh/gitworktree/<branch>` (path prefix = repository, so the
111
+ * native workspace tree nests it under its repository automatically); an
112
+ * existing registration for the branch ANYWHERE is reused first (the
113
+ * repository-wide worktree list is location-independent — legacy-central
114
+ * worktrees keep being returned, never duplicated). With `cutout: true` the
115
+ * branch is the CURRENT checkout (occupied by the main worktree, so git
94
116
  * refuses to add it): a new branch is cut out of it (`<branch>-wt`, first
95
117
  * free `-wt<N>` suffix) and isolated in the fresh worktree instead.
96
118
  * @param deps - host dependencies.
@@ -187,8 +209,9 @@ export declare function handleRemoveWorktree(deps: RouteDeps, body: unknown): Pr
187
209
  export declare function handlePathExists(deps: RouteDeps, body: unknown): Promise<RouteOutcome>;
188
210
  /**
189
211
  * POST /ensure-directory — recreate a MISSING worktree storage slot
190
- * (`mkdir -p`). Strictly gated to paths sitting DIRECTLY inside the resolved
191
- * worktree storage root: those slots were planned and created by this plugin,
212
+ * (`mkdir -p`). Strictly gated to paths sitting DIRECTLY inside one of the
213
+ * plugin's two storage layouts (the legacy central root, or a repository's
214
+ * `.dsh/gitworktree`): those slots were planned and created by this plugin,
192
215
  * so rebuilding the empty folder is self-healing (historical sessions
193
216
  * reattach automatically once realpath matches again — DSH keeps the
194
217
  * workspace accounting and filters membership by the session header's cwd).