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

GitWorkflowService.ts

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