-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy pathworktree.ts
More file actions
283 lines (254 loc) · 7.88 KB
/
Copy pathworktree.ts
File metadata and controls
283 lines (254 loc) · 7.88 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
import * as fs from "node:fs/promises";
import * as path from "node:path";
import { GitSaga, type GitSagaInput } from "../git-saga";
import {
addToLocalExclude,
branchExists,
fetchRef,
getDefaultBranch,
hasRef,
} from "../queries";
import { forceRemove, safeSymlink } from "../utils";
import { processWorktreeInclude, runPostCheckoutHook } from "../worktree";
export interface CreateWorktreeInput extends GitSagaInput {
worktreePath: string;
branchName: string;
baseBranch?: string;
/** Base the worktree on `origin/<baseBranch>` after fetching; falls back to the local ref if the fetch fails. */
fetchBeforeCreate?: boolean;
}
export interface CreateWorktreeOutput {
worktreePath: string;
branchName: string;
baseBranch: string;
}
export class CreateWorktreeSaga extends GitSaga<
CreateWorktreeInput,
CreateWorktreeOutput
> {
readonly sagaName = "CreateWorktreeSaga";
protected async executeGitOperations(
input: CreateWorktreeInput,
): Promise<CreateWorktreeOutput> {
const {
baseDir,
worktreePath,
branchName,
baseBranch,
fetchBeforeCreate,
signal,
} = input;
const base = await this.readOnlyStep("get-base-branch", async () => {
if (baseBranch) return baseBranch;
return getDefaultBranch(baseDir, { abortSignal: signal });
});
// Use `this.git` directly to avoid re-entering the write lock the saga already holds.
const baseRef = fetchBeforeCreate
? await this.readOnlyStep("resolve-fresh-base-ref", async () => {
const remote = "origin";
const remoteRef = `${remote}/${base}`;
const fetched = await fetchRef(this.git, remote, base);
if (!fetched) return base;
const exists = await hasRef(this.git, remoteRef);
return exists ? remoteRef : base;
})
: base;
await this.step({
name: "create-worktree",
execute: () =>
this.git.raw([
"-c",
"core.hooksPath=/dev/null",
"worktree",
"add",
"-b",
branchName,
worktreePath,
baseRef,
]),
rollback: async () => {
try {
await this.git.raw(["worktree", "remove", worktreePath, "--force"]);
} catch {
await forceRemove(worktreePath);
await this.git.raw(["worktree", "prune"]);
}
try {
await this.git.deleteLocalBranch(branchName, true);
} catch {}
},
});
await this.step({
name: "symlink-claude-local-instructions",
execute: async () => {
const sourceClaudeLocalMd = path.join(baseDir, "CLAUDE.local.md");
const targetClaudeLocalMd = path.join(worktreePath, "CLAUDE.local.md");
const linkedFile = await safeSymlink(
sourceClaudeLocalMd,
targetClaudeLocalMd,
"file",
);
if (linkedFile) {
await addToLocalExclude(worktreePath, "CLAUDE.local.md", {
abortSignal: signal,
});
}
},
rollback: async () => {
const targetClaudeLocalMd = path.join(worktreePath, "CLAUDE.local.md");
await fs.rm(targetClaudeLocalMd, { force: true }).catch(() => {});
},
});
await this.step({
name: "process-worktree-include",
execute: () => processWorktreeInclude(baseDir, worktreePath),
rollback: async () => {},
});
await this.step({
name: "run-post-checkout-hook",
execute: () => runPostCheckoutHook(baseDir, worktreePath),
rollback: async () => {},
});
return { worktreePath, branchName, baseBranch: base };
}
}
export interface CreateWorktreeForBranchInput extends GitSagaInput {
worktreePath: string;
branchName: string;
}
export interface CreateWorktreeForBranchOutput {
worktreePath: string;
branchName: string;
}
export class CreateWorktreeForBranchSaga extends GitSaga<
CreateWorktreeForBranchInput,
CreateWorktreeForBranchOutput
> {
readonly sagaName = "CreateWorktreeForBranchSaga";
protected async executeGitOperations(
input: CreateWorktreeForBranchInput,
): Promise<CreateWorktreeForBranchOutput> {
const { baseDir, worktreePath, branchName, signal } = input;
await this.readOnlyStep("verify-branch-exists", async () => {
const exists = await branchExists(baseDir, branchName, {
abortSignal: signal,
});
if (!exists) {
throw new Error(`Branch '${branchName}' does not exist`);
}
});
await this.step({
name: "create-worktree",
execute: () =>
this.git.raw([
"-c",
"core.hooksPath=/dev/null",
"worktree",
"add",
worktreePath,
branchName,
]),
rollback: async () => {
try {
await this.git.raw(["worktree", "remove", worktreePath, "--force"]);
} catch {
await forceRemove(worktreePath);
await this.git.raw(["worktree", "prune"]);
}
},
});
await this.step({
name: "symlink-claude-local-instructions",
execute: async () => {
const sourceClaudeLocalMd = path.join(baseDir, "CLAUDE.local.md");
const targetClaudeLocalMd = path.join(worktreePath, "CLAUDE.local.md");
const linkedFile = await safeSymlink(
sourceClaudeLocalMd,
targetClaudeLocalMd,
"file",
);
if (linkedFile) {
await addToLocalExclude(worktreePath, "CLAUDE.local.md", {
abortSignal: signal,
});
}
},
rollback: async () => {
const targetClaudeLocalMd = path.join(worktreePath, "CLAUDE.local.md");
await fs.rm(targetClaudeLocalMd, { force: true }).catch(() => {});
},
});
await this.step({
name: "process-worktree-include",
execute: () => processWorktreeInclude(baseDir, worktreePath),
rollback: async () => {},
});
await this.step({
name: "run-post-checkout-hook",
execute: () => runPostCheckoutHook(baseDir, worktreePath),
rollback: async () => {},
});
return { worktreePath, branchName };
}
}
export interface DeleteWorktreeInput extends GitSagaInput {
worktreePath: string;
}
export interface DeleteWorktreeOutput {
deleted: boolean;
}
export class DeleteWorktreeSaga extends GitSaga<
DeleteWorktreeInput,
DeleteWorktreeOutput
> {
readonly sagaName = "DeleteWorktreeSaga";
protected async executeGitOperations(
input: DeleteWorktreeInput,
): Promise<DeleteWorktreeOutput> {
const { baseDir, worktreePath } = input;
const resolvedWorktreePath = path.resolve(worktreePath);
const resolvedMainRepoPath = path.resolve(baseDir);
await this.readOnlyStep("safety-checks", async () => {
if (resolvedWorktreePath === resolvedMainRepoPath) {
throw new Error("Cannot delete worktree: path matches main repo path");
}
if (
resolvedMainRepoPath.startsWith(resolvedWorktreePath) &&
resolvedMainRepoPath !== resolvedWorktreePath
) {
throw new Error(
"Cannot delete worktree: path is a parent of main repo path",
);
}
try {
const gitPath = path.join(resolvedWorktreePath, ".git");
const stat = await fs.stat(gitPath);
if (stat.isDirectory()) {
throw new Error(
"Cannot delete worktree: path appears to be a main repository",
);
}
} catch (error) {
if (
error instanceof Error &&
error.message.includes("Cannot delete worktree")
) {
throw error;
}
}
});
await this.step({
name: "delete-worktree",
execute: async () => {
try {
await this.git.raw(["worktree", "remove", worktreePath, "--force"]);
} catch {
await forceRemove(worktreePath);
await this.git.raw(["worktree", "prune"]);
}
},
rollback: async () => {},
});
return { deleted: true };
}
}