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