@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

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