-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathworktrees.ts
More file actions
165 lines (146 loc) · 5.05 KB
/
worktrees.ts
File metadata and controls
165 lines (146 loc) · 5.05 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
import { existsSync } from "node:fs";
import { branchExistsLocally, getDefaultBranch, hasRemote, isRepoDirty, remoteBranchExists } from "./git";
import { error, inlineResult, inlineStart, plural, warn } from "./output";
import { type FetchResult, parallelFetch } from "./parallel-fetch";
import type { RepoRemotes } from "./remotes";
export interface AddWorktreesResult {
created: string[];
skipped: string[];
failed: string[];
}
export async function addWorktrees(
name: string,
branch: string,
repos: string[],
reposDir: string,
baseDir: string,
baseBranch?: string,
remotesMap?: Map<string, RepoRemotes>,
): Promise<AddWorktreesResult> {
const wsDir = `${baseDir}/${name}`;
const result: AddWorktreesResult = { created: [], skipped: [], failed: [] };
// Phase 1: parallel fetch
const fetchResults = new Map<string, FetchResult>();
const reposDirsToFetch: string[] = [];
for (const repo of repos) {
const repoPath = `${reposDir}/${repo}`;
if (!existsSync(`${repoPath}/.git`)) {
fetchResults.set(repo, { repo, exitCode: 1, output: "" });
continue;
}
if (!(await hasRemote(repoPath))) {
fetchResults.set(repo, { repo, exitCode: 0, output: "" });
continue;
}
reposDirsToFetch.push(repoPath);
}
if (reposDirsToFetch.length > 0) {
process.stderr.write(`Fetching ${plural(reposDirsToFetch.length, "repo")}...\n`);
const fetched = await parallelFetch(reposDirsToFetch, undefined, remotesMap);
for (const [repo, fr] of fetched) {
fetchResults.set(repo, fr);
}
}
// Phase 2: sequential worktree creation
process.stderr.write("Creating worktrees...\n");
for (const repo of repos) {
const repoPath = `${reposDir}/${repo}`;
const fr = fetchResults.get(repo);
if (!existsSync(`${repoPath}/.git`)) {
error(` [${repo}] not a git repo`);
result.failed.push(repo);
continue;
}
if (fr && fr.exitCode !== 0) {
if (fr.exitCode === 124) {
error(` [${repo}] fetch timed out`);
} else {
error(` [${repo}] fetch failed`);
}
if (fr.output) {
for (const line of fr.output.split("\n").filter(Boolean)) {
error(` ${line}`);
}
}
result.failed.push(repo);
continue;
}
if (existsSync(`${wsDir}/${repo}`)) {
warn(` [${repo}] worktree already exists — skipping`);
result.skipped.push(repo);
continue;
}
if (await isRepoDirty(repoPath)) {
warn(` [${repo}] canonical repo has uncommitted changes`);
}
const repoHasRemote = await hasRemote(repoPath);
// Resolve remote names for this repo
const repoRemotes = remotesMap?.get(repo);
const upstreamRemote = repoRemotes?.upstream ?? "origin";
let effectiveBase: string | null;
if (baseBranch) {
const baseExists = repoHasRemote
? await remoteBranchExists(repoPath, baseBranch, upstreamRemote)
: await branchExistsLocally(repoPath, baseBranch);
if (baseExists) {
effectiveBase = baseBranch;
} else {
effectiveBase = await getDefaultBranch(repoPath, upstreamRemote);
if (effectiveBase) {
warn(` [${repo}] base branch '${baseBranch}' not found — using '${effectiveBase}'`);
} else {
error(` [${repo}] base branch '${baseBranch}' not found and could not determine default branch`);
result.failed.push(repo);
continue;
}
}
} else {
effectiveBase = await getDefaultBranch(repoPath, upstreamRemote);
if (!effectiveBase) {
error(` [${repo}] could not determine default branch`);
result.failed.push(repo);
continue;
}
}
const branchExists = await branchExistsLocally(repoPath, branch);
// Prune stale worktrees
await Bun.$`git -C ${repoPath} worktree prune`.cwd(repoPath).quiet().nothrow();
if (branchExists) {
inlineStart(repo, `attaching branch ${branch}`);
const wt = await Bun.$`git -C ${repoPath} worktree add ${wsDir}/${repo} ${branch}`
.cwd(repoPath)
.quiet()
.nothrow();
if (wt.exitCode !== 0) {
inlineResult(repo, "failed");
const errText = wt.stderr.toString().trim();
if (errText) error(` ${errText}`);
result.failed.push(repo);
continue;
}
inlineResult(repo, `branch ${branch} attached`);
} else {
const startPoint = repoHasRemote ? `${upstreamRemote}/${effectiveBase}` : effectiveBase;
inlineStart(repo, `creating branch ${branch} from ${startPoint}`);
// Prevent git from auto-setting tracking config (branch.autoSetupMerge) when
// branching from a remote ref. We rely on tracking config being absent for fresh
// branches and present only after `arb push -u`, so we can detect "gone" branches
// (pushed, merged, remote branch deleted) vs never-pushed branches.
const noTrack = repoHasRemote ? ["--no-track"] : [];
const wt = await Bun.$`git -C ${repoPath} worktree add ${noTrack} -b ${branch} ${wsDir}/${repo} ${startPoint}`
.cwd(repoPath)
.quiet()
.nothrow();
if (wt.exitCode !== 0) {
inlineResult(repo, "failed");
const errText = wt.stderr.toString().trim();
if (errText) error(` ${errText}`);
result.failed.push(repo);
continue;
}
inlineResult(repo, `branch ${branch} created from ${startPoint}`);
}
result.created.push(repo);
}
return result;
}