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: GitManager.GitManager["Service"]["invalidateStatus"];
63 readonly statusUpstreamFetchCount: GitVcsDriver.GitVcsDriver["Service"]["statusUpstreamFetchCount"];
64 readonly pullCurrentBranch: (cwd: string) => Effect.Effect<VcsPullResult, GitCommandError>;
65 readonly runStackedAction: (
66 input: GitRunStackedActionInput,
67 options?: GitManager.GitRunStackedActionOptions,
68 ) => Effect.Effect<GitRunStackedActionResult, GitManagerServiceError>;
69 readonly resolvePullRequest: (
70 input: GitPullRequestRefInput,
71 ) => Effect.Effect<GitResolvePullRequestResult, GitManagerServiceError>;
72 readonly preparePullRequestThread: (
73 input: GitPreparePullRequestThreadInput,
74 ) => Effect.Effect<GitPreparePullRequestThreadResult, GitManagerServiceError>;
75 readonly listRefs: (
76 input: VcsListRefsInput,
77 ) => Effect.Effect<VcsListRefsResult, GitCommandError>;
78 readonly createWorktree: (
79 input: VcsCreateWorktreeInput,
80 options?: GitVcsDriver.CreateWorktreeOptions,
81 ) => Effect.Effect<VcsCreateWorktreeResult, GitCommandError>;
82 readonly listLocalBranchNames: (cwd: string) => Effect.Effect<string[], GitCommandError>;
83 readonly fetchRemote: (input: {
84 readonly cwd: string;
85 readonly remoteName: string;
86 readonly refName?: string;
87 }) => Effect.Effect<void, GitCommandError>;
88 readonly remoteExists: (input: {
89 readonly cwd: string;
90 readonly remoteName: string;
91 }) => Effect.Effect<boolean, GitCommandError>;
92 readonly remoteBranchExists: (input: {
93 readonly cwd: string;
94 readonly remoteName: string;
95 readonly refName: string;
96 }) => Effect.Effect<boolean, GitCommandError>;
97 readonly resolveRemoteTrackingCommit: (input: {
98 readonly cwd: string;
99 readonly refName: string;
100 readonly fallbackRemoteName: string;
101 }) => Effect.Effect<
102 { readonly commitSha: string; readonly remoteRefName: string },
103 GitCommandError
104 >;
105 readonly resolveWorktreeBaseRemote: GitVcsDriver.GitVcsDriver["Service"]["resolveWorktreeBaseRemote"];
106 readonly fetchWorktreeBaseCommit: (input: {
107 readonly cwd: string;
108 readonly refName: string;
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 isRepository: Effect.fn("GitWorkflowService.isRepository")(function (cwd) {
275 return registry.detect({ cwd }).pipe(
276 Effect.map((handle) => handle?.kind === "git"),
277 Effect.mapError(
278 (cause) =>
279 new GitManagerError({
280 operation: "GitWorkflowService.isRepository",
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 statusUpstreamFetchCount: git.statusUpstreamFetchCount,
374 pullCurrentBranch: Effect.fn("GitWorkflowService.pullCurrentBranch")(function (cwd) {
375 return ensureGitCommand("GitWorkflowService.pullCurrentBranch", cwd).pipe(
376 Effect.andThen(git.pullCurrentBranch(cwd)),
377 );
378 }),
379 runStackedAction: Effect.fn("GitWorkflowService.runStackedAction")(function (input, options) {
380 return ensureGit("GitWorkflowService.runStackedAction", input.cwd).pipe(
381 Effect.flatMap((handle) =>
382 withCheckoutLease(
383 handle.repository.rootPath,
384 gitManager.runStackedAction(input, options),
385 ),
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);