Skip to content
Source
Sign inSign up
Open History to see the last commit

GitWorkflowService.ts

513 lines18.8 KB

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