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