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