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

GitWorkflowService.ts

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