Repository navigation
Expand file tree
/
Copy pathworktrees.ts
More file actions
303 lines (277 loc) · 8.93 KB
/
Copy pathworktrees.ts
File metadata and controls
303 lines (277 loc) · 8.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
import type { GitMutationResult } from '../../../common/git.js';
import path from "path";
import { promises as fs } from "fs";
import type {
CreateWorktreeOptions,
ProjectOptions,
RemoveWorktreeOptions,
RepoInfo,
TargetCandidate,
WorktreeInfo,
} from "./types.js";
import {
assertGitRepository,
readOnlyGitOptions,
runGit,
runGitTraced,
} from "./run.js";
import {
assertExistingCommitRef,
assertSafeBranchName,
} from "./ref-validation.js";
import { mapWithConcurrency } from "../../common/concurrency.js";
import { createLogger } from "../../common/log.js";
import { probeWorktreeLayout } from "./worktree-layout.js";
import { readAdminWorktreeRecords } from "./worktree-admin.js";
import { readPorcelainWorktreeRecords } from "./worktree-porcelain.js";
import {
compareWorktreePaths,
type WorktreeRecord,
} from "./worktree-record.js";
const WORKTREE_STAT_CONCURRENCY = 32;
const logger = createLogger("git:worktrees");
interface WorktreeOperationOptions {
assertProjectPathAllowed?: (projectPath: string) => Promise<string>;
// Forces the Git-backed source for differential parity tests.
source?: "auto" | "git";
}
export function serializeWorktreeMtime(mtime: Date): string | null {
return Number.isFinite(mtime.getTime()) ? mtime.toISOString() : null;
}
async function enrichWorktreeMetadata(worktree: WorktreeInfo): Promise<void> {
try {
const stats = await fs.stat(worktree.path);
if (!stats.isDirectory()) {
worktree.isPathMissing = true;
worktree.lastModifiedAt = null;
return;
}
worktree.lastModifiedAt = serializeWorktreeMtime(stats.mtime);
} catch {
worktree.isPathMissing = true;
worktree.lastModifiedAt = null;
}
}
function normalizeWorktreeRecords(
records: readonly WorktreeRecord[],
projectPath: string,
): WorktreeInfo[] {
const resolvedProject = path.resolve(projectPath);
// Garcon owns byte ordering so both sources agree regardless of core.ignorecase.
const orderedRecords = records.length < 2
? records
: [records[0], ...records.slice(1).sort(compareWorktreePaths)];
return orderedRecords.map((record, index) => ({
path: record.path,
branch: record.branch,
name: record.name || path.basename(record.path),
isCurrent: path.resolve(record.path) === resolvedProject,
isMain: index === 0 || record.isMain,
isPathMissing: false,
lastModifiedAt: null,
}));
}
async function collectWorktrees(
{ projectPath, trace }: ProjectOptions,
source: "auto" | "git",
assertProjectPathAllowed?: (projectPath: string) => Promise<string>,
): Promise<{
currentWorktreePath: string;
worktrees: WorktreeInfo[];
}> {
const layout = source === "auto"
? await probeWorktreeLayout(projectPath, trace)
: null;
let currentWorktreePath: string;
let records: WorktreeRecord[] | null = null;
if (layout) {
currentWorktreePath = layout.worktreeRoot;
if (layout.refFormat === "files") {
try {
records = await readAdminWorktreeRecords(layout);
} catch {
logger.debug("Direct worktree metadata read failed; using Git.");
}
}
} else {
await assertGitRepository(projectPath);
const { stdout } = await runGitTraced(
projectPath,
["rev-parse", "--show-toplevel"],
trace,
readOnlyGitOptions(),
);
currentWorktreePath = stdout.trim();
}
records ??= await readPorcelainWorktreeRecords(projectPath, trace);
const worktrees: WorktreeInfo[] = [];
for (const worktree of normalizeWorktreeRecords(records, projectPath)) {
if (assertProjectPathAllowed) {
try { await assertProjectPathAllowed(worktree.path); }
catch { continue; }
}
worktrees.push(worktree);
}
await mapWithConcurrency(
worktrees,
WORKTREE_STAT_CONCURRENCY,
enrichWorktreeMetadata,
);
return { currentWorktreePath, worktrees };
}
export function createWorktreeOperations(
{ source = "auto", assertProjectPathAllowed }: WorktreeOperationOptions = {},
) {
// Lightweight git capability probe. Reports whether a path is inside a
// git repository and, if so, the repository root and current worktree path.
async function getRepoInfo({
projectPath,
}: ProjectOptions): Promise<RepoInfo> {
try {
await fs.access(projectPath);
} catch {
return { isGitRepository: false };
}
try {
const { stdout: topLevelOut } = await runGit(
projectPath,
["rev-parse", "--show-toplevel"],
readOnlyGitOptions(),
);
const repoRoot = topLevelOut.trim();
// --show-toplevel gives the worktree root, which equals projectPath
// when the user points at a worktree directory directly.
return {
isGitRepository: true,
repoRoot,
currentWorktreePath: repoRoot,
};
} catch {
return { isGitRepository: false };
}
}
async function getWorktrees({
projectPath,
trace,
}: ProjectOptions): Promise<{ worktrees: WorktreeInfo[] }> {
const { worktrees } = await collectWorktrees({ projectPath, trace }, source, assertProjectPathAllowed);
return { worktrees };
}
async function getTargetCandidates({
projectPath,
trace,
}: ProjectOptions): Promise<{ targets: TargetCandidate[] }> {
const { currentWorktreePath, worktrees } = await collectWorktrees(
{ projectPath, trace },
source,
assertProjectPathAllowed,
);
const targets: TargetCandidate[] = [];
const seen = new Set<string>();
const repoRoot = currentWorktreePath || projectPath;
function addTarget(target: TargetCandidate): void {
if (!target.worktreePath || seen.has(target.worktreePath)) return;
seen.add(target.worktreePath);
targets.push(target);
}
// The chat-project target shares the current worktree's path, so the
// dedup below drops the matching worktree entry. Carry its branch onto
// the chat-project candidate so the toolbar shows the branch on first
// paint without a separate status request.
const chatProjectWorktreePath = repoRoot;
const resolvedChatProjectWorktreePath = path.resolve(
chatProjectWorktreePath,
);
const currentWorktree =
worktrees.find((worktree) => worktree.isCurrent) ??
worktrees.find((worktree) =>
path.resolve(worktree.path) === resolvedChatProjectWorktreePath
);
addTarget({
projectPath,
repoRoot,
worktreePath: chatProjectWorktreePath,
label: path.basename(projectPath) || projectPath,
branch: currentWorktree?.branch ?? "",
source: "chat-project",
isCurrent: true,
isMissing: false,
});
for (const worktree of worktrees) {
const name = worktree.name || path.basename(worktree.path);
const branchLabel = worktree.branch ? ` (${worktree.branch})` : "";
addTarget({
projectPath: worktree.path,
repoRoot,
worktreePath: worktree.path,
label: `${name}${branchLabel}`,
branch: worktree.branch,
source: "worktree",
isCurrent: worktree.isCurrent,
isMissing: worktree.isPathMissing,
});
}
return { targets };
}
async function createWorktree({
projectPath,
baseRef,
worktreePath,
branch,
detach,
}: CreateWorktreeOptions): Promise<GitMutationResult> {
await assertGitRepository(projectPath);
if (baseRef) await assertExistingCommitRef(projectPath, baseRef, "base");
if (branch) await assertSafeBranchName(projectPath, branch, "branch name");
const args: string[] = ["worktree", "add"];
if (detach) {
args.push("--detach", worktreePath);
if (baseRef) args.push(baseRef);
} else if (branch) {
// Check if the branch already exists to avoid `-b` failure.
const branchExists = await runGit(
projectPath,
["rev-parse", "--verify", `refs/heads/${branch}`],
readOnlyGitOptions(),
)
.then(() => true)
.catch(() => false);
if (branchExists) {
// Checkout existing branch into the new worktree path.
args.push(worktreePath, branch);
} else {
args.push("--no-track", "-b", branch, worktreePath);
if (baseRef) args.push(baseRef);
}
} else {
args.push(worktreePath);
if (baseRef) args.push(baseRef);
}
const { stdout } = await runGit(projectPath, args);
const resolvedPath = path.resolve(projectPath, worktreePath);
return {
success: true,
output: stdout || "Worktree created",
worktreePath: resolvedPath,
};
}
async function removeWorktree({
projectPath,
worktreePath,
force,
}: RemoveWorktreeOptions): Promise<GitMutationResult> {
await assertGitRepository(projectPath);
const args: string[] = ["worktree", "remove"];
if (force) args.push("--force");
args.push(worktreePath);
const { stdout } = await runGit(projectPath, args);
return { success: true, output: stdout || "Worktree removed" };
}
return {
getRepoInfo,
getWorktrees,
getTargetCandidates,
createWorktree,
removeWorktree,
};
}