Skip to content
Source
Sign inSign up
Open History to see the last commit

GitWorkflowService.ts

539 lines19.8 KB

1import * as Context from "effect/Context";
2import * as Effect from "effect/Effect";
3import * as Layer from "effect/Layer";
4import * as FileSystem from "effect/FileSystem";
5​
6import {
7 GitManagerError,
8 GitCommandError,
9 type VcsSwitchRefInput,
10 type VcsSwitchRefResult,
11 type VcsCreateRefInput,
12 type VcsCreateRefResult,
13 type VcsCreateWorktreeInput,
14 type VcsCreateWorktreeResult,
15 type VcsListRefsInput,
16 type VcsListRefsResult,
17 type GitManagerServiceError,
18 type GitPreparePullRequestThreadInput,
19 type GitPreparePullRequestThreadResult,
20 type GitPullRequestRefInput,
21 type VcsPullResult,
22 type VcsRemoveWorktreeInput,
23 type GitResolvePullRequestResult,
24 type GitRunStackedActionInput,
25 type GitRunStackedActionResult,
26 type VcsStatusInput,
27 type VcsStatusLocalResult,
28 type VcsStatusRemoteResult,
29 type VcsStatusResult,
30} from "@t3tools/contracts";
31​
32import * as GitManager from "./GitManager.ts";
33import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
34import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
35import { withWorkspaceLease } from "../workspace/workspaceLease.ts";
36​
37export class GitWorkflowService extends Context.Service<
38 GitWorkflowService,
39 {
40 readonly repositoryRoot: (cwd: string) => Effect.Effect<string | null, GitManagerServiceError>;
41 readonly hasCommit: (input: {
42 readonly cwd: string;
43 readonly refName: string;
44 }) => Effect.Effect<boolean, GitCommandError>;
45 readonly hasRefNamed: (input: {
46 readonly cwd: string;
47 readonly refName: string;
48 }) => Effect.Effect<boolean, GitCommandError>;
49 readonly status: (
50 input: VcsStatusInput,
51 ) => Effect.Effect<VcsStatusResult, GitManagerServiceError>;
52 readonly localStatus: (
53 input: VcsStatusInput,
54 ) => Effect.Effect<VcsStatusLocalResult, GitManagerServiceError>;
55 readonly currentBranch: (cwd: string) => Effect.Effect<string | null, GitManagerServiceError>;
56 readonly upstreamDivergence: (cwd: string) => Effect.Effect<
57 {
58 readonly refName: string;
59 readonly aheadCount: number;
60 readonly behindCount: number;
61 } | null,
62 GitManagerServiceError
63 >;
64 readonly remoteStatus: (
65 input: VcsStatusInput,
66 options?: GitManager.GitRemoteStatusOptions,
67 ) => Effect.Effect<VcsStatusRemoteResult | null, GitManagerServiceError>;
68 readonly invalidateLocalStatus: (cwd: string) => Effect.Effect<void, never>;
69 readonly invalidateRemoteStatus: (cwd: string) => Effect.Effect<void, never>;
70 readonly invalidateStatus: (cwd: string) => Effect.Effect<void, never>;
71 /** The checkout's own HEAD file, inside a linked worktree's admin directory when there is one. */
72 readonly headPath: (cwd: string) => Effect.Effect<string | null, never>;
73 readonly pullCurrentBranch: (cwd: string) => Effect.Effect<VcsPullResult, GitCommandError>;
74 readonly runStackedAction: (
75 input: GitRunStackedActionInput,
76 options?: GitManager.GitRunStackedActionOptions,
77 ) => Effect.Effect<GitRunStackedActionResult, GitManagerServiceError>;
78 readonly resolvePullRequest: (
79 input: GitPullRequestRefInput,
80 ) => Effect.Effect<GitResolvePullRequestResult, GitManagerServiceError>;
81 readonly preparePullRequestThread: (
82 input: GitPreparePullRequestThreadInput,
83 ) => Effect.Effect<GitPreparePullRequestThreadResult, GitManagerServiceError>;
84 readonly listRefs: (
85 input: VcsListRefsInput,
86 ) => Effect.Effect<VcsListRefsResult, GitCommandError>;
87 readonly createWorktree: (
88 input: VcsCreateWorktreeInput,
89 options?: GitVcsDriver.CreateWorktreeOptions,
90 ) => Effect.Effect<VcsCreateWorktreeResult, GitCommandError>;
91 readonly listLocalBranchNames: (cwd: string) => Effect.Effect<string[], GitCommandError>;
92 readonly fetchRemote: (input: {
93 readonly cwd: string;
94 readonly remoteName: string;
95 readonly refName?: string;
96 }) => Effect.Effect<void, GitCommandError>;
97 readonly remoteExists: (input: {
98 readonly cwd: string;
99 readonly remoteName: string;
100 }) => Effect.Effect<boolean, GitCommandError>;
101 readonly remoteBranchExists: (input: {
102 readonly cwd: string;
103 readonly remoteName: string;
104 readonly refName: string;
105 }) => Effect.Effect<boolean, GitCommandError>;
106 readonly resolvePrimaryRemoteName: (cwd: string) => Effect.Effect<string, GitCommandError>;
107 readonly resolveRemoteTrackingCommit: (input: {
108 readonly cwd: string;
109 readonly refName: string;
110 readonly fallbackRemoteName: string;
111 }) => Effect.Effect<
112 { readonly commitSha: string; readonly remoteRefName: string },
113 GitCommandError
114 >;
115 readonly resolveWorktreeBaseRemote: GitVcsDriver.GitVcsDriver["Service"]["resolveWorktreeBaseRemote"];
116 readonly fetchWorktreeBaseCommit: (input: {
117 readonly cwd: string;
118 readonly refName: string;
119 readonly remote?: GitVcsDriver.GitWorktreeBaseRemote;
120 }) => Effect.Effect<
121 { readonly commitSha: string; readonly remoteRefName: string } | null,
122 GitCommandError
123 >;
124 readonly removeWorktree: (
125 input: VcsRemoveWorktreeInput,
126 ) => Effect.Effect<void, GitCommandError>;
127 readonly pruneWorktrees: (input: {
128 readonly cwd: string;
129 }) => Effect.Effect<void, GitCommandError>;
130 readonly deleteLocalBranch: (
131 input: GitVcsDriver.GitDeleteLocalBranchInput,
132 ) => Effect.Effect<void, GitCommandError>;
133 readonly createRef: (
134 input: VcsCreateRefInput,
135 ) => Effect.Effect<VcsCreateRefResult, GitCommandError>;
136 readonly switchRef: (
137 input: VcsSwitchRefInput,
138 ) => Effect.Effect<VcsSwitchRefResult, GitCommandError>;
139 readonly renameBranch: (input: {
140 readonly exactName?: boolean;
141 readonly cwd: string;
142 readonly oldBranch: string;
143 readonly newBranch: string;
144 }) => Effect.Effect<{ readonly branch: string }, GitManagerServiceError>;
145 }
146>()("t3/git/GitWorkflowService") {}
147​
148function nonRepositoryLocalStatus(): VcsStatusLocalResult {
149 return {
150 isRepo: false,
151 hasPrimaryRemote: false,
152 isDefaultRef: false,
153 refName: null,
154 hasWorkingTreeChanges: false,
155 workingTree: {
156 files: [],
157 insertions: 0,
158 deletions: 0,
159 },
160 };
162​
163function nonRepositoryStatus(): VcsStatusResult {
164 return {
165 ...nonRepositoryLocalStatus(),
166 hasUpstream: false,
167 aheadCount: 0,
168 behindCount: 0,
169 aheadOfDefaultCount: 0,
170 pr: null,
171 };
173​
174function nonRepositoryListRefs(): VcsListRefsResult {
175 return {
176 refs: [],
177 isRepo: false,
178 hasPrimaryRemote: false,
179 nextCursor: null,
180 totalCount: 0,
181 };
183​
184/** @public */
185export const make = Effect.gen(function* () {
186 const registry = yield* VcsDriverRegistry.VcsDriverRegistry;
187 const git = yield* GitVcsDriver.GitVcsDriver;
188 const gitManager = yield* GitManager.GitManager;
189 const fileSystem = yield* FileSystem.FileSystem;
190​
191 // Nested projects and path aliases must share the checkout's branch-mutation lease.
192 const withCheckoutLease = <A, E, R>(rootPath: string, effect: Effect.Effect<A, E, R>) =>
193 fileSystem.realPath(rootPath).pipe(
194 Effect.orElseSucceed(() => rootPath),
195 Effect.flatMap((cwd) => withWorkspaceLease(cwd, effect)),
196 );
197​
198 const ensureGit = Effect.fn("GitWorkflowService.ensureGit")(function* (
199 operation: string,
200 cwd: string,
201 ) {
202 const handle = yield* registry.resolve({ cwd }).pipe(
203 Effect.mapError(
204 (cause) =>
205 new GitManagerError({
206 operation,
207 cwd,
208 detail: "Failed to resolve the VCS driver for this Git workflow.",
209 cause,
210 }),
211 ),
212 );
213 return handle;
214 });
215​
216 const ensureGitCommand = Effect.fn("GitWorkflowService.ensureGitCommand")(function* (
217 operation: string,
218 cwd: string,
219 ) {
220 const handle = yield* registry.resolve({ cwd }).pipe(
221 Effect.mapError(
222 (cause) =>
223 new GitCommandError({
224 operation,
225 command: "vcs-route",
226 cwd,
227 detail: "Failed to resolve the VCS driver for this Git command.",
228 cause,
229 }),
230 ),
231 );
232 return handle;
233 });
234​
235 const detectGitRepositoryForStatus = Effect.fn("GitWorkflowService.detectGitRepositoryForStatus")(
236 function* (operation: string, cwd: string) {
237 const handle = yield* registry.detect({ cwd }).pipe(
238 Effect.mapError(
239 (cause) =>
240 new GitManagerError({
241 operation,
242 cwd,
243 detail: "Failed to detect a VCS repository for this Git workflow.",
244 cause,
245 }),
246 ),
247 );
248 if (!handle) {
249 return false;
250 }
251 return true;
252 },
253 );
254​
255 const detectGitRepositoryForCommand = Effect.fn(
256 "GitWorkflowService.detectGitRepositoryForCommand",
257 )(function* (operation: string, cwd: string) {
258 const handle = yield* registry.detect({ cwd }).pipe(
259 Effect.mapError(
260 (cause) =>
261 new GitCommandError({
262 operation,
263 command: "vcs-route",
264 cwd,
265 detail: "Failed to detect a VCS repository for this Git command.",
266 cause,
267 }),
268 ),
269 );
270 if (!handle) {
271 return false;
272 }
273 return true;
274 });
275​
276 const routeGitManager =
277 <Input extends { readonly cwd: string }, Output>(
278 operation: string,
279 run: (input: Input) => Effect.Effect<Output, GitManagerServiceError>,
280 ) =>
281 (input: Input) =>
282 ensureGit(operation, input.cwd).pipe(Effect.andThen(run(input)));
283​
284 return GitWorkflowService.of({
285 repositoryRoot: Effect.fn("GitWorkflowService.repositoryRoot")(function (cwd) {
286 return registry.detect({ cwd }).pipe(
287 Effect.map((handle) => (handle?.kind === "git" ? handle.repository.rootPath : null)),
288 Effect.mapError(
289 (cause) =>
290 new GitManagerError({
291 operation: "GitWorkflowService.repositoryRoot",
292 cwd,
293 detail: "Failed to detect a VCS repository for this Git workflow.",
294 cause,
295 }),
296 ),
297 );
298 }),
299 hasCommit: Effect.fn("GitWorkflowService.hasCommit")(function (input) {
300 return ensureGitCommand("GitWorkflowService.hasCommit", input.cwd).pipe(
301 Effect.andThen(
302 git.execute({
303 operation: "GitWorkflowService.hasCommit",
304 cwd: input.cwd,
305 args: ["rev-parse", "--verify", `${input.refName}^{commit}`],
306 allowNonZeroExit: true,
307 }),
308 ),
309 Effect.map((result) => result.exitCode === 0),
310 );
311 }),
312 hasRefNamed: Effect.fn("GitWorkflowService.hasRefNamed")(function (input) {
313 // Pattern characters would widen the ref match.
314 return /[*?[\\]/.test(input.refName)
315 ? Effect.succeed(false)
316 : ensureGitCommand("GitWorkflowService.hasRefNamed", input.cwd).pipe(
317 Effect.andThen(
318 git.execute({
319 operation: "GitWorkflowService.hasRefNamed",
320 cwd: input.cwd,
321 args: [
322 "for-each-ref",
323 "--count=1",
324 "--format=%(refname)",
325 `refs/**/${input.refName}`,
326 ],
327 }),
328 ),
329 Effect.map((result) => result.stdout.trim().length > 0),
330 );
331 }),
332 status: Effect.fn("GitWorkflowService.status")(function (input) {
333 return detectGitRepositoryForStatus("GitWorkflowService.status", input.cwd).pipe(
334 Effect.flatMap((isGitRepository) =>
335 isGitRepository ? gitManager.status(input) : Effect.succeed(nonRepositoryStatus()),
336 ),
337 );
338 }),
339 localStatus: Effect.fn("GitWorkflowService.localStatus")(function (input) {
340 return detectGitRepositoryForStatus("GitWorkflowService.localStatus", input.cwd).pipe(
341 Effect.flatMap((isGitRepository) =>
342 isGitRepository
343 ? gitManager.localStatus(input)
344 : Effect.succeed(nonRepositoryLocalStatus()),
345 ),
346 );
347 }),
348 currentBranch: Effect.fn("GitWorkflowService.currentBranch")(function* (cwd) {
349 if (!(yield* detectGitRepositoryForStatus("GitWorkflowService.currentBranch", cwd))) {
350 return null;
351 }
352 const result = yield* git.execute({
353 operation: "GitWorkflowService.currentBranch",
354 cwd,
355 args: ["symbolic-ref", "--quiet", "HEAD"],
356 allowNonZeroExit: true,
357 timeoutMs: 5_000,
358 });
359 if (result.exitCode === 0) {
360 return result.stdout.trim().replace(/^refs\/heads\//, "") || null;
361 }
362 if (result.exitCode === 1) return null;
363 return yield* new GitCommandError({
364 operation: "GitWorkflowService.currentBranch",
365 command: "git symbolic-ref",
366 cwd,
367 argumentCount: 3,
368 ...(result.exitCode === null ? {} : { exitCode: result.exitCode }),
369 stdoutLength: result.stdout.length,
370 stderrLength: result.stderr.length,
371 detail: "Failed to read the checked-out branch.",
372 });
373 }),
374 upstreamDivergence: Effect.fn("GitWorkflowService.upstreamDivergence")(function* (cwd) {
375 const details = yield* git.statusDetailsRemote(cwd, { refreshUpstream: false });
376 return details.hasUpstream && details.branch !== null
377 ? {
378 refName: details.branch,
379 aheadCount: details.aheadCount,
380 behindCount: details.behindCount,
381 }
382 : null;
383 }),
384 remoteStatus: Effect.fn("GitWorkflowService.remoteStatus")(function (input, options) {
385 return detectGitRepositoryForStatus("GitWorkflowService.remoteStatus", input.cwd).pipe(
386 Effect.flatMap((isGitRepository) =>
387 isGitRepository ? gitManager.remoteStatus(input, options) : Effect.succeed(null),
388 ),
389 );
390 }),
391 invalidateLocalStatus: gitManager.invalidateLocalStatus,
392 invalidateRemoteStatus: gitManager.invalidateRemoteStatus,
393 invalidateStatus: gitManager.invalidateStatus,
394 headPath: Effect.fn("GitWorkflowService.headPath")(function (cwd) {
395 return git
396 .execute({
397 operation: "GitWorkflowService.headPath",
398 cwd,
399 args: ["rev-parse", "--path-format=absolute", "--git-path", "HEAD"],
400 allowNonZeroExit: true,
401 })
402 .pipe(
403 Effect.map((result) => (result.exitCode === 0 ? result.stdout.trim() || null : null)),
404 Effect.orElseSucceed(() => null),
405 );
406 }),
407 pullCurrentBranch: Effect.fn("GitWorkflowService.pullCurrentBranch")(function (cwd) {
408 return ensureGitCommand("GitWorkflowService.pullCurrentBranch", cwd).pipe(
409 Effect.andThen(git.pullCurrentBranch(cwd)),
410 );
411 }),
412 runStackedAction: Effect.fn("GitWorkflowService.runStackedAction")(function (input, options) {
413 return ensureGit("GitWorkflowService.runStackedAction", input.cwd).pipe(
414 Effect.flatMap((handle) =>
415 withCheckoutLease(
416 handle.repository.rootPath,
417 gitManager.runStackedAction(input, options),
418 ),
419 ),
420 );
421 }),
422 resolvePullRequest: routeGitManager(
423 "GitWorkflowService.resolvePullRequest",
424 gitManager.resolvePullRequest,
425 ),
426 preparePullRequestThread: Effect.fn("GitWorkflowService.preparePullRequestThread")(
427 function (input) {
428 return ensureGit("GitWorkflowService.preparePullRequestThread", input.cwd).pipe(
429 Effect.flatMap((handle) =>
430 input.mode === "local"
431 ? withCheckoutLease(
432 handle.repository.rootPath,
433 gitManager.preparePullRequestThread(input),
434 )
435 : gitManager.preparePullRequestThread(input),
436 ),
437 );
438 },
439 ),
440 listRefs: Effect.fn("GitWorkflowService.listRefs")(function (input) {
441 return detectGitRepositoryForCommand("GitWorkflowService.listRefs", input.cwd).pipe(
442 Effect.flatMap((isGitRepository) =>
443 isGitRepository ? git.listRefs(input) : Effect.succeed(nonRepositoryListRefs()),
444 ),
445 );
446 }),
447 createWorktree: Effect.fn("GitWorkflowService.createWorktree")(function (input, options) {
448 return ensureGitCommand("GitWorkflowService.createWorktree", input.cwd).pipe(
449 Effect.andThen(gitManager.createWorktree(input, options)),
450 );
451 }),
452 listLocalBranchNames: Effect.fn("GitWorkflowService.listLocalBranchNames")(function (cwd) {
453 return ensureGitCommand("GitWorkflowService.listLocalBranchNames", cwd).pipe(
454 Effect.andThen(git.listLocalBranchNames(cwd)),
455 );
456 }),
457 fetchRemote: Effect.fn("GitWorkflowService.fetchRemote")(function (input) {
458 return ensureGitCommand("GitWorkflowService.fetchRemote", input.cwd).pipe(
459 Effect.andThen(git.fetchRemote(input)),
460 );
461 }),
462 remoteExists: Effect.fn("GitWorkflowService.remoteExists")(function (input) {
463 return ensureGitCommand("GitWorkflowService.remoteExists", input.cwd).pipe(
464 Effect.andThen(git.remoteExists(input)),
465 );
466 }),
467 remoteBranchExists: Effect.fn("GitWorkflowService.remoteBranchExists")(function (input) {
468 return ensureGitCommand("GitWorkflowService.remoteBranchExists", input.cwd).pipe(
469 Effect.andThen(git.remoteBranchExists(input)),
470 );
471 }),
472 resolvePrimaryRemoteName: Effect.fn("GitWorkflowService.resolvePrimaryRemoteName")(
473 function (cwd) {
474 return ensureGitCommand("GitWorkflowService.resolvePrimaryRemoteName", cwd).pipe(
475 Effect.andThen(git.resolvePrimaryRemoteName(cwd)),
476 );
477 },
478 ),
479 resolveRemoteTrackingCommit: Effect.fn("GitWorkflowService.resolveRemoteTrackingCommit")(
480 function (input) {
481 return ensureGitCommand("GitWorkflowService.resolveRemoteTrackingCommit", input.cwd).pipe(
482 Effect.andThen(git.resolveRemoteTrackingCommit(input)),
483 );
484 },
485 ),
486 resolveWorktreeBaseRemote: Effect.fn("GitWorkflowService.resolveWorktreeBaseRemote")(
487 function (input) {
488 return ensureGitCommand("GitWorkflowService.resolveWorktreeBaseRemote", input.cwd).pipe(
489 Effect.andThen(git.resolveWorktreeBaseRemote(input)),
490 );
491 },
492 ),
493 fetchWorktreeBaseCommit: Effect.fn("GitWorkflowService.fetchWorktreeBaseCommit")(
494 function (input) {
495 return ensureGitCommand("GitWorkflowService.fetchWorktreeBaseCommit", input.cwd).pipe(
496 Effect.andThen(git.fetchWorktreeBaseCommit(input)),
497 );
498 },
499 ),
500 removeWorktree: Effect.fn("GitWorkflowService.removeWorktree")(function (input) {
501 return ensureGitCommand("GitWorkflowService.removeWorktree", input.cwd).pipe(
502 Effect.andThen(git.removeWorktree(input)),
503 );
504 }),
505 pruneWorktrees: Effect.fn("GitWorkflowService.pruneWorktrees")(function (input) {
506 return ensureGitCommand("GitWorkflowService.pruneWorktrees", input.cwd).pipe(
507 Effect.andThen(git.pruneWorktrees(input)),
508 );
509 }),
510 deleteLocalBranch: Effect.fn("GitWorkflowService.deleteLocalBranch")(function (input) {
511 return ensureGitCommand("GitWorkflowService.deleteLocalBranch", input.cwd).pipe(
512 Effect.andThen(git.deleteLocalBranch(input)),
513 );
514 }),
515 createRef: Effect.fn("GitWorkflowService.createRef")(function (input) {
516 return ensureGitCommand("GitWorkflowService.createRef", input.cwd).pipe(
517 Effect.flatMap((handle) =>
518 input.switchRef
519 ? withCheckoutLease(handle.repository.rootPath, git.createRef(input))
520 : git.createRef(input),
521 ),
522 );
523 }),
524 switchRef: Effect.fn("GitWorkflowService.switchRef")(function (input) {
525 return ensureGitCommand("GitWorkflowService.switchRef", input.cwd).pipe(
526 Effect.flatMap((handle) =>
527 withCheckoutLease(handle.repository.rootPath, Effect.scoped(git.switchRef(input))),
528 ),
529 );
530 }),
531 renameBranch: Effect.fn("GitWorkflowService.renameBranch")(function (input) {
532 return ensureGit("GitWorkflowService.renameBranch", input.cwd).pipe(
533 Effect.andThen(git.renameBranch(input)),
534 );
535 }),
536 });
537});
538​
539export const layer = Layer.effect(GitWorkflowService, make);