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

GitWorkflowService.ts

422 lines14.4 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 removeWorktree: (
102 input: VcsRemoveWorktreeInput,
103 ) => Effect.Effect<void, GitCommandError>;
104 readonly pruneWorktrees: (input: {
105 readonly cwd: string;
106 }) => Effect.Effect<void, GitCommandError>;
107 readonly deleteLocalBranch: (
108 input: GitVcsDriver.GitDeleteLocalBranchInput,
109 ) => Effect.Effect<void, GitCommandError>;
110 readonly createRef: (
111 input: VcsCreateRefInput,
112 ) => Effect.Effect<VcsCreateRefResult, GitCommandError>;
113 readonly switchRef: (
114 input: VcsSwitchRefInput,
115 ) => Effect.Effect<VcsSwitchRefResult, GitCommandError>;
116 readonly renameBranch: (input: {
117 readonly exactName?: boolean;
118 readonly cwd: string;
119 readonly oldBranch: string;
120 readonly newBranch: string;
121 }) => Effect.Effect<{ readonly branch: string }, GitManagerServiceError>;
122 }
123>()("t3/git/GitWorkflowService") {}
124​
125function nonRepositoryLocalStatus(): VcsStatusLocalResult {
126 return {
127 isRepo: false,
128 hasPrimaryRemote: false,
129 isDefaultRef: false,
130 refName: null,
131 hasWorkingTreeChanges: false,
132 workingTree: {
133 files: [],
134 insertions: 0,
135 deletions: 0,
136 },
137 };
139​
140function nonRepositoryStatus(): VcsStatusResult {
141 return {
142 ...nonRepositoryLocalStatus(),
143 hasUpstream: false,
144 aheadCount: 0,
145 behindCount: 0,
146 aheadOfDefaultCount: 0,
147 pr: null,
148 };
150​
151function nonRepositoryListRefs(): VcsListRefsResult {
152 return {
153 refs: [],
154 isRepo: false,
155 hasPrimaryRemote: false,
156 nextCursor: null,
157 totalCount: 0,
158 };
160​
161/** @public */
162export const make = Effect.gen(function* () {
163 const registry = yield* VcsDriverRegistry.VcsDriverRegistry;
164 const git = yield* GitVcsDriver.GitVcsDriver;
165 const gitManager = yield* GitManager.GitManager;
166​
167 const ensureGit = Effect.fn("GitWorkflowService.ensureGit")(function* (
168 operation: string,
169 cwd: string,
170 ) {
171 const handle = yield* registry.resolve({ cwd }).pipe(
172 Effect.mapError(
173 (cause) =>
174 new GitManagerError({
175 operation,
176 cwd,
177 detail: "Failed to resolve the VCS driver for this Git workflow.",
178 cause,
179 }),
180 ),
181 );
182 if (handle.kind !== "git") {
183 return yield* new GitManagerError({
184 operation,
185 cwd,
186 detail: `The ${operation} workflow currently supports Git repositories only; detected ${handle.kind}. (${cwd})`,
187 });
188 }
189 });
190​
191 const ensureGitCommand = Effect.fn("GitWorkflowService.ensureGitCommand")(function* (
192 operation: string,
193 cwd: string,
194 ) {
195 const handle = yield* registry.resolve({ cwd }).pipe(
196 Effect.mapError(
197 (cause) =>
198 new GitCommandError({
199 operation,
200 command: "vcs-route",
201 cwd,
202 detail: "Failed to resolve the VCS driver for this Git command.",
203 cause,
204 }),
205 ),
206 );
207 if (handle.kind !== "git") {
208 return yield* new GitCommandError({
209 operation,
210 command: "vcs-route",
211 cwd,
212 detail: `The ${operation} command currently supports Git repositories only; detected ${handle.kind}.`,
213 });
214 }
215 });
216​
217 const detectGitRepositoryForStatus = Effect.fn("GitWorkflowService.detectGitRepositoryForStatus")(
218 function* (operation: string, cwd: string) {
219 const handle = yield* registry.detect({ cwd }).pipe(
220 Effect.mapError(
221 (cause) =>
222 new GitManagerError({
223 operation,
224 cwd,
225 detail: "Failed to detect a VCS repository for this Git workflow.",
226 cause,
227 }),
228 ),
229 );
230 if (!handle) {
231 return false;
232 }
233 if (handle.kind !== "git") {
234 return yield* new GitManagerError({
235 operation,
236 cwd,
237 detail: `The ${operation} workflow currently supports Git repositories only; detected ${handle.kind}. (${cwd})`,
238 });
239 }
240 return true;
241 },
242 );
243​
244 const detectGitRepositoryForCommand = Effect.fn(
245 "GitWorkflowService.detectGitRepositoryForCommand",
246 )(function* (operation: string, cwd: string) {
247 const handle = yield* registry.detect({ cwd }).pipe(
248 Effect.mapError(
249 (cause) =>
250 new GitCommandError({
251 operation,
252 command: "vcs-route",
253 cwd,
254 detail: "Failed to detect a VCS repository for this Git command.",
255 cause,
256 }),
257 ),
258 );
259 if (!handle) {
260 return false;
261 }
262 if (handle.kind !== "git") {
263 return yield* new GitCommandError({
264 operation,
265 command: "vcs-route",
266 cwd,
267 detail: `The ${operation} command currently supports Git repositories only; detected ${handle.kind}.`,
268 });
269 }
270 return true;
271 });
272​
273 const routeGitManager =
274 <Input extends { readonly cwd: string }, Output>(
275 operation: string,
276 run: (input: Input) => Effect.Effect<Output, GitManagerServiceError>,
277 ) =>
278 (input: Input) =>
279 ensureGit(operation, input.cwd).pipe(Effect.andThen(run(input)));
280​
281 return GitWorkflowService.of({
282 isRepository: (cwd) =>
283 registry.detect({ cwd }).pipe(
284 Effect.map((handle) => handle?.kind === "git"),
285 Effect.mapError(
286 (cause) =>
287 new GitManagerError({
288 operation: "GitWorkflowService.isRepository",
289 cwd,
290 detail: "Failed to detect a VCS repository for this Git workflow.",
291 cause,
292 }),
293 ),
294 ),
295 hasCommit: (input) =>
296 ensureGitCommand("GitWorkflowService.hasCommit", input.cwd).pipe(
297 Effect.andThen(
298 git.execute({
299 operation: "GitWorkflowService.hasCommit",
300 cwd: input.cwd,
301 args: ["rev-parse", "--verify", `${input.refName}^{commit}`],
302 allowNonZeroExit: true,
303 }),
304 ),
305 Effect.map((result) => result.exitCode === 0),
306 ),
307 hasRefNamed: (input) =>
308 // No ref name holds a pattern character, and one here would widen the match.
309 /[*?[\\]/.test(input.refName)
310 ? Effect.succeed(false)
311 : ensureGitCommand("GitWorkflowService.hasRefNamed", input.cwd).pipe(
312 Effect.andThen(
313 git.execute({
314 operation: "GitWorkflowService.hasRefNamed",
315 cwd: input.cwd,
316 args: [
317 "for-each-ref",
318 "--count=1",
319 "--format=%(refname)",
320 `refs/**/${input.refName}`,
321 ],
322 }),
323 ),
324 Effect.map((result) => result.stdout.trim().length > 0),
325 ),
326 status: (input) =>
327 detectGitRepositoryForStatus("GitWorkflowService.status", input.cwd).pipe(
328 Effect.flatMap((isGitRepository) =>
329 isGitRepository ? gitManager.status(input) : Effect.succeed(nonRepositoryStatus()),
330 ),
331 ),
332 localStatus: (input) =>
333 detectGitRepositoryForStatus("GitWorkflowService.localStatus", input.cwd).pipe(
334 Effect.flatMap((isGitRepository) =>
335 isGitRepository
336 ? gitManager.localStatus(input)
337 : Effect.succeed(nonRepositoryLocalStatus()),
338 ),
339 ),
340 remoteStatus: (input, options) =>
341 detectGitRepositoryForStatus("GitWorkflowService.remoteStatus", input.cwd).pipe(
342 Effect.flatMap((isGitRepository) =>
343 isGitRepository ? gitManager.remoteStatus(input, options) : Effect.succeed(null),
344 ),
345 ),
346 invalidateLocalStatus: gitManager.invalidateLocalStatus,
347 invalidateRemoteStatus: gitManager.invalidateRemoteStatus,
348 invalidateStatus: gitManager.invalidateStatus,
349 pullCurrentBranch: (cwd) =>
350 ensureGitCommand("GitWorkflowService.pullCurrentBranch", cwd).pipe(
351 Effect.andThen(git.pullCurrentBranch(cwd)),
352 ),
353 runStackedAction: (input, options) =>
354 ensureGit("GitWorkflowService.runStackedAction", input.cwd).pipe(
355 Effect.andThen(gitManager.runStackedAction(input, options)),
356 ),
357 resolvePullRequest: routeGitManager(
358 "GitWorkflowService.resolvePullRequest",
359 gitManager.resolvePullRequest,
360 ),
361 preparePullRequestThread: routeGitManager(
362 "GitWorkflowService.preparePullRequestThread",
363 gitManager.preparePullRequestThread,
364 ),
365 listRefs: (input) =>
366 detectGitRepositoryForCommand("GitWorkflowService.listRefs", input.cwd).pipe(
367 Effect.flatMap((isGitRepository) =>
368 isGitRepository ? git.listRefs(input) : Effect.succeed(nonRepositoryListRefs()),
369 ),
370 ),
371 createWorktree: (input, options) =>
372 ensureGitCommand("GitWorkflowService.createWorktree", input.cwd).pipe(
373 Effect.andThen(gitManager.createWorktree(input, options)),
374 ),
375 listLocalBranchNames: (cwd) =>
376 ensureGitCommand("GitWorkflowService.listLocalBranchNames", cwd).pipe(
377 Effect.andThen(git.listLocalBranchNames(cwd)),
378 ),
379 fetchRemote: (input) =>
380 ensureGitCommand("GitWorkflowService.fetchRemote", input.cwd).pipe(
381 Effect.andThen(git.fetchRemote(input)),
382 ),
383 remoteExists: (input) =>
384 ensureGitCommand("GitWorkflowService.remoteExists", input.cwd).pipe(
385 Effect.andThen(git.remoteExists(input)),
386 ),
387 remoteBranchExists: (input) =>
388 ensureGitCommand("GitWorkflowService.remoteBranchExists", input.cwd).pipe(
389 Effect.andThen(git.remoteBranchExists(input)),
390 ),
391 resolveRemoteTrackingCommit: (input) =>
392 ensureGitCommand("GitWorkflowService.resolveRemoteTrackingCommit", input.cwd).pipe(
393 Effect.andThen(git.resolveRemoteTrackingCommit(input)),
394 ),
395 removeWorktree: (input) =>
396 ensureGitCommand("GitWorkflowService.removeWorktree", input.cwd).pipe(
397 Effect.andThen(git.removeWorktree(input)),
398 ),
399 pruneWorktrees: (input) =>
400 ensureGitCommand("GitWorkflowService.pruneWorktrees", input.cwd).pipe(
401 Effect.andThen(git.pruneWorktrees(input)),
402 ),
403 deleteLocalBranch: (input) =>
404 ensureGitCommand("GitWorkflowService.deleteLocalBranch", input.cwd).pipe(
405 Effect.andThen(git.deleteLocalBranch(input)),
406 ),
407 createRef: (input) =>
408 ensureGitCommand("GitWorkflowService.createRef", input.cwd).pipe(
409 Effect.andThen(git.createRef(input)),
410 ),
411 switchRef: (input) =>
412 ensureGitCommand("GitWorkflowService.switchRef", input.cwd).pipe(
413 Effect.andThen(Effect.scoped(git.switchRef(input))),
414 ),
415 renameBranch: (input) =>
416 ensureGit("GitWorkflowService.renameBranch", input.cwd).pipe(
417 Effect.andThen(git.renameBranch(input)),
418 ),
419 });
420});
421​
422export const layer = Layer.effect(GitWorkflowService, make);