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