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

GitWorkflowService.ts

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