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: (cwd) =>
303 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 hasCommit: (input) =>
316 ensureGitCommand("GitWorkflowService.hasCommit", input.cwd).pipe(
317 Effect.andThen(
318 git.execute({
319 operation: "GitWorkflowService.hasCommit",
320 cwd: input.cwd,
321 args: ["rev-parse", "--verify", `${input.refName}^{commit}`],
322 allowNonZeroExit: true,
323 }),
324 ),
325 Effect.map((result) => result.exitCode === 0),
326 ),
327 hasRefNamed: (input) =>
328 // Pattern characters would widen the ref match.
329 /[*?[\\]/.test(input.refName)
330 ? Effect.succeed(false)
331 : ensureGitCommand("GitWorkflowService.hasRefNamed", input.cwd).pipe(
332 Effect.andThen(
333 git.execute({
334 operation: "GitWorkflowService.hasRefNamed",
335 cwd: input.cwd,
336 args: [
337 "for-each-ref",
338 "--count=1",
339 "--format=%(refname)",
340 `refs/**/${input.refName}`,
341 ],
342 }),
343 ),
344 Effect.map((result) => result.stdout.trim().length > 0),
345 ),
346 status: (input) =>
347 detectGitRepositoryForStatus("GitWorkflowService.status", input.cwd).pipe(
348 Effect.flatMap((isGitRepository) =>
349 isGitRepository ? gitManager.status(input) : Effect.succeed(nonRepositoryStatus()),
350 ),
351 ),
352 localStatus: (input) =>
353 detectGitRepositoryForStatus("GitWorkflowService.localStatus", input.cwd).pipe(
354 Effect.flatMap((isGitRepository) =>
355 isGitRepository
356 ? gitManager.localStatus(input)
357 : Effect.succeed(nonRepositoryLocalStatus()),
358 ),
359 ),
360 remoteStatus: (input, options) =>
361 detectGitRepositoryForStatus("GitWorkflowService.remoteStatus", input.cwd).pipe(
362 Effect.flatMap((isGitRepository) =>
363 isGitRepository ? gitManager.remoteStatus(input, options) : Effect.succeed(null),
364 ),
365 ),
366 invalidateLocalStatus: gitManager.invalidateLocalStatus,
367 invalidateRemoteStatus: gitManager.invalidateRemoteStatus,
368 invalidateStatus: gitManager.invalidateStatus,
369 pullCurrentBranch: (cwd) =>
370 ensureGitCommand("GitWorkflowService.pullCurrentBranch", cwd).pipe(
371 Effect.andThen(git.pullCurrentBranch(cwd)),
372 ),
373 runStackedAction: (input, options) =>
374 ensureGit("GitWorkflowService.runStackedAction", input.cwd).pipe(
375 Effect.flatMap((handle) =>
376 input.featureBranch
377 ? withCheckoutLease(
378 handle.repository.rootPath,
379 gitManager.runStackedAction(input, options),
380 )
381 : gitManager.runStackedAction(input, options),
382 ),
383 ),
384 resolvePullRequest: routeGitManager(
385 "GitWorkflowService.resolvePullRequest",
386 gitManager.resolvePullRequest,
387 ),
388 preparePullRequestThread: (input) =>
389 ensureGit("GitWorkflowService.preparePullRequestThread", input.cwd).pipe(
390 Effect.flatMap((handle) =>
391 input.mode === "local"
392 ? withCheckoutLease(
393 handle.repository.rootPath,
394 gitManager.preparePullRequestThread(input),
395 )
396 : gitManager.preparePullRequestThread(input),
397 ),
398 ),
399 listRefs: (input) =>
400 detectGitRepositoryForCommand("GitWorkflowService.listRefs", input.cwd).pipe(
401 Effect.flatMap((isGitRepository) =>
402 isGitRepository ? git.listRefs(input) : Effect.succeed(nonRepositoryListRefs()),
403 ),
404 ),
405 createWorktree: (input, options) =>
406 ensureGitCommand("GitWorkflowService.createWorktree", input.cwd).pipe(
407 Effect.andThen(gitManager.createWorktree(input, options)),
408 ),
409 listLocalBranchNames: (cwd) =>
410 ensureGitCommand("GitWorkflowService.listLocalBranchNames", cwd).pipe(
411 Effect.andThen(git.listLocalBranchNames(cwd)),
412 ),
413 fetchRemote: (input) =>
414 ensureGitCommand("GitWorkflowService.fetchRemote", input.cwd).pipe(
415 Effect.andThen(git.fetchRemote(input)),
416 ),
417 remoteExists: (input) =>
418 ensureGitCommand("GitWorkflowService.remoteExists", input.cwd).pipe(
419 Effect.andThen(git.remoteExists(input)),
420 ),
421 remoteBranchExists: (input) =>
422 ensureGitCommand("GitWorkflowService.remoteBranchExists", input.cwd).pipe(
423 Effect.andThen(git.remoteBranchExists(input)),
424 ),
425 resolveRemoteTrackingCommit: (input) =>
426 ensureGitCommand("GitWorkflowService.resolveRemoteTrackingCommit", input.cwd).pipe(
427 Effect.andThen(git.resolveRemoteTrackingCommit(input)),
428 ),
429 resolveWorktreeBaseRemote: (input) =>
430 ensureGitCommand("GitWorkflowService.resolveWorktreeBaseRemote", input.cwd).pipe(
431 Effect.andThen(git.resolveWorktreeBaseRemote(input)),
432 ),
433 fetchWorktreeBaseCommit: (input) =>
434 ensureGitCommand("GitWorkflowService.fetchWorktreeBaseCommit", input.cwd).pipe(
435 Effect.andThen(git.fetchWorktreeBaseCommit(input)),
436 ),
437 removeWorktree: (input) =>
438 ensureGitCommand("GitWorkflowService.removeWorktree", input.cwd).pipe(
439 Effect.andThen(git.removeWorktree(input)),
440 ),
441 pruneWorktrees: (input) =>
442 ensureGitCommand("GitWorkflowService.pruneWorktrees", input.cwd).pipe(
443 Effect.andThen(git.pruneWorktrees(input)),
444 ),
445 deleteLocalBranch: (input) =>
446 ensureGitCommand("GitWorkflowService.deleteLocalBranch", input.cwd).pipe(
447 Effect.andThen(git.deleteLocalBranch(input)),
448 ),
449 createRef: (input) =>
450 ensureGitCommand("GitWorkflowService.createRef", input.cwd).pipe(
451 Effect.flatMap((handle) =>
452 input.switchRef
453 ? withCheckoutLease(handle.repository.rootPath, git.createRef(input))
454 : git.createRef(input),
455 ),
456 ),
457 switchRef: (input) =>
458 ensureGitCommand("GitWorkflowService.switchRef", input.cwd).pipe(
459 Effect.flatMap((handle) =>
460 withCheckoutLease(handle.repository.rootPath, Effect.scoped(git.switchRef(input))),
461 ),
462 ),
463 renameBranch: (input) =>
464 ensureGit("GitWorkflowService.renameBranch", input.cwd).pipe(
465 Effect.andThen(git.renameBranch(input)),
466 ),
467 });
468});
469
470export const layer = Layer.effect(GitWorkflowService, make);