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

GitWorkflowService.ts

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