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 withCheckoutLease(
381 handle.repository.rootPath,
382 gitManager.runStackedAction(input, options),
383 ),
384 ),
385 );
386 }),
387 resolvePullRequest: routeGitManager(
388 "GitWorkflowService.resolvePullRequest",
389 gitManager.resolvePullRequest,
390 ),
391 preparePullRequestThread: Effect.fn("GitWorkflowService.preparePullRequestThread")(
392 function (input) {
393 return ensureGit("GitWorkflowService.preparePullRequestThread", input.cwd).pipe(
394 Effect.flatMap((handle) =>
395 input.mode === "local"
396 ? withCheckoutLease(
397 handle.repository.rootPath,
398 gitManager.preparePullRequestThread(input),
399 )
400 : gitManager.preparePullRequestThread(input),
401 ),
402 );
403 },
404 ),
405 listRefs: Effect.fn("GitWorkflowService.listRefs")(function (input) {
406 return detectGitRepositoryForCommand("GitWorkflowService.listRefs", input.cwd).pipe(
407 Effect.flatMap((isGitRepository) =>
408 isGitRepository ? git.listRefs(input) : Effect.succeed(nonRepositoryListRefs()),
409 ),
410 );
411 }),
412 createWorktree: Effect.fn("GitWorkflowService.createWorktree")(function (input, options) {
413 return ensureGitCommand("GitWorkflowService.createWorktree", input.cwd).pipe(
414 Effect.andThen(gitManager.createWorktree(input, options)),
415 );
416 }),
417 listLocalBranchNames: Effect.fn("GitWorkflowService.listLocalBranchNames")(function (cwd) {
418 return ensureGitCommand("GitWorkflowService.listLocalBranchNames", cwd).pipe(
419 Effect.andThen(git.listLocalBranchNames(cwd)),
420 );
421 }),
422 fetchRemote: Effect.fn("GitWorkflowService.fetchRemote")(function (input) {
423 return ensureGitCommand("GitWorkflowService.fetchRemote", input.cwd).pipe(
424 Effect.andThen(git.fetchRemote(input)),
425 );
426 }),
427 remoteExists: Effect.fn("GitWorkflowService.remoteExists")(function (input) {
428 return ensureGitCommand("GitWorkflowService.remoteExists", input.cwd).pipe(
429 Effect.andThen(git.remoteExists(input)),
430 );
431 }),
432 remoteBranchExists: Effect.fn("GitWorkflowService.remoteBranchExists")(function (input) {
433 return ensureGitCommand("GitWorkflowService.remoteBranchExists", input.cwd).pipe(
434 Effect.andThen(git.remoteBranchExists(input)),
435 );
436 }),
437 resolveRemoteTrackingCommit: Effect.fn("GitWorkflowService.resolveRemoteTrackingCommit")(
438 function (input) {
439 return ensureGitCommand("GitWorkflowService.resolveRemoteTrackingCommit", input.cwd).pipe(
440 Effect.andThen(git.resolveRemoteTrackingCommit(input)),
441 );
442 },
443 ),
444 resolveWorktreeBaseRemote: Effect.fn("GitWorkflowService.resolveWorktreeBaseRemote")(
445 function (input) {
446 return ensureGitCommand("GitWorkflowService.resolveWorktreeBaseRemote", input.cwd).pipe(
447 Effect.andThen(git.resolveWorktreeBaseRemote(input)),
448 );
449 },
450 ),
451 fetchWorktreeBaseCommit: Effect.fn("GitWorkflowService.fetchWorktreeBaseCommit")(
452 function (input) {
453 return ensureGitCommand("GitWorkflowService.fetchWorktreeBaseCommit", input.cwd).pipe(
454 Effect.andThen(git.fetchWorktreeBaseCommit(input)),
455 );
456 },
457 ),
458 removeWorktree: Effect.fn("GitWorkflowService.removeWorktree")(function (input) {
459 return ensureGitCommand("GitWorkflowService.removeWorktree", input.cwd).pipe(
460 Effect.andThen(git.removeWorktree(input)),
461 );
462 }),
463 pruneWorktrees: Effect.fn("GitWorkflowService.pruneWorktrees")(function (input) {
464 return ensureGitCommand("GitWorkflowService.pruneWorktrees", input.cwd).pipe(
465 Effect.andThen(git.pruneWorktrees(input)),
466 );
467 }),
468 deleteLocalBranch: Effect.fn("GitWorkflowService.deleteLocalBranch")(function (input) {
469 return ensureGitCommand("GitWorkflowService.deleteLocalBranch", input.cwd).pipe(
470 Effect.andThen(git.deleteLocalBranch(input)),
471 );
472 }),
473 createRef: Effect.fn("GitWorkflowService.createRef")(function (input) {
474 return ensureGitCommand("GitWorkflowService.createRef", input.cwd).pipe(
475 Effect.flatMap((handle) =>
476 input.switchRef
477 ? withCheckoutLease(handle.repository.rootPath, git.createRef(input))
478 : git.createRef(input),
479 ),
480 );
481 }),
482 switchRef: Effect.fn("GitWorkflowService.switchRef")(function (input) {
483 return ensureGitCommand("GitWorkflowService.switchRef", input.cwd).pipe(
484 Effect.flatMap((handle) =>
485 withCheckoutLease(handle.repository.rootPath, Effect.scoped(git.switchRef(input))),
486 ),
487 );
488 }),
489 renameBranch: Effect.fn("GitWorkflowService.renameBranch")(function (input) {
490 return ensureGit("GitWorkflowService.renameBranch", input.cwd).pipe(
491 Effect.andThen(git.renameBranch(input)),
492 );
493 }),
494 });
495});
496
497export const layer = Layer.effect(GitWorkflowService, make);