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