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