@laoyuehanni/dsh-git-worktree 0.4.4 → 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/README.md +19 -16
- package/README.zh.md +19 -16
- package/lib/client.js +2796 -3761
- package/lib/copy-files.d.ts +59 -0
- package/lib/copy-files.js +148 -0
- package/lib/git.d.ts +100 -8
- package/lib/git.js +155 -14
- package/lib/index.d.ts +47 -29
- package/lib/index.js +92 -92
- package/lib/routes.d.ts +99 -11
- package/lib/routes.js +374 -47
- package/lib/settings.d.ts +0 -27
- package/lib/settings.js +0 -50
- package/lib/wire.d.ts +129 -5
- package/lib/wire.js +14 -1
- package/package.json +59 -41
|
@@ -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
|
@@ -32,6 +32,17 @@ export interface RepoFacts {
|
|
|
32
32
|
repoRoot: string;
|
|
33
33
|
/** Main repository directory basename. */
|
|
34
34
|
repoName: string;
|
|
35
|
+
/** The QUERIED directory's own toplevel — the worktree the session
|
|
36
|
+
* actually sits in. Repository-wide commands (branch refs, fetch,
|
|
37
|
+
* worktree registration) run at {@link RepoFacts.repoRoot}; commands that
|
|
38
|
+
* act on the session's own checkout (switch/update/create-and-check-out)
|
|
39
|
+
* run HERE, or a linked-worktree session would silently operate on the
|
|
40
|
+
* main checkout instead. */
|
|
41
|
+
toplevel: string;
|
|
42
|
+
/** Whether the QUERIED directory is the main worktree — see
|
|
43
|
+
* {@link isMainWorktree}. `repoRoot` cannot answer this: it names the main
|
|
44
|
+
* checkout from every worktree by construction. */
|
|
45
|
+
main: boolean;
|
|
35
46
|
/** Branch checked out by the queried directory. */
|
|
36
47
|
currentBranch: string;
|
|
37
48
|
branches: BranchEntry[];
|
|
@@ -63,6 +74,18 @@ export declare function fsSweepDir(path: string): Promise<'gone' | 'empty' | 'oc
|
|
|
63
74
|
* @param dirExists - existence seam for stale-registration filtering.
|
|
64
75
|
*/
|
|
65
76
|
export declare function probeRepo(exec: Exec, path: string, dirExists?: DirExists): Promise<RepoFacts | undefined>;
|
|
77
|
+
/**
|
|
78
|
+
* Resolve a branch display name against the authoritative branch list of the
|
|
79
|
+
* repository. Exported for the /worktree route's fetch gate: the pre-create
|
|
80
|
+
* remote sync only earns its round trip when the display name is REMOTE-only
|
|
81
|
+
* (a local branch's worktree never consumes fetched refs).
|
|
82
|
+
* @returns the local name plus the tracking remote when the display name is
|
|
83
|
+
* remote-only, or undefined when neither shape exists.
|
|
84
|
+
*/
|
|
85
|
+
export declare function resolveBranch(exec: Exec, repoRoot: string, branch: string): Promise<{
|
|
86
|
+
local: string;
|
|
87
|
+
remote: string | undefined;
|
|
88
|
+
} | undefined>;
|
|
66
89
|
/**
|
|
67
90
|
* Create (or reuse) the worktree for one branch.
|
|
68
91
|
*
|
|
@@ -119,18 +142,53 @@ export declare function addWorktreeCutout(exec: Exec, repoRoot: string, base: st
|
|
|
119
142
|
*/
|
|
120
143
|
export declare function switchBranch(exec: Exec, repoRoot: string, branch: string): Promise<string>;
|
|
121
144
|
/**
|
|
122
|
-
* Create a NEW branch
|
|
123
|
-
*
|
|
124
|
-
*
|
|
125
|
-
*
|
|
126
|
-
*
|
|
127
|
-
*
|
|
145
|
+
* Create a NEW branch. Three shapes:
|
|
146
|
+
*
|
|
147
|
+
* - no `from`: cut from the current checkout and check it out in place
|
|
148
|
+
* (`git switch -c`) — the cut point is whatever the queried directory's
|
|
149
|
+
* HEAD points at, so a detached or unborn checkout cuts from the current
|
|
150
|
+
* commit too. Runs at the queried directory's own toplevel — a session
|
|
151
|
+
* inside a linked worktree creates and checks out within that worktree,
|
|
152
|
+
* never the main checkout (the same semantics as {@link switchBranch}).
|
|
153
|
+
* - `from` without `checkout`: create AT that start point WITHOUT touching
|
|
154
|
+
* any checkout (`git branch`) — a create aimed at another branch must
|
|
155
|
+
* not move this session's HEAD.
|
|
156
|
+
* - `from` with `checkout`: create at the start point AND check it out
|
|
157
|
+
* here in one stroke (`git switch -c <name> <from>`).
|
|
128
158
|
* @param exec - executor seam.
|
|
129
159
|
* @param cwd - directory whose HEAD the branch is cut from (worktree toplevel).
|
|
130
160
|
* @param name - new branch name (git validates; failures raise GitError).
|
|
131
|
-
* @
|
|
161
|
+
* @param from - optional start point; absent keeps the in-place semantics.
|
|
162
|
+
* @param checkout - with `from`, also check the new branch out here.
|
|
163
|
+
* @returns the branch name now created (checked out unless created at a
|
|
164
|
+
* start point with `checkout` false).
|
|
165
|
+
*/
|
|
166
|
+
export declare function createBranch(exec: Exec, cwd: string, name: string, from?: string, checkout?: boolean): Promise<string>;
|
|
167
|
+
/**
|
|
168
|
+
* Rename a LOCAL branch (`git branch -m`): branch refs are repository-wide,
|
|
169
|
+
* so the command runs at the repository root and every worktree HEAD pointing
|
|
170
|
+
* at the old name follows the ref. Git validates the new name and refuses a
|
|
171
|
+
* target that already exists; remote branches are not renameable (not ours).
|
|
172
|
+
* @param exec - executor seam.
|
|
173
|
+
* @param repoRoot - main worktree directory.
|
|
174
|
+
* @param name - branch to rename.
|
|
175
|
+
* @param newName - the new local name.
|
|
176
|
+
* @returns the new name.
|
|
132
177
|
*/
|
|
133
|
-
export declare function
|
|
178
|
+
export declare function renameBranch(exec: Exec, repoRoot: string, name: string, newName: string): Promise<string>;
|
|
179
|
+
/**
|
|
180
|
+
* Delete a LOCAL branch (`git branch -d`, the SAFE form): git refuses a
|
|
181
|
+
* branch with unmerged commits ("not fully merged") and one checked out in
|
|
182
|
+
* any worktree — both caller-side state, mapped to 400 by the route. No
|
|
183
|
+
* `-D` force variant on purpose: a menu click must never discard commits
|
|
184
|
+
* (the terminal is the place for deliberate force-deletes). Runs at the
|
|
185
|
+
* repository root; remote branches are not ours to delete.
|
|
186
|
+
* @param exec - executor seam.
|
|
187
|
+
* @param repoRoot - main worktree directory.
|
|
188
|
+
* @param name - branch to delete.
|
|
189
|
+
* @returns the name of the branch that was deleted.
|
|
190
|
+
*/
|
|
191
|
+
export declare function deleteBranch(exec: Exec, repoRoot: string, name: string): Promise<string>;
|
|
134
192
|
/**
|
|
135
193
|
* Sync remote-tracking refs: fetch every remote and prune tracking branches
|
|
136
194
|
* the remotes no longer carry (the CLI equivalent of IDEA's "synchronize
|
|
@@ -229,3 +287,37 @@ export declare function removeWorktree(exec: Exec, repoRoot: string, worktreePat
|
|
|
229
287
|
* binary surfaces the same way — a non-zero exit through the seam).
|
|
230
288
|
*/
|
|
231
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 {
|
|
@@ -73,6 +73,38 @@ function isDirBusyGitError(error) {
|
|
|
73
73
|
|| /\bEACCES\b/i.test(text)
|
|
74
74
|
|| /\bEBUSY\b/i.test(text);
|
|
75
75
|
}
|
|
76
|
+
/**
|
|
77
|
+
* Whether a directory IS the main worktree of its repository: exactly when
|
|
78
|
+
* its own toplevel holds the SHARED `.git` that `--git-common-dir` names.
|
|
79
|
+
* From a linked worktree that path resolves to the shared `<repo>/.git` too,
|
|
80
|
+
* but its toplevel is the linked folder — so the two differ and the answer
|
|
81
|
+
* is false.
|
|
82
|
+
*
|
|
83
|
+
* Deliberately NOT "is the first entry of `worktree list`": that list is
|
|
84
|
+
* filtered by directory existence downstream (a stale main registration
|
|
85
|
+
* would flip the answer), it costs a second git spawn, and its `main` flag
|
|
86
|
+
* describes a different question — which entry git considers main, not
|
|
87
|
+
* which directory was asked about. Same rule as {@link probeWorkspaceGit}
|
|
88
|
+
* applies for the sidebar's grouping, extracted here so both answers are the
|
|
89
|
+
* same answer.
|
|
90
|
+
* @param toplevel - the queried directory's own `--show-toplevel`.
|
|
91
|
+
* @param gitDir - the SHARED git dir (`--git-common-dir`) every worktree
|
|
92
|
+
* resolves back to.
|
|
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
|
+
}
|
|
105
|
+
function isMainWorktree(toplevel, gitDir) {
|
|
106
|
+
return isSamePath(resolve(toplevel, '.git'), gitDir);
|
|
107
|
+
}
|
|
76
108
|
/**
|
|
77
109
|
* Resolve a directory to repository facts, or undefined outside any git
|
|
78
110
|
* repository (including the `git` binary missing: ENOENT surfaces as a
|
|
@@ -102,6 +134,8 @@ export async function probeRepo(exec, path, dirExists = fsDirExists) {
|
|
|
102
134
|
return {
|
|
103
135
|
repoRoot,
|
|
104
136
|
repoName: basename(dirname(gitDir)),
|
|
137
|
+
toplevel,
|
|
138
|
+
main: isMainWorktree(toplevel, gitDir),
|
|
105
139
|
currentBranch: await currentBranch(exec, path),
|
|
106
140
|
branches: await listBranches(exec, repoRoot),
|
|
107
141
|
// A stale registration (directory removed behind git's back) must not
|
|
@@ -207,11 +241,13 @@ async function listWorktrees(exec, repoRoot) {
|
|
|
207
241
|
}
|
|
208
242
|
/**
|
|
209
243
|
* Resolve a branch display name against the authoritative branch list of the
|
|
210
|
-
* repository.
|
|
244
|
+
* repository. Exported for the /worktree route's fetch gate: the pre-create
|
|
245
|
+
* remote sync only earns its round trip when the display name is REMOTE-only
|
|
246
|
+
* (a local branch's worktree never consumes fetched refs).
|
|
211
247
|
* @returns the local name plus the tracking remote when the display name is
|
|
212
248
|
* remote-only, or undefined when neither shape exists.
|
|
213
249
|
*/
|
|
214
|
-
async function resolveBranch(exec, repoRoot, branch) {
|
|
250
|
+
export async function resolveBranch(exec, repoRoot, branch) {
|
|
215
251
|
const localsOut = await git(exec, repoRoot, ['for-each-ref', 'refs/heads', '--format=%(refname:short)']);
|
|
216
252
|
const locals = localsOut.split('\n').map(l => l.trim()).filter(l => l !== '');
|
|
217
253
|
if (locals.includes(branch))
|
|
@@ -341,19 +377,65 @@ export async function switchBranch(exec, repoRoot, branch) {
|
|
|
341
377
|
return resolved.local;
|
|
342
378
|
}
|
|
343
379
|
/**
|
|
344
|
-
* Create a NEW branch
|
|
345
|
-
*
|
|
346
|
-
*
|
|
347
|
-
*
|
|
348
|
-
*
|
|
349
|
-
*
|
|
380
|
+
* Create a NEW branch. Three shapes:
|
|
381
|
+
*
|
|
382
|
+
* - no `from`: cut from the current checkout and check it out in place
|
|
383
|
+
* (`git switch -c`) — the cut point is whatever the queried directory's
|
|
384
|
+
* HEAD points at, so a detached or unborn checkout cuts from the current
|
|
385
|
+
* commit too. Runs at the queried directory's own toplevel — a session
|
|
386
|
+
* inside a linked worktree creates and checks out within that worktree,
|
|
387
|
+
* never the main checkout (the same semantics as {@link switchBranch}).
|
|
388
|
+
* - `from` without `checkout`: create AT that start point WITHOUT touching
|
|
389
|
+
* any checkout (`git branch`) — a create aimed at another branch must
|
|
390
|
+
* not move this session's HEAD.
|
|
391
|
+
* - `from` with `checkout`: create at the start point AND check it out
|
|
392
|
+
* here in one stroke (`git switch -c <name> <from>`).
|
|
350
393
|
* @param exec - executor seam.
|
|
351
394
|
* @param cwd - directory whose HEAD the branch is cut from (worktree toplevel).
|
|
352
395
|
* @param name - new branch name (git validates; failures raise GitError).
|
|
353
|
-
* @
|
|
396
|
+
* @param from - optional start point; absent keeps the in-place semantics.
|
|
397
|
+
* @param checkout - with `from`, also check the new branch out here.
|
|
398
|
+
* @returns the branch name now created (checked out unless created at a
|
|
399
|
+
* start point with `checkout` false).
|
|
400
|
+
*/
|
|
401
|
+
export async function createBranch(exec, cwd, name, from, checkout = false) {
|
|
402
|
+
if (from === undefined || checkout) {
|
|
403
|
+
const startPoint = from === undefined ? [] : [from];
|
|
404
|
+
await git(exec, cwd, ['switch', '-c', name, ...startPoint]);
|
|
405
|
+
return name;
|
|
406
|
+
}
|
|
407
|
+
await git(exec, cwd, ['branch', name, from]);
|
|
408
|
+
return name;
|
|
409
|
+
}
|
|
410
|
+
/**
|
|
411
|
+
* Rename a LOCAL branch (`git branch -m`): branch refs are repository-wide,
|
|
412
|
+
* so the command runs at the repository root and every worktree HEAD pointing
|
|
413
|
+
* at the old name follows the ref. Git validates the new name and refuses a
|
|
414
|
+
* target that already exists; remote branches are not renameable (not ours).
|
|
415
|
+
* @param exec - executor seam.
|
|
416
|
+
* @param repoRoot - main worktree directory.
|
|
417
|
+
* @param name - branch to rename.
|
|
418
|
+
* @param newName - the new local name.
|
|
419
|
+
* @returns the new name.
|
|
420
|
+
*/
|
|
421
|
+
export async function renameBranch(exec, repoRoot, name, newName) {
|
|
422
|
+
await git(exec, repoRoot, ['branch', '-m', name, newName]);
|
|
423
|
+
return newName;
|
|
424
|
+
}
|
|
425
|
+
/**
|
|
426
|
+
* Delete a LOCAL branch (`git branch -d`, the SAFE form): git refuses a
|
|
427
|
+
* branch with unmerged commits ("not fully merged") and one checked out in
|
|
428
|
+
* any worktree — both caller-side state, mapped to 400 by the route. No
|
|
429
|
+
* `-D` force variant on purpose: a menu click must never discard commits
|
|
430
|
+
* (the terminal is the place for deliberate force-deletes). Runs at the
|
|
431
|
+
* repository root; remote branches are not ours to delete.
|
|
432
|
+
* @param exec - executor seam.
|
|
433
|
+
* @param repoRoot - main worktree directory.
|
|
434
|
+
* @param name - branch to delete.
|
|
435
|
+
* @returns the name of the branch that was deleted.
|
|
354
436
|
*/
|
|
355
|
-
export async function
|
|
356
|
-
await git(exec,
|
|
437
|
+
export async function deleteBranch(exec, repoRoot, name) {
|
|
438
|
+
await git(exec, repoRoot, ['branch', '-d', name]);
|
|
357
439
|
return name;
|
|
358
440
|
}
|
|
359
441
|
/**
|
|
@@ -510,6 +592,10 @@ export async function probeWorkspaceGit(exec, path) {
|
|
|
510
592
|
if (top === '' || commonDir === '')
|
|
511
593
|
return undefined;
|
|
512
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;
|
|
513
599
|
// Git outputs carry forward slashes on Windows — normalize every derived
|
|
514
600
|
// path so consumers can compare against join()-built ones.
|
|
515
601
|
const gitDir = normalize(resolve(path, commonDir));
|
|
@@ -517,6 +603,61 @@ export async function probeWorkspaceGit(exec, path) {
|
|
|
517
603
|
repoRoot: dirname(gitDir),
|
|
518
604
|
repoName: basename(dirname(gitDir)),
|
|
519
605
|
branch: branchName === '' || branchName === 'HEAD' ? null : branchName,
|
|
520
|
-
main:
|
|
606
|
+
main: isMainWorktree(toplevel, gitDir),
|
|
521
607
|
};
|
|
522
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
|
+
}
|