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