@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.
@@ -0,0 +1,59 @@
1
+ /**
2
+ * Post-create configuration file copying: copies untracked local files
3
+ * declared in `.worktreeinclude` (or fallback config) from the main worktree
4
+ * to a fresh worktree directory.
5
+ */
6
+ /** One failed copy record with error details. */
7
+ export interface CopyFailure {
8
+ file: string;
9
+ error: string;
10
+ }
11
+ /** Pure I/O seams for file reading, existence probe, directory creation, and copying. */
12
+ export interface CopyFilesSeams {
13
+ /** Read file as UTF-8; null if missing (ENOENT). */
14
+ readFile?: (path: string) => Promise<string | null>;
15
+ /** Check whether a file or directory exists. */
16
+ exists: (path: string) => Promise<boolean>;
17
+ /** Copy file from src to dest. */
18
+ copyFile: (src: string, dest: string) => Promise<void>;
19
+ /** Recursive mkdir. */
20
+ mkdir: (path: string) => Promise<void>;
21
+ }
22
+ /** Real fs-backed seams. */
23
+ export declare const fsCopyFilesSeams: CopyFilesSeams;
24
+ /**
25
+ * Parse `.worktreeinclude` content: line-by-line exact relative paths.
26
+ * Skips empty lines and lines starting with `#`. MVP has no glob expansion
27
+ * or `!` negation support.
28
+ */
29
+ export declare function parseWorktreeInclude(content: string): string[];
30
+ /**
31
+ * Validate that a path is a safe relative path.
32
+ * Rejects empty paths, absolute paths (both POSIX and Windows shapes),
33
+ * and any path traversal containing `..` segments.
34
+ */
35
+ export declare function isSafeRelativePath(relPath: string): boolean;
36
+ /**
37
+ * Copy declared files from main worktree (repoRoot) to targetPath.
38
+ * - Missing source files are silently skipped.
39
+ * - Existing destination files are not overwritten.
40
+ * - Parent directories are created recursively.
41
+ * - Unsafe paths and copy errors are collected into failures without throwing.
42
+ */
43
+ export declare function copyWorktreeFiles(files: readonly string[], repoRoot: string, targetPath: string, seams?: CopyFilesSeams): Promise<CopyFailure[]>;
44
+ /**
45
+ * Format copy failures into a single warning message for the client toast.
46
+ */
47
+ export declare function formatCopyWarning(failures: readonly CopyFailure[]): string | undefined;
48
+ export interface RunCopyDeps {
49
+ sectionPostCreateCopyFiles?: () => string[] | undefined;
50
+ copyFilesSeams?: CopyFilesSeams;
51
+ }
52
+ /**
53
+ * Coordinate post-create copying after a fresh worktree is created:
54
+ * 1. Try reading `<repoRoot>/.worktreeinclude`.
55
+ * 2. If present, parse it (fully overrides fallback, even if empty).
56
+ * 3. If absent, fallback to `sectionPostCreateCopyFiles`.
57
+ * 4. Perform copying and return formatted copyWarning if any failures occur.
58
+ */
59
+ export declare function runPostCreateCopy(deps: RunCopyDeps, repoRoot: string, targetPath: string): Promise<string | undefined>;
@@ -0,0 +1,148 @@
1
+ /**
2
+ * Post-create configuration file copying: copies untracked local files
3
+ * declared in `.worktreeinclude` (or fallback config) from the main worktree
4
+ * to a fresh worktree directory.
5
+ */
6
+ import { copyFile, mkdir, readFile, stat } from 'node:fs/promises';
7
+ import { dirname, isAbsolute, join } from 'node:path';
8
+ /** Real fs-backed seams. */
9
+ export const fsCopyFilesSeams = {
10
+ readFile: async (path) => {
11
+ try {
12
+ return await readFile(path, 'utf8');
13
+ }
14
+ catch (error) {
15
+ if (error.code === 'ENOENT')
16
+ return null;
17
+ throw error;
18
+ }
19
+ },
20
+ exists: async (path) => {
21
+ try {
22
+ await stat(path);
23
+ return true;
24
+ }
25
+ catch {
26
+ return false;
27
+ }
28
+ },
29
+ copyFile: async (src, dest) => {
30
+ await copyFile(src, dest);
31
+ },
32
+ mkdir: async (path) => {
33
+ await mkdir(path, { recursive: true });
34
+ },
35
+ };
36
+ /**
37
+ * Parse `.worktreeinclude` content: line-by-line exact relative paths.
38
+ * Skips empty lines and lines starting with `#`. MVP has no glob expansion
39
+ * or `!` negation support.
40
+ */
41
+ export function parseWorktreeInclude(content) {
42
+ const result = [];
43
+ const lines = content.split(/\r?\n/);
44
+ for (const raw of lines) {
45
+ const trimmed = raw.trim();
46
+ if (trimmed === '' || trimmed.startsWith('#'))
47
+ continue;
48
+ if (!result.includes(trimmed)) {
49
+ result.push(trimmed);
50
+ }
51
+ }
52
+ return result;
53
+ }
54
+ /**
55
+ * Validate that a path is a safe relative path.
56
+ * Rejects empty paths, absolute paths (both POSIX and Windows shapes),
57
+ * and any path traversal containing `..` segments.
58
+ */
59
+ export function isSafeRelativePath(relPath) {
60
+ if (relPath.trim() === '')
61
+ return false;
62
+ if (isAbsolute(relPath) || relPath.startsWith('/') || relPath.startsWith('\\') || /^[a-zA-Z]:[\\/]/.test(relPath)) {
63
+ return false;
64
+ }
65
+ const segments = relPath.split(/[\\/]/);
66
+ if (segments.some(segment => segment === '..')) {
67
+ return false;
68
+ }
69
+ return true;
70
+ }
71
+ /**
72
+ * Copy declared files from main worktree (repoRoot) to targetPath.
73
+ * - Missing source files are silently skipped.
74
+ * - Existing destination files are not overwritten.
75
+ * - Parent directories are created recursively.
76
+ * - Unsafe paths and copy errors are collected into failures without throwing.
77
+ */
78
+ export async function copyWorktreeFiles(files, repoRoot, targetPath, seams = fsCopyFilesSeams) {
79
+ const failures = [];
80
+ const unique = Array.from(new Set(files));
81
+ for (const relPath of unique) {
82
+ if (!isSafeRelativePath(relPath)) {
83
+ failures.push({ file: relPath, error: 'path traversal or absolute path is not allowed' });
84
+ continue;
85
+ }
86
+ const src = join(repoRoot, relPath);
87
+ const dest = join(targetPath, relPath);
88
+ try {
89
+ if (!(await seams.exists(src))) {
90
+ continue;
91
+ }
92
+ if (await seams.exists(dest)) {
93
+ continue;
94
+ }
95
+ await seams.mkdir(dirname(dest));
96
+ await seams.copyFile(src, dest);
97
+ }
98
+ catch (error) {
99
+ failures.push({
100
+ file: relPath,
101
+ error: error instanceof Error ? error.message : String(error),
102
+ });
103
+ }
104
+ }
105
+ return failures;
106
+ }
107
+ /**
108
+ * Format copy failures into a single warning message for the client toast.
109
+ */
110
+ export function formatCopyWarning(failures) {
111
+ if (failures.length === 0)
112
+ return undefined;
113
+ const details = failures.map(f => `${f.file}: ${f.error}`).join('; ');
114
+ return `Failed to copy configuration files: ${details}`;
115
+ }
116
+ /**
117
+ * Coordinate post-create copying after a fresh worktree is created:
118
+ * 1. Try reading `<repoRoot>/.worktreeinclude`.
119
+ * 2. If present, parse it (fully overrides fallback, even if empty).
120
+ * 3. If absent, fallback to `sectionPostCreateCopyFiles`.
121
+ * 4. Perform copying and return formatted copyWarning if any failures occur.
122
+ */
123
+ export async function runPostCreateCopy(deps, repoRoot, targetPath) {
124
+ const seams = deps.copyFilesSeams ?? fsCopyFilesSeams;
125
+ const includePath = join(repoRoot, '.worktreeinclude');
126
+ let files;
127
+ try {
128
+ const readFn = seams.readFile ?? fsCopyFilesSeams.readFile;
129
+ const content = await readFn(includePath);
130
+ if (content !== null) {
131
+ files = parseWorktreeInclude(content);
132
+ }
133
+ }
134
+ catch (error) {
135
+ return `Failed to read .worktreeinclude: ${error instanceof Error ? error.message : String(error)}`;
136
+ }
137
+ if (files === undefined) {
138
+ const fallback = deps.sectionPostCreateCopyFiles?.();
139
+ if (fallback !== undefined && fallback.length > 0) {
140
+ files = [...fallback];
141
+ }
142
+ }
143
+ if (files === undefined || files.length === 0) {
144
+ return undefined;
145
+ }
146
+ const failures = await copyWorktreeFiles(files, repoRoot, targetPath, seams);
147
+ return formatCopyWarning(failures);
148
+ }
package/lib/git.d.ts CHANGED
@@ -287,3 +287,37 @@ export declare function removeWorktree(exec: Exec, repoRoot: string, worktreePat
287
287
  * binary surfaces the same way — a non-zero exit through the seam).
288
288
  */
289
289
  export declare function probeWorkspaceGit(exec: Exec, path: string): Promise<WorkspaceGitFacts | undefined>;
290
+ /** The one local-ignore rule the project-internal worktree layout needs.
291
+ * Exactly this pattern — NOT `/.dsh/` — so project-level `.dsh/` files a user
292
+ * may want to commit stay trackable. */
293
+ export declare const WORKTREE_EXCLUDE_RULE = "/.dsh/gitworktree/";
294
+ /** fs seams for {@link appendWorktreeExclude}; tests substitute. */
295
+ export interface ExcludeSeams {
296
+ /** Whole file as UTF-8 text; a missing file reads as '' (the rule is
297
+ * simply not there yet). */
298
+ readFile: (path: string) => Promise<string>;
299
+ /** Append text to the end of the file, creating it when missing. */
300
+ appendFile: (path: string, text: string) => Promise<void>;
301
+ /** Recursive mkdir for the `info` directory (git init ships it; a stripped
302
+ * or hand-moved clone may not). */
303
+ mkdir: (path: string) => Promise<void>;
304
+ }
305
+ /** Real fs-backed seams. */
306
+ export declare const fsExcludeSeams: ExcludeSeams;
307
+ /**
308
+ * Idempotently add {@link WORKTREE_EXCLUDE_RULE} to the repository's local
309
+ * ignore file (`<repo>/.git/info/exclude`, reachable from every worktree
310
+ * because it lives in the SHARED git dir): the git-blessed place for rules
311
+ * that must stay private to this clone — never committed, never cloned.
312
+ *
313
+ * The write never blocks a worktree creation (the folder cannot be rolled
314
+ * back once built), so a failure is returned as text for the response to
315
+ * carry, not thrown. Idempotent by full-content line match: an absent rule
316
+ * is appended behind a newline guard so it never glues onto the user's last
317
+ * line; an existing rule — or any pre-existing content — is left untouched.
318
+ * @param seams - fs seams (tests substitute).
319
+ * @param repoRoot - the repository's main worktree directory.
320
+ * @returns undefined on success (or the rule already being present); the
321
+ * failure text otherwise.
322
+ */
323
+ export declare function appendWorktreeExclude(seams: ExcludeSeams, repoRoot: string): Promise<string | undefined>;
package/lib/git.js CHANGED
@@ -5,8 +5,8 @@
5
5
  */
6
6
  import { execFile } from 'node:child_process';
7
7
  import { existsSync, readdirSync } from 'node:fs';
8
- import { rm } from 'node:fs/promises';
9
- import { basename, dirname, isAbsolute, normalize, resolve } from 'node:path';
8
+ import { appendFile, mkdir, readFile, rm } from 'node:fs/promises';
9
+ import { basename, dirname, isAbsolute, join, normalize, resolve } from 'node:path';
10
10
  import { localBranchName } from './normalize.js';
11
11
  /** Failure of one git invocation: non-zero exit with the stderr text. */
12
12
  export class GitError extends Error {
@@ -91,8 +91,19 @@ function isDirBusyGitError(error) {
91
91
  * @param gitDir - the SHARED git dir (`--git-common-dir`) every worktree
92
92
  * resolves back to.
93
93
  */
94
+ /**
95
+ * Whether two paths refer to the same directory on disk, accounting for
96
+ * trailing slashes, slash directions, and Windows case-insensitivity.
97
+ */
98
+ function isSamePath(a, b) {
99
+ const normA = normalize(resolve(a));
100
+ const normB = normalize(resolve(b));
101
+ return process.platform === 'win32'
102
+ ? normA.toLowerCase() === normB.toLowerCase()
103
+ : normA === normB;
104
+ }
94
105
  function isMainWorktree(toplevel, gitDir) {
95
- return normalize(resolve(toplevel, '.git')) === gitDir;
106
+ return isSamePath(resolve(toplevel, '.git'), gitDir);
96
107
  }
97
108
  /**
98
109
  * Resolve a directory to repository facts, or undefined outside any git
@@ -581,6 +592,10 @@ export async function probeWorkspaceGit(exec, path) {
581
592
  if (top === '' || commonDir === '')
582
593
  return undefined;
583
594
  const toplevel = normalize(top);
595
+ // A directory whose git toplevel is an ancestor is an ordinary subdirectory,
596
+ // not an independent worktree or repository root.
597
+ if (!isSamePath(toplevel, path))
598
+ return undefined;
584
599
  // Git outputs carry forward slashes on Windows — normalize every derived
585
600
  // path so consumers can compare against join()-built ones.
586
601
  const gitDir = normalize(resolve(path, commonDir));
@@ -591,3 +606,58 @@ export async function probeWorkspaceGit(exec, path) {
591
606
  main: isMainWorktree(toplevel, gitDir),
592
607
  };
593
608
  }
609
+ /** The one local-ignore rule the project-internal worktree layout needs.
610
+ * Exactly this pattern — NOT `/.dsh/` — so project-level `.dsh/` files a user
611
+ * may want to commit stay trackable. */
612
+ export const WORKTREE_EXCLUDE_RULE = '/.dsh/gitworktree/';
613
+ /** Real fs-backed seams. */
614
+ export const fsExcludeSeams = {
615
+ readFile: async (path) => {
616
+ try {
617
+ return await readFile(path, 'utf8');
618
+ }
619
+ catch (error) {
620
+ if (error.code === 'ENOENT')
621
+ return '';
622
+ throw error;
623
+ }
624
+ },
625
+ appendFile: async (path, text) => {
626
+ await appendFile(path, text, 'utf8');
627
+ },
628
+ mkdir: async (path) => {
629
+ await mkdir(path, { recursive: true });
630
+ },
631
+ };
632
+ /**
633
+ * Idempotently add {@link WORKTREE_EXCLUDE_RULE} to the repository's local
634
+ * ignore file (`<repo>/.git/info/exclude`, reachable from every worktree
635
+ * because it lives in the SHARED git dir): the git-blessed place for rules
636
+ * that must stay private to this clone — never committed, never cloned.
637
+ *
638
+ * The write never blocks a worktree creation (the folder cannot be rolled
639
+ * back once built), so a failure is returned as text for the response to
640
+ * carry, not thrown. Idempotent by full-content line match: an absent rule
641
+ * is appended behind a newline guard so it never glues onto the user's last
642
+ * line; an existing rule — or any pre-existing content — is left untouched.
643
+ * @param seams - fs seams (tests substitute).
644
+ * @param repoRoot - the repository's main worktree directory.
645
+ * @returns undefined on success (or the rule already being present); the
646
+ * failure text otherwise.
647
+ */
648
+ export async function appendWorktreeExclude(seams, repoRoot) {
649
+ try {
650
+ const infoDir = join(repoRoot, '.git', 'info');
651
+ const excludePath = join(infoDir, 'exclude');
652
+ const text = await seams.readFile(excludePath);
653
+ if (!text.split(/\r?\n/).includes(WORKTREE_EXCLUDE_RULE)) {
654
+ await seams.mkdir(infoDir);
655
+ const prefix = text === '' || text.endsWith('\n') ? '' : '\n';
656
+ await seams.appendFile(excludePath, `${prefix}${WORKTREE_EXCLUDE_RULE}\n`);
657
+ }
658
+ return undefined;
659
+ }
660
+ catch (error) {
661
+ return error instanceof Error ? error.message : String(error);
662
+ }
663
+ }
package/lib/index.d.ts CHANGED
@@ -1,45 +1,39 @@
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
- import type { Context } from '@deepseek-ai/cordis';
8
+ import type { Context, Volatile } from '@deepseek-ai/cordis';
16
9
  import z from '@deepseek-ai/schemastery';
17
10
  export declare const name = "dsh-git-worktree";
18
11
  export declare const inject: never[];
19
12
  export interface Config {
20
13
  /** Worktree storage root; defaults to `$DSH_HOME/gitworktree` (`~/.dsh/gitworktree`). */
21
- rootDir?: string;
14
+ rootDir?: Volatile<string | undefined> | string;
22
15
  /** Sidebar git grouping on/off; absent = on (the composition-entry layer's default). */
23
- groupSidebar?: boolean;
16
+ groupSidebar?: Volatile<boolean> | boolean;
24
17
  /** Fetch every remote before creating a worktree; absent = off. A failed
25
18
  * fetch never blocks the creation (see the /worktree route). */
26
- fetchBeforeCreate?: boolean;
19
+ fetchBeforeCreate?: Volatile<boolean> | boolean;
27
20
  /** Prune stale worktrees lazily after each creation; absent = off. */
28
- autoPruneWorktrees?: boolean;
21
+ autoPruneWorktrees?: Volatile<boolean> | boolean;
29
22
  /** Global cap the lazy prune trims down to (valid git worktrees only);
30
23
  * absent = 30. */
31
- keepWorktrees?: number;
24
+ keepWorktrees?: Volatile<number> | number;
25
+ /** Post-create configuration files to copy when .worktreeinclude is absent;
26
+ * absent = none. */
27
+ postCreateCopyFiles?: Volatile<string[]> | string[];
32
28
  }
29
+ /** The shipped prune cap (whole storage root, valid git worktrees only). */
30
+ export declare const KEEP_WORKTREES_DEFAULT = 30;
33
31
  /**
34
32
  * Cordis resolves the composition entry's config through this schema before
35
- * `apply` runs (official plugin-config convention: export the `Config` type
36
- * and a same-named Schemastery schema). It fills the `groupSidebar` default;
37
- * `rootDir` passes through untouched — its absence stays observable so the
38
- * settings section keeps spelling the resolved default. Constraints the
39
- * schema cannot express still fail loudly in validateConfig below (absolute
40
- * path; unknown keys — schemastery keeps extras instead of rejecting them).
33
+ * `apply` runs. In dsh 0.1.7+, fields marked with `.volatile()` are projected
34
+ * by the settings service into live configuration forms.
41
35
  */
42
- export declare const Config: z<Config>;
36
+ export declare const Config: z;
43
37
  /** Reject stale or misspelled config keys before defaults can hide them. */
44
38
  export declare function validateConfig(config: Config): void;
45
39
  /**
@@ -64,19 +58,17 @@ export interface SectionConfig {
64
58
  autoPruneWorktrees?: boolean;
65
59
  /** Global cap the lazy prune trims down to; absent = 30. */
66
60
  keepWorktrees?: number;
61
+ /** Post-create configuration files to copy when .worktreeinclude is absent. */
62
+ postCreateCopyFiles?: string[];
67
63
  }
68
- /** Schema resolving the `git-worktree` settings section. */
69
- export declare const sectionSchema: z<SectionConfig>;
70
- /** The shipped prune cap (whole storage root, valid git worktrees only). */
71
- export declare const KEEP_WORKTREES_DEFAULT = 30;
72
64
  /** The section-shaped view of a config: absent keys stay absent
73
65
  * (`exactOptionalPropertyTypes`) except the switches, which spell their
74
66
  * shipped defaults so a user-layer unset can always fall back to them. */
75
67
  export declare function sectionOf(config: Config): SectionConfig;
76
68
  /**
77
- * Plugin apply: install the settings section, migrate any legacy stored root
78
- * into it, then mount routes on any webServer that comes and goes.
69
+ * Plugin apply: mount the settings presentation policy and HTTP routes on any
70
+ * webServer that comes and goes.
79
71
  * @param ctx - host cordis context.
80
- * @param config - the composition entry config (the section's base layer).
72
+ * @param config - the composition entry config.
81
73
  */
82
74
  export declare function apply(ctx: Context, config?: Config): void;