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 WorkspaceWorktrees from "./WorkspaceWorktrees.ts";
34import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
35import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
36import { withWorkspaceLease } from "../workspace/workspaceLease.ts";
37
38export class GitWorkflowService extends Context.Service<
39 GitWorkflowService,
40 {
41 readonly isRepository: (cwd: string) => Effect.Effect<boolean, GitManagerServiceError>;
42 readonly hasCommit: (input: {
43 readonly cwd: string;
44 readonly refName: string;
45 }) => Effect.Effect<boolean, GitCommandError>;
46 readonly hasRefNamed: (input: {
47 readonly cwd: string;
48 readonly refName: string;
49 }) => Effect.Effect<boolean, GitCommandError>;
50 readonly status: (
51 input: VcsStatusInput,
52 ) => Effect.Effect<VcsStatusResult, GitManagerServiceError>;
53 readonly localStatus: (
54 input: VcsStatusInput,
55 ) => Effect.Effect<VcsStatusLocalResult, 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 workspaceWorktrees = yield* WorkspaceWorktrees.WorkspaceWorktrees;
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 if (handle.kind !== "git") {
203 return yield* new GitManagerError({
204 operation,
205 cwd,
206 detail: `The ${operation} workflow currently supports Git repositories only; detected ${handle.kind}. (${cwd})`,
207 });
208 }
209 return handle;
210 });
211
212 const ensureGitCommand = Effect.fn("GitWorkflowService.ensureGitCommand")(function* (
213 operation: string,
214 cwd: string,
215 ) {
216 const handle = yield* registry.resolve({ cwd }).pipe(
217 Effect.mapError(
218 (cause) =>
219 new GitCommandError({
220 operation,
221 command: "vcs-route",
222 cwd,
223 detail: "Failed to resolve the VCS driver for this Git command.",
224 cause,
225 }),
226 ),
227 );
228 if (handle.kind !== "git") {
229 return yield* new GitCommandError({
230 operation,
231 command: "vcs-route",
232 cwd,
233 detail: `The ${operation} command currently supports Git repositories only; detected ${handle.kind}.`,
234 });
235 }
236 return handle;
237 });
238
239 const detectGitRepositoryForStatus = Effect.fn("GitWorkflowService.detectGitRepositoryForStatus")(
240 function* (operation: string, cwd: string) {
241 const handle = yield* registry.detect({ cwd }).pipe(
242 Effect.mapError(
243 (cause) =>
244 new GitManagerError({
245 operation,
246 cwd,
247 detail: "Failed to detect a VCS repository for this Git workflow.",
248 cause,
249 }),
250 ),
251 );
252 if (!handle) {
253 return false;
254 }
255 if (handle.kind !== "git") {
256 return yield* new GitManagerError({
257 operation,
258 cwd,
259 detail: `The ${operation} workflow currently supports Git repositories only; detected ${handle.kind}. (${cwd})`,
260 });
261 }
262 return true;
263 },
264 );
265
266 const detectGitRepositoryForCommand = Effect.fn(
267 "GitWorkflowService.detectGitRepositoryForCommand",
268 )(function* (operation: string, cwd: string) {
269 const handle = yield* registry.detect({ cwd }).pipe(
270 Effect.mapError(
271 (cause) =>
272 new GitCommandError({
273 operation,
274 command: "vcs-route",
275 cwd,
276 detail: "Failed to detect a VCS repository for this Git command.",
277 cause,
278 }),
279 ),
280 );
281 if (!handle) {
282 return false;
283 }
284 if (handle.kind !== "git") {
285 return yield* new GitCommandError({
286 operation,
287 command: "vcs-route",
288 cwd,
289 detail: `The ${operation} command currently supports Git repositories only; detected ${handle.kind}.`,
290 });
291 }
292 return true;
293 });
294
295 const routeGitManager =
296 <Input extends { readonly cwd: string }, Output>(
297 operation: string,
298 run: (input: Input) => Effect.Effect<Output, GitManagerServiceError>,
299 ) =>
300 (input: Input) =>
301 ensureGit(operation, input.cwd).pipe(Effect.andThen(run(input)));
302
303 return GitWorkflowService.of({
304 isRepository: Effect.fn("GitWorkflowService.isRepository")(function (cwd) {
305 return registry.detect({ cwd }).pipe(
306 Effect.map((handle) => handle?.kind === "git"),
307 Effect.mapError(
308 (cause) =>
309 new GitManagerError({
310 operation: "GitWorkflowService.isRepository",
311 cwd,
312 detail: "Failed to detect a VCS repository for this Git workflow.",
313 cause,
314 }),
315 ),
316 );
317 }),
318 hasCommit: Effect.fn("GitWorkflowService.hasCommit")(function (input) {
319 return ensureGitCommand("GitWorkflowService.hasCommit", input.cwd).pipe(
320 Effect.andThen(
321 git.execute({
322 operation: "GitWorkflowService.hasCommit",
323 cwd: input.cwd,
324 args: ["rev-parse", "--verify", `${input.refName}^{commit}`],
325 allowNonZeroExit: true,
326 }),
327 ),
328 Effect.map((result) => result.exitCode === 0),
329 );
330 }),
331 hasRefNamed: Effect.fn("GitWorkflowService.hasRefNamed")(function (input) {
332 // Pattern characters would widen the ref match.
333 return /[*?[\\]/.test(input.refName)
334 ? Effect.succeed(false)
335 : ensureGitCommand("GitWorkflowService.hasRefNamed", input.cwd).pipe(
336 Effect.andThen(
337 git.execute({
338 operation: "GitWorkflowService.hasRefNamed",
339 cwd: input.cwd,
340 args: [
341 "for-each-ref",
342 "--count=1",
343 "--format=%(refname)",
344 `refs/**/${input.refName}`,
345 ],
346 }),
347 ),
348 Effect.map((result) => result.stdout.trim().length > 0),
349 );
350 }),
351 status: Effect.fn("GitWorkflowService.status")(function (input) {
352 return detectGitRepositoryForStatus("GitWorkflowService.status", input.cwd).pipe(
353 Effect.flatMap((isGitRepository) =>
354 isGitRepository ? gitManager.status(input) : Effect.succeed(nonRepositoryStatus()),
355 ),
356 );
357 }),
358 localStatus: Effect.fn("GitWorkflowService.localStatus")(function (input) {
359 return detectGitRepositoryForStatus("GitWorkflowService.localStatus", input.cwd).pipe(
360 Effect.flatMap((isGitRepository) =>
361 isGitRepository
362 ? gitManager.localStatus(input)
363 : Effect.succeed(nonRepositoryLocalStatus()),
364 ),
365 );
366 }),
367 remoteStatus: Effect.fn("GitWorkflowService.remoteStatus")(function (input, options) {
368 return detectGitRepositoryForStatus("GitWorkflowService.remoteStatus", input.cwd).pipe(
369 Effect.flatMap((isGitRepository) =>
370 isGitRepository ? gitManager.remoteStatus(input, options) : Effect.succeed(null),
371 ),
372 );
373 }),
374 invalidateLocalStatus: gitManager.invalidateLocalStatus,
375 invalidateRemoteStatus: gitManager.invalidateRemoteStatus,
376 invalidateStatus: gitManager.invalidateStatus,
377 pullCurrentBranch: Effect.fn("GitWorkflowService.pullCurrentBranch")(function (cwd) {
378 return ensureGitCommand("GitWorkflowService.pullCurrentBranch", cwd).pipe(
379 Effect.andThen(git.pullCurrentBranch(cwd)),
380 );
381 }),
382 runStackedAction: Effect.fn("GitWorkflowService.runStackedAction")(function (input, options) {
383 return ensureGit("GitWorkflowService.runStackedAction", input.cwd).pipe(
384 Effect.flatMap((handle) =>
385 input.featureBranch
386 ? withCheckoutLease(
387 handle.repository.rootPath,
388 gitManager.runStackedAction(input, options),
389 )
390 : gitManager.runStackedAction(input, options),
391 ),
392 );
393 }),
394 resolvePullRequest: routeGitManager(
395 "GitWorkflowService.resolvePullRequest",
396 gitManager.resolvePullRequest,
397 ),
398 preparePullRequestThread: Effect.fn("GitWorkflowService.preparePullRequestThread")(
399 function (input) {
400 return ensureGit("GitWorkflowService.preparePullRequestThread", input.cwd).pipe(
401 Effect.flatMap((handle) =>
402 input.mode === "local"
403 ? withCheckoutLease(
404 handle.repository.rootPath,
405 gitManager.preparePullRequestThread(input),
406 )
407 : gitManager.preparePullRequestThread(input),
408 ),
409 );
410 },
411 ),
412 listRefs: Effect.fn("GitWorkflowService.listRefs")(function (input) {
413 return detectGitRepositoryForCommand("GitWorkflowService.listRefs", input.cwd).pipe(
414 Effect.flatMap((isGitRepository) =>
415 isGitRepository ? git.listRefs(input) : Effect.succeed(nonRepositoryListRefs()),
416 ),
417 );
418 }),
419 createWorktree: Effect.fn("GitWorkflowService.createWorktree")(function (input, options) {
420 return ensureGitCommand("GitWorkflowService.createWorktree", input.cwd).pipe(
421 Effect.andThen(gitManager.createWorktree(input, options)),
422 );
423 }),
424 listLocalBranchNames: Effect.fn("GitWorkflowService.listLocalBranchNames")(function (cwd) {
425 return ensureGitCommand("GitWorkflowService.listLocalBranchNames", cwd).pipe(
426 Effect.andThen(git.listLocalBranchNames(cwd)),
427 );
428 }),
429 fetchRemote: Effect.fn("GitWorkflowService.fetchRemote")(function (input) {
430 return ensureGitCommand("GitWorkflowService.fetchRemote", input.cwd).pipe(
431 Effect.andThen(git.fetchRemote(input)),
432 );
433 }),
434 remoteExists: Effect.fn("GitWorkflowService.remoteExists")(function (input) {
435 return ensureGitCommand("GitWorkflowService.remoteExists", input.cwd).pipe(
436 Effect.andThen(git.remoteExists(input)),
437 );
438 }),
439 remoteBranchExists: Effect.fn("GitWorkflowService.remoteBranchExists")(function (input) {
440 return ensureGitCommand("GitWorkflowService.remoteBranchExists", input.cwd).pipe(
441 Effect.andThen(git.remoteBranchExists(input)),
442 );
443 }),
444 resolveRemoteTrackingCommit: Effect.fn("GitWorkflowService.resolveRemoteTrackingCommit")(
445 function (input) {
446 return ensureGitCommand("GitWorkflowService.resolveRemoteTrackingCommit", input.cwd).pipe(
447 Effect.andThen(git.resolveRemoteTrackingCommit(input)),
448 );
449 },
450 ),
451 resolveWorktreeBaseRemote: Effect.fn("GitWorkflowService.resolveWorktreeBaseRemote")(
452 function (input) {
453 return ensureGitCommand("GitWorkflowService.resolveWorktreeBaseRemote", input.cwd).pipe(
454 Effect.andThen(git.resolveWorktreeBaseRemote(input)),
455 );
456 },
457 ),
458 fetchWorktreeBaseCommit: Effect.fn("GitWorkflowService.fetchWorktreeBaseCommit")(
459 function (input) {
460 return ensureGitCommand("GitWorkflowService.fetchWorktreeBaseCommit", input.cwd).pipe(
461 Effect.andThen(git.fetchWorktreeBaseCommit(input)),
462 );
463 },
464 ),
465 removeWorktree: Effect.fn("GitWorkflowService.removeWorktree")(function (input) {
466 return workspaceWorktrees.isContainer(input.path).pipe(
467 Effect.flatMap((isContainer) =>
468 isContainer
469 ? workspaceWorktrees.remove({
470 workspaceRoot: input.cwd,
471 path: input.path,
472 force: input.force === true,
473 })
474 : ensureGitCommand("GitWorkflowService.removeWorktree", input.cwd).pipe(
475 Effect.andThen(git.removeWorktree(input)),
476 ),
477 ),
478 );
479 }),
480 pruneWorktrees: Effect.fn("GitWorkflowService.pruneWorktrees")(function (input) {
481 return ensureGitCommand("GitWorkflowService.pruneWorktrees", input.cwd).pipe(
482 Effect.andThen(git.pruneWorktrees(input)),
483 );
484 }),
485 deleteLocalBranch: Effect.fn("GitWorkflowService.deleteLocalBranch")(function (input) {
486 return ensureGitCommand("GitWorkflowService.deleteLocalBranch", input.cwd).pipe(
487 Effect.andThen(git.deleteLocalBranch(input)),
488 );
489 }),
490 createRef: Effect.fn("GitWorkflowService.createRef")(function (input) {
491 return ensureGitCommand("GitWorkflowService.createRef", input.cwd).pipe(
492 Effect.flatMap((handle) =>
493 input.switchRef
494 ? withCheckoutLease(handle.repository.rootPath, git.createRef(input))
495 : git.createRef(input),
496 ),
497 );
498 }),
499 switchRef: Effect.fn("GitWorkflowService.switchRef")(function (input) {
500 return ensureGitCommand("GitWorkflowService.switchRef", input.cwd).pipe(
501 Effect.flatMap((handle) =>
502 withCheckoutLease(handle.repository.rootPath, Effect.scoped(git.switchRef(input))),
503 ),
504 );
505 }),
506 renameBranch: Effect.fn("GitWorkflowService.renameBranch")(function (input) {
507 return ensureGit("GitWorkflowService.renameBranch", input.cwd).pipe(
508 Effect.andThen(git.renameBranch(input)),
509 );
510 }),
511 });
512});
513
514export const layer = Layer.effect(GitWorkflowService, make);