-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathgit.ts
More file actions
270 lines (254 loc) · 8.26 KB
/
Copy pathgit.ts
File metadata and controls
270 lines (254 loc) · 8.26 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
// git/* worker tasks. Handlers build their own SimpleGit — the worker spawns
// the git subprocesses itself, so stdout draining AND parsing leave the
// host-service event loop. Credential env is resolved in-process (it needs
// the credential provider) and crosses as plain data.
import {
type ResolvedGitInfo,
readGitIdentity,
} from "../../runtime/git/identity.ts";
import { createUserSimpleGit } from "../../runtime/git/simple-git.ts";
import {
readWorkspaceRefs,
type WorkspaceRefsSnapshot,
} from "../../runtime/pull-requests/utils/workspace-refs.ts";
import type { ChangedFile } from "../../trpc/router/git/types.ts";
import type { BaseRefFetchTarget } from "../../trpc/router/git/utils/base-ref-freshness.ts";
import {
type DiffCategory,
getChangedFilesForDiff,
loadFileDiffContent,
mapWithConcurrency,
resolveDiffCategoryRefs,
} from "../../trpc/router/git/utils/git-helpers.ts";
import type { GitStatusSnapshotComputation } from "../../trpc/router/git/utils/git-status.ts";
import { getGitStatusSnapshot } from "../../trpc/router/git/utils/git-status.ts";
import {
normalizeWorktreePath,
parseWorktreeList,
type WorktreeRecord,
} from "../../trpc/router/workspace-creation/shared/worktree-list.ts";
import { defineWorkerTask } from "../define-worker-task.ts";
// How many `git show` pairs run at once for a bulk diff request. Each pair
// is its own SimpleGit instance so slots genuinely run concurrently
// (simple-git serializes commands within one instance).
const DIFF_BULK_CONCURRENCY = 8;
export interface GitTaskEnv {
[key: string]: string;
}
export const gitStatusSnapshotTask = defineWorkerTask<
{ worktreePath: string; baseBranch?: string; gitEnv: GitTaskEnv },
GitStatusSnapshotComputation
>({
type: "git/getStatusSnapshot",
handler: async ({ worktreePath, baseBranch, gitEnv }) => {
const git = createUserSimpleGit(worktreePath).env(gitEnv);
return getGitStatusSnapshot({ git, worktreePath, baseBranch });
},
});
export const gitFetchBaseRefTask = defineWorkerTask<
{
worktreePath: string;
target: BaseRefFetchTarget;
gitEnv: GitTaskEnv;
},
void
>({
type: "git/fetchBaseRef",
handler: async ({ worktreePath, target, gitEnv }) => {
const git = createUserSimpleGit(worktreePath).env(gitEnv);
await git.fetch([target.remote, target.branch, "--quiet", "--no-tags"]);
},
});
export const gitCommitFilesTask = defineWorkerTask<
{
worktreePath: string;
commitHash: string;
fromHash?: string;
gitEnv: GitTaskEnv;
},
ChangedFile[]
>({
type: "git/getCommitFiles",
handler: async ({ worktreePath, commitHash, fromHash, gitEnv }) => {
const git = createUserSimpleGit(worktreePath).env(gitEnv);
const from = fromHash ? fromHash : `${commitHash}^`;
return getChangedFilesForDiff(git, [from, commitHash]);
},
});
// Bulk sibling of the single-file diff path: resolves the category's shared
// refs once, then loads every requested file's diff with bounded
// concurrency — all inside this worker, so a several-hundred-file changeset
// never spawns its `git show` processes on the host-service event loop.
export const gitDiffBulkTask = defineWorkerTask<
{
worktreePath: string;
paths: string[];
category: DiffCategory;
baseBranch?: string;
commitHash?: string;
fromHash?: string;
gitEnv: GitTaskEnv;
},
{
diffs: Array<{
path: string;
oldFile: { name: string; contents: string };
newFile: { name: string; contents: string };
}>;
}
>({
type: "git/getDiffBulk",
handler: async ({
worktreePath,
paths,
category,
baseBranch,
commitHash,
fromHash,
gitEnv,
}) => {
const refs = await resolveDiffCategoryRefs(
createUserSimpleGit(worktreePath).env(gitEnv),
category,
{ baseBranch, commitHash, fromHash },
);
const diffs = await mapWithConcurrency(
paths,
DIFF_BULK_CONCURRENCY,
async (path) => {
const git = createUserSimpleGit(worktreePath).env(gitEnv);
const { oldFile, newFile } = await loadFileDiffContent(
git,
worktreePath,
category,
path,
refs,
);
return { path, oldFile, newFile };
},
);
return { diffs };
},
});
export const gitWorkspaceRefsTask = defineWorkerTask<
{ worktreePath: string; gitEnv: GitTaskEnv },
WorkspaceRefsSnapshot
>({
type: "git/readWorkspaceRefs",
handler: async ({ worktreePath, gitEnv }) => {
const git = createUserSimpleGit(worktreePath).env(gitEnv);
return readWorkspaceRefs(git);
},
});
export const gitIdentityTask = defineWorkerTask<
{ shellEnv: GitTaskEnv },
ResolvedGitInfo
>({
type: "git/readGitIdentity",
handler: ({ shellEnv }) => readGitIdentity(shellEnv),
});
// Delete-preview + destroy-preflight state for workspace cleanup.
// Unpushed-commit detection uses `rev-list --not --remotes` so brand-new
// branches with no upstream still report unpushed commits correctly.
export const gitWorktreeStateTask = defineWorkerTask<
{
worktreePath: string;
gitEnv: GitTaskEnv;
// Session repos have no remote, so `--not --remotes` counts every
// commit and the initial scaffold commit would read as "unpushed"
// forever. This treats exactly one commit as the empty baseline.
ignoreInitialCommit?: boolean;
},
{ hasChanges: boolean; hasUnpushedCommits: boolean }
>({
type: "git/worktreeState",
handler: async ({ worktreePath, gitEnv, ignoreInitialCommit }) => {
const git = createUserSimpleGit(worktreePath).env(gitEnv);
const status = await git.status();
let hasUnpushedCommits = false;
try {
const result = await git.raw([
"rev-list",
"--count",
"HEAD",
"--not",
"--remotes",
]);
const count = Number.parseInt(result.trim(), 10);
hasUnpushedCommits =
Number.isFinite(count) && count > (ignoreInitialCommit ? 1 : 0);
} catch {
// Leave false — `rev-list` failure isn't a signal we can act on.
}
return { hasChanges: !status.isClean(), hasUnpushedCommits };
},
});
export const gitWorktreeRemoveTask = defineWorkerTask<
{ repoPath: string; worktreePath: string; gitEnv: GitTaskEnv },
{ stillRegistered: boolean }
>({
type: "git/removeWorktree",
handler: async ({ repoPath, worktreePath, gitEnv }) => {
const git = createUserSimpleGit(repoPath).env(gitEnv);
// Remove against git's canonical path so a symlinked stored path
// (macOS `/var` → `/private/var`) still matches its registration.
const target = normalizeWorktreePath(worktreePath);
// Best-effort: the registry read below is authoritative, not the
// command's locale- and version-dependent exit text. `--force --force`
// also unregisters a worktree whose directory is already gone, so no
// separate prune (which would clobber other stale worktrees' metadata)
// is needed.
await git
.raw(["worktree", "remove", "--force", "--force", target])
.catch(() => {});
// A `worktree list` failure throws out of the task: the post-remove
// state is unknown and the caller must not treat it as removed.
const raw = await git.raw(["worktree", "list", "--porcelain"]);
return {
stillRegistered: parseWorktreeList(raw).some(
(w) => normalizeWorktreePath(w.path) === target,
),
};
},
});
export const gitWorktreeListTask = defineWorkerTask<
{ repoPath: string; gitEnv: GitTaskEnv },
WorktreeRecord[]
>({
type: "git/listWorktrees",
handler: async ({ repoPath, gitEnv }) => {
const git = createUserSimpleGit(repoPath).env(gitEnv);
return parseWorktreeList(
await git.raw(["worktree", "list", "--porcelain"]),
);
},
});
export const gitDeleteBranchTask = defineWorkerTask<
{ repoPath: string; branch: string; gitEnv: GitTaskEnv },
{ deleted: boolean }
>({
type: "git/deleteLocalBranch",
handler: async ({ repoPath, branch, gitEnv }) => {
const git = createUserSimpleGit(repoPath).env(gitEnv);
// `branch --list` exits 0 whether or not the branch exists (empty
// output when absent), so an absent ref — renamed, pruned, or never
// materialized — already satisfies the goal, while a thrown failure
// propagates instead of being misread as "already deleted".
const listed = await git.raw(["branch", "--list", branch]);
if (listed.trim().length === 0) return { deleted: false };
await git.raw(["branch", "-D", branch]);
return { deleted: true };
},
});
export const gitTasks = [
gitStatusSnapshotTask,
gitFetchBaseRefTask,
gitCommitFilesTask,
gitDiffBulkTask,
gitWorkspaceRefsTask,
gitIdentityTask,
gitWorktreeStateTask,
gitWorktreeRemoveTask,
gitWorktreeListTask,
gitDeleteBranchTask,
];