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