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

GitWorkflowService.ts

438 lines15.1 KB

1import * as Context from "effect/Context";
2import * as Effect from "effect/Effect";
3import * as Layer from "effect/Layer";
4​
5import {
6 GitManagerError,
7 GitCommandError,
8 type VcsSwitchRefInput,
9 type VcsSwitchRefResult,
10 type VcsCreateRefInput,
11 type VcsCreateRefResult,
12 type VcsCreateWorktreeInput,
13 type VcsCreateWorktreeResult,
14 type VcsListRefsInput,
15 type VcsListRefsResult,
16 type GitManagerServiceError,
17 type GitPreparePullRequestThreadInput,
18 type GitPreparePullRequestThreadResult,
19 type GitPullRequestRefInput,
20 type VcsPullResult,
21 type VcsRemoveWorktreeInput,
22 type GitResolvePullRequestResult,
23 type GitRunStackedActionInput,
24 type GitRunStackedActionResult,
25 type VcsStatusInput,
26 type VcsStatusLocalResult,
27 type VcsStatusRemoteResult,
28 type VcsStatusResult,
29} from "@t3tools/contracts";
30​
31import * as GitManager from "./GitManager.ts";
32import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
33import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
34​
35export class GitWorkflowService extends Context.Service<
36 GitWorkflowService,
37 {
38 readonly isRepository: (cwd: string) => Effect.Effect<boolean, GitManagerServiceError>;
39 readonly hasCommit: (input: {
40 readonly cwd: string;
41 readonly refName: string;
42 }) => Effect.Effect<boolean, GitCommandError>;
43 readonly hasRefNamed: (input: {
44 readonly cwd: string;
45 readonly refName: string;
46 }) => Effect.Effect<boolean, GitCommandError>;
47 readonly status: (
48 input: VcsStatusInput,
49 ) => Effect.Effect<VcsStatusResult, GitManagerServiceError>;
50 readonly localStatus: (
51 input: VcsStatusInput,
52 ) => Effect.Effect<VcsStatusLocalResult, GitManagerServiceError>;
53 readonly remoteStatus: (
54 input: VcsStatusInput,
55 options?: GitManager.GitRemoteStatusOptions,
56 ) => Effect.Effect<VcsStatusRemoteResult | null, GitManagerServiceError>;
57 readonly invalidateLocalStatus: (cwd: string) => Effect.Effect<void, never>;
58 readonly invalidateRemoteStatus: (cwd: string) => Effect.Effect<void, never>;
59 readonly invalidateStatus: (cwd: string) => Effect.Effect<void, never>;
60 readonly pullCurrentBranch: (cwd: string) => Effect.Effect<VcsPullResult, GitCommandError>;
61 readonly runStackedAction: (
62 input: GitRunStackedActionInput,
63 options?: GitManager.GitRunStackedActionOptions,
64 ) => Effect.Effect<GitRunStackedActionResult, GitManagerServiceError>;
65 readonly resolvePullRequest: (
66 input: GitPullRequestRefInput,
67 ) => Effect.Effect<GitResolvePullRequestResult, GitManagerServiceError>;
68 readonly preparePullRequestThread: (
69 input: GitPreparePullRequestThreadInput,
70 ) => Effect.Effect<GitPreparePullRequestThreadResult, GitManagerServiceError>;
71 readonly listRefs: (
72 input: VcsListRefsInput,
73 ) => Effect.Effect<VcsListRefsResult, GitCommandError>;
74 readonly createWorktree: (
75 input: VcsCreateWorktreeInput,
76 options?: GitVcsDriver.CreateWorktreeOptions,
77 ) => Effect.Effect<VcsCreateWorktreeResult, GitCommandError>;
78 readonly listLocalBranchNames: (cwd: string) => Effect.Effect<string[], GitCommandError>;
79 readonly fetchRemote: (input: {
80 readonly cwd: string;
81 readonly remoteName: string;
82 readonly refName?: string;
83 }) => Effect.Effect<void, GitCommandError>;
84 readonly remoteExists: (input: {
85 readonly cwd: string;
86 readonly remoteName: string;
87 }) => Effect.Effect<boolean, GitCommandError>;
88 readonly remoteBranchExists: (input: {
89 readonly cwd: string;
90 readonly remoteName: string;
91 readonly refName: string;
92 }) => Effect.Effect<boolean, GitCommandError>;
93 readonly resolveRemoteTrackingCommit: (input: {
94 readonly cwd: string;
95 readonly refName: string;
96 readonly fallbackRemoteName: string;
97 }) => Effect.Effect<
98 { readonly commitSha: string; readonly remoteRefName: string },
99 GitCommandError
100 >;
101 readonly resolveWorktreeBaseRemote: GitVcsDriver.GitVcsDriver["Service"]["resolveWorktreeBaseRemote"];
102 readonly fetchWorktreeBaseCommit: (input: {
103 readonly cwd: string;
104 readonly refName: string;
105 }) => Effect.Effect<
106 { readonly commitSha: string; readonly remoteRefName: string } | null,
107 GitCommandError
108 >;
109 readonly removeWorktree: (
110 input: VcsRemoveWorktreeInput,
111 ) => Effect.Effect<void, GitCommandError>;
112 readonly pruneWorktrees: (input: {
113 readonly cwd: string;
114 }) => Effect.Effect<void, GitCommandError>;
115 readonly deleteLocalBranch: (
116 input: GitVcsDriver.GitDeleteLocalBranchInput,
117 ) => Effect.Effect<void, GitCommandError>;
118 readonly createRef: (
119 input: VcsCreateRefInput,
120 ) => Effect.Effect<VcsCreateRefResult, GitCommandError>;
121 readonly switchRef: (
122 input: VcsSwitchRefInput,
123 ) => Effect.Effect<VcsSwitchRefResult, GitCommandError>;
124 readonly renameBranch: (input: {
125 readonly exactName?: boolean;
126 readonly cwd: string;
127 readonly oldBranch: string;
128 readonly newBranch: string;
129 }) => Effect.Effect<{ readonly branch: string }, GitManagerServiceError>;
130 }
131>()("t3/git/GitWorkflowService") {}
132​
133function nonRepositoryLocalStatus(): VcsStatusLocalResult {
134 return {
135 isRepo: false,
136 hasPrimaryRemote: false,
137 isDefaultRef: false,
138 refName: null,
139 hasWorkingTreeChanges: false,
140 workingTree: {
141 files: [],
142 insertions: 0,
143 deletions: 0,
144 },
145 };
147​
148function nonRepositoryStatus(): VcsStatusResult {
149 return {
150 ...nonRepositoryLocalStatus(),
151 hasUpstream: false,
152 aheadCount: 0,
153 behindCount: 0,
154 aheadOfDefaultCount: 0,
155 pr: null,
156 };
158​
159function nonRepositoryListRefs(): VcsListRefsResult {
160 return {
161 refs: [],
162 isRepo: false,
163 hasPrimaryRemote: false,
164 nextCursor: null,
165 totalCount: 0,
166 };
168​
169/** @public */
170export const make = Effect.gen(function* () {
171 const registry = yield* VcsDriverRegistry.VcsDriverRegistry;
172 const git = yield* GitVcsDriver.GitVcsDriver;
173 const gitManager = yield* GitManager.GitManager;
174​
175 const ensureGit = Effect.fn("GitWorkflowService.ensureGit")(function* (
176 operation: string,
177 cwd: string,
178 ) {
179 const handle = yield* registry.resolve({ cwd }).pipe(
180 Effect.mapError(
181 (cause) =>
182 new GitManagerError({
183 operation,
184 cwd,
185 detail: "Failed to resolve the VCS driver for this Git workflow.",
186 cause,
187 }),
188 ),
189 );
190 if (handle.kind !== "git") {
191 return yield* new GitManagerError({
192 operation,
193 cwd,
194 detail: `The ${operation} workflow currently supports Git repositories only; detected ${handle.kind}. (${cwd})`,
195 });
196 }
197 });
198​
199 const ensureGitCommand = Effect.fn("GitWorkflowService.ensureGitCommand")(function* (
200 operation: string,
201 cwd: string,
202 ) {
203 const handle = yield* registry.resolve({ cwd }).pipe(
204 Effect.mapError(
205 (cause) =>
206 new GitCommandError({
207 operation,
208 command: "vcs-route",
209 cwd,
210 detail: "Failed to resolve the VCS driver for this Git command.",
211 cause,
212 }),
213 ),
214 );
215 if (handle.kind !== "git") {
216 return yield* new GitCommandError({
217 operation,
218 command: "vcs-route",
219 cwd,
220 detail: `The ${operation} command currently supports Git repositories only; detected ${handle.kind}.`,
221 });
222 }
223 });
224​
225 const detectGitRepositoryForStatus = Effect.fn("GitWorkflowService.detectGitRepositoryForStatus")(
226 function* (operation: string, cwd: string) {
227 const handle = yield* registry.detect({ cwd }).pipe(
228 Effect.mapError(
229 (cause) =>
230 new GitManagerError({
231 operation,
232 cwd,
233 detail: "Failed to detect a VCS repository for this Git workflow.",
234 cause,
235 }),
236 ),
237 );
238 if (!handle) {
239 return false;
240 }
241 if (handle.kind !== "git") {
242 return yield* new GitManagerError({
243 operation,
244 cwd,
245 detail: `The ${operation} workflow currently supports Git repositories only; detected ${handle.kind}. (${cwd})`,
246 });
247 }
248 return true;
249 },
250 );
251​
252 const detectGitRepositoryForCommand = Effect.fn(
253 "GitWorkflowService.detectGitRepositoryForCommand",
254 )(function* (operation: string, cwd: string) {
255 const handle = yield* registry.detect({ cwd }).pipe(
256 Effect.mapError(
257 (cause) =>
258 new GitCommandError({
259 operation,
260 command: "vcs-route",
261 cwd,
262 detail: "Failed to detect a VCS repository for this Git command.",
263 cause,
264 }),
265 ),
266 );
267 if (!handle) {
268 return false;
269 }
270 if (handle.kind !== "git") {
271 return yield* new GitCommandError({
272 operation,
273 command: "vcs-route",
274 cwd,
275 detail: `The ${operation} command currently supports Git repositories only; detected ${handle.kind}.`,
276 });
277 }
278 return true;
279 });
280​
281 const routeGitManager =
282 <Input extends { readonly cwd: string }, Output>(
283 operation: string,
284 run: (input: Input) => Effect.Effect<Output, GitManagerServiceError>,
285 ) =>
286 (input: Input) =>
287 ensureGit(operation, input.cwd).pipe(Effect.andThen(run(input)));
288​
289 return GitWorkflowService.of({
290 isRepository: (cwd) =>
291 registry.detect({ cwd }).pipe(
292 Effect.map((handle) => handle?.kind === "git"),
293 Effect.mapError(
294 (cause) =>
295 new GitManagerError({
296 operation: "GitWorkflowService.isRepository",
297 cwd,
298 detail: "Failed to detect a VCS repository for this Git workflow.",
299 cause,
300 }),
301 ),
302 ),
303 hasCommit: (input) =>
304 ensureGitCommand("GitWorkflowService.hasCommit", input.cwd).pipe(
305 Effect.andThen(
306 git.execute({
307 operation: "GitWorkflowService.hasCommit",
308 cwd: input.cwd,
309 args: ["rev-parse", "--verify", `${input.refName}^{commit}`],
310 allowNonZeroExit: true,
311 }),
312 ),
313 Effect.map((result) => result.exitCode === 0),
314 ),
315 hasRefNamed: (input) =>
316 // No ref name holds a pattern character, and one here would widen the match.
317 /[*?[\\]/.test(input.refName)
318 ? Effect.succeed(false)
319 : ensureGitCommand("GitWorkflowService.hasRefNamed", input.cwd).pipe(
320 Effect.andThen(
321 git.execute({
322 operation: "GitWorkflowService.hasRefNamed",
323 cwd: input.cwd,
324 args: [
325 "for-each-ref",
326 "--count=1",
327 "--format=%(refname)",
328 `refs/**/${input.refName}`,
329 ],
330 }),
331 ),
332 Effect.map((result) => result.stdout.trim().length > 0),
333 ),
334 status: (input) =>
335 detectGitRepositoryForStatus("GitWorkflowService.status", input.cwd).pipe(
336 Effect.flatMap((isGitRepository) =>
337 isGitRepository ? gitManager.status(input) : Effect.succeed(nonRepositoryStatus()),
338 ),
339 ),
340 localStatus: (input) =>
341 detectGitRepositoryForStatus("GitWorkflowService.localStatus", input.cwd).pipe(
342 Effect.flatMap((isGitRepository) =>
343 isGitRepository
344 ? gitManager.localStatus(input)
345 : Effect.succeed(nonRepositoryLocalStatus()),
346 ),
347 ),
348 remoteStatus: (input, options) =>
349 detectGitRepositoryForStatus("GitWorkflowService.remoteStatus", input.cwd).pipe(
350 Effect.flatMap((isGitRepository) =>
351 isGitRepository ? gitManager.remoteStatus(input, options) : Effect.succeed(null),
352 ),
353 ),
354 invalidateLocalStatus: gitManager.invalidateLocalStatus,
355 invalidateRemoteStatus: gitManager.invalidateRemoteStatus,
356 invalidateStatus: gitManager.invalidateStatus,
357 pullCurrentBranch: (cwd) =>
358 ensureGitCommand("GitWorkflowService.pullCurrentBranch", cwd).pipe(
359 Effect.andThen(git.pullCurrentBranch(cwd)),
360 ),
361 runStackedAction: (input, options) =>
362 ensureGit("GitWorkflowService.runStackedAction", input.cwd).pipe(
363 Effect.andThen(gitManager.runStackedAction(input, options)),
364 ),
365 resolvePullRequest: routeGitManager(
366 "GitWorkflowService.resolvePullRequest",
367 gitManager.resolvePullRequest,
368 ),
369 preparePullRequestThread: routeGitManager(
370 "GitWorkflowService.preparePullRequestThread",
371 gitManager.preparePullRequestThread,
372 ),
373 listRefs: (input) =>
374 detectGitRepositoryForCommand("GitWorkflowService.listRefs", input.cwd).pipe(
375 Effect.flatMap((isGitRepository) =>
376 isGitRepository ? git.listRefs(input) : Effect.succeed(nonRepositoryListRefs()),
377 ),
378 ),
379 createWorktree: (input, options) =>
380 ensureGitCommand("GitWorkflowService.createWorktree", input.cwd).pipe(
381 Effect.andThen(gitManager.createWorktree(input, options)),
382 ),
383 listLocalBranchNames: (cwd) =>
384 ensureGitCommand("GitWorkflowService.listLocalBranchNames", cwd).pipe(
385 Effect.andThen(git.listLocalBranchNames(cwd)),
386 ),
387 fetchRemote: (input) =>
388 ensureGitCommand("GitWorkflowService.fetchRemote", input.cwd).pipe(
389 Effect.andThen(git.fetchRemote(input)),
390 ),
391 remoteExists: (input) =>
392 ensureGitCommand("GitWorkflowService.remoteExists", input.cwd).pipe(
393 Effect.andThen(git.remoteExists(input)),
394 ),
395 remoteBranchExists: (input) =>
396 ensureGitCommand("GitWorkflowService.remoteBranchExists", input.cwd).pipe(
397 Effect.andThen(git.remoteBranchExists(input)),
398 ),
399 resolveRemoteTrackingCommit: (input) =>
400 ensureGitCommand("GitWorkflowService.resolveRemoteTrackingCommit", input.cwd).pipe(
401 Effect.andThen(git.resolveRemoteTrackingCommit(input)),
402 ),
403 resolveWorktreeBaseRemote: (input) =>
404 ensureGitCommand("GitWorkflowService.resolveWorktreeBaseRemote", input.cwd).pipe(
405 Effect.andThen(git.resolveWorktreeBaseRemote(input)),
406 ),
407 fetchWorktreeBaseCommit: (input) =>
408 ensureGitCommand("GitWorkflowService.fetchWorktreeBaseCommit", input.cwd).pipe(
409 Effect.andThen(git.fetchWorktreeBaseCommit(input)),
410 ),
411 removeWorktree: (input) =>
412 ensureGitCommand("GitWorkflowService.removeWorktree", input.cwd).pipe(
413 Effect.andThen(git.removeWorktree(input)),
414 ),
415 pruneWorktrees: (input) =>
416 ensureGitCommand("GitWorkflowService.pruneWorktrees", input.cwd).pipe(
417 Effect.andThen(git.pruneWorktrees(input)),
418 ),
419 deleteLocalBranch: (input) =>
420 ensureGitCommand("GitWorkflowService.deleteLocalBranch", input.cwd).pipe(
421 Effect.andThen(git.deleteLocalBranch(input)),
422 ),
423 createRef: (input) =>
424 ensureGitCommand("GitWorkflowService.createRef", input.cwd).pipe(
425 Effect.andThen(git.createRef(input)),
426 ),
427 switchRef: (input) =>
428 ensureGitCommand("GitWorkflowService.switchRef", input.cwd).pipe(
429 Effect.andThen(Effect.scoped(git.switchRef(input))),
430 ),
431 renameBranch: (input) =>
432 ensureGit("GitWorkflowService.renameBranch", input.cwd).pipe(
433 Effect.andThen(git.renameBranch(input)),
434 ),
435 });
436});
437​
438export const layer = Layer.effect(GitWorkflowService, make);