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