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