import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as FileSystem from "effect/FileSystem"; import { GitManagerError, GitCommandError, type VcsSwitchRefInput, type VcsSwitchRefResult, type VcsCreateRefInput, type VcsCreateRefResult, type VcsCreateWorktreeInput, type VcsCreateWorktreeResult, type VcsListRefsInput, type VcsListRefsResult, type GitManagerServiceError, type GitPreparePullRequestThreadInput, type GitPreparePullRequestThreadResult, type GitPullRequestRefInput, type VcsPullResult, type VcsRemoveWorktreeInput, type GitResolvePullRequestResult, type GitRunStackedActionInput, type GitRunStackedActionResult, type VcsStatusInput, type VcsStatusLocalResult, type VcsStatusRemoteResult, type VcsStatusResult, } from "@t3tools/contracts"; import * as GitManager from "./GitManager.ts"; import * as GitVcsDriver from "../vcs/GitVcsDriver.ts"; import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts"; import { withWorkspaceLease } from "../workspace/workspaceLease.ts"; export class GitWorkflowService extends Context.Service< GitWorkflowService, { readonly repositoryRoot: (cwd: string) => Effect.Effect; readonly hasCommit: (input: { readonly cwd: string; readonly refName: string; }) => Effect.Effect; readonly hasRefNamed: (input: { readonly cwd: string; readonly refName: string; }) => Effect.Effect; readonly status: ( input: VcsStatusInput, ) => Effect.Effect; readonly localStatus: ( input: VcsStatusInput, ) => Effect.Effect; readonly currentBranch: (cwd: string) => Effect.Effect; readonly upstreamDivergence: (cwd: string) => Effect.Effect< { readonly refName: string; readonly aheadCount: number; readonly behindCount: number; } | null, GitManagerServiceError >; readonly remoteStatus: ( input: VcsStatusInput, options?: GitManager.GitRemoteStatusOptions, ) => Effect.Effect; readonly invalidateLocalStatus: (cwd: string) => Effect.Effect; readonly invalidateRemoteStatus: (cwd: string) => Effect.Effect; readonly readRefSnapshot: (cwd: string) => Effect.Effect; readonly invalidateStatus: (cwd: string) => Effect.Effect; /** The checkout's own HEAD file, inside a linked worktree's admin directory when there is one. */ readonly headPath: (cwd: string) => Effect.Effect; readonly pullCurrentBranch: (cwd: string) => Effect.Effect; readonly runStackedAction: ( input: GitRunStackedActionInput, options?: GitManager.GitRunStackedActionOptions, ) => Effect.Effect; readonly resolvePullRequest: ( input: GitPullRequestRefInput, ) => Effect.Effect; readonly preparePullRequestThread: ( input: GitPreparePullRequestThreadInput, ) => Effect.Effect; readonly listRefs: ( input: VcsListRefsInput, ) => Effect.Effect; readonly createWorktree: ( input: VcsCreateWorktreeInput, options?: GitVcsDriver.CreateWorktreeOptions, ) => Effect.Effect; readonly listLocalBranchNames: (cwd: string) => Effect.Effect; readonly fetchRemote: (input: { readonly cwd: string; readonly remoteName: string; readonly refName?: string; }) => Effect.Effect; readonly remoteExists: (input: { readonly cwd: string; readonly remoteName: string; }) => Effect.Effect; readonly remoteBranchExists: (input: { readonly cwd: string; readonly remoteName: string; readonly refName: string; }) => Effect.Effect; readonly resolvePrimaryRemoteName: (cwd: string) => Effect.Effect; readonly resolveRemoteTrackingCommit: (input: { readonly cwd: string; readonly refName: string; readonly fallbackRemoteName: string; }) => Effect.Effect< { readonly commitSha: string; readonly remoteRefName: string }, GitCommandError >; readonly resolveWorktreeBaseRemote: GitVcsDriver.GitVcsDriver["Service"]["resolveWorktreeBaseRemote"]; readonly fetchWorktreeBaseCommit: (input: { readonly cwd: string; readonly refName: string; readonly remote?: GitVcsDriver.GitWorktreeBaseRemote; }) => Effect.Effect< { readonly commitSha: string; readonly remoteRefName: string } | null, GitCommandError >; readonly resolveDefaultBranchName: ( cwd: string, remoteName: string, ) => Effect.Effect; readonly removeWorktree: ( input: VcsRemoveWorktreeInput, ) => Effect.Effect; readonly pruneWorktrees: (input: { readonly cwd: string; }) => Effect.Effect; readonly deleteLocalBranch: ( input: GitVcsDriver.GitDeleteLocalBranchInput, ) => Effect.Effect; readonly createRef: ( input: VcsCreateRefInput, ) => Effect.Effect; readonly switchRef: ( input: VcsSwitchRefInput, ) => Effect.Effect; readonly renameBranch: (input: { readonly exactName?: boolean; readonly cwd: string; readonly oldBranch: string; readonly newBranch: string; }) => Effect.Effect<{ readonly branch: string }, GitManagerServiceError>; } >()("t3/git/GitWorkflowService") {} function nonRepositoryLocalStatus(): VcsStatusLocalResult { return { isRepo: false, hasPrimaryRemote: false, isDefaultRef: false, refName: null, hasWorkingTreeChanges: false, workingTree: { files: [], insertions: 0, deletions: 0, }, }; } function nonRepositoryStatus(): VcsStatusResult { return { ...nonRepositoryLocalStatus(), hasUpstream: false, aheadCount: 0, behindCount: 0, aheadOfDefaultCount: 0, pr: null, }; } function nonRepositoryListRefs(): VcsListRefsResult { return { refs: [], isRepo: false, hasPrimaryRemote: false, nextCursor: null, totalCount: 0, }; } /** @public */ export const make = Effect.gen(function* () { const registry = yield* VcsDriverRegistry.VcsDriverRegistry; const git = yield* GitVcsDriver.GitVcsDriver; const gitManager = yield* GitManager.GitManager; const fileSystem = yield* FileSystem.FileSystem; // Nested projects and path aliases must share the checkout's branch-mutation lease. const withCheckoutLease = (rootPath: string, effect: Effect.Effect) => fileSystem.realPath(rootPath).pipe( Effect.orElseSucceed(() => rootPath), Effect.flatMap((cwd) => withWorkspaceLease(cwd, effect)), ); const ensureGit = Effect.fn("GitWorkflowService.ensureGit")(function* ( operation: string, cwd: string, ) { const handle = yield* registry.resolve({ cwd }).pipe( Effect.mapError( (cause) => new GitManagerError({ operation, cwd, detail: "Failed to resolve the VCS driver for this Git workflow.", cause, }), ), ); return handle; }); const ensureGitCommand = Effect.fn("GitWorkflowService.ensureGitCommand")(function* ( operation: string, cwd: string, ) { const handle = yield* registry.resolve({ cwd }).pipe( Effect.mapError( (cause) => new GitCommandError({ operation, command: "vcs-route", cwd, detail: "Failed to resolve the VCS driver for this Git command.", cause, }), ), ); return handle; }); const detectGitRepositoryForStatus = Effect.fn("GitWorkflowService.detectGitRepositoryForStatus")( function* (operation: string, cwd: string) { const handle = yield* registry.detect({ cwd }).pipe( Effect.mapError( (cause) => new GitManagerError({ operation, cwd, detail: "Failed to detect a VCS repository for this Git workflow.", cause, }), ), ); if (!handle) { return false; } return true; }, ); const detectGitRepositoryForCommand = Effect.fn( "GitWorkflowService.detectGitRepositoryForCommand", )(function* (operation: string, cwd: string) { const handle = yield* registry.detect({ cwd }).pipe( Effect.mapError( (cause) => new GitCommandError({ operation, command: "vcs-route", cwd, detail: "Failed to detect a VCS repository for this Git command.", cause, }), ), ); if (!handle) { return false; } return true; }); const routeGitManager = ( operation: string, run: (input: Input) => Effect.Effect, ) => (input: Input) => ensureGit(operation, input.cwd).pipe(Effect.andThen(run(input))); return GitWorkflowService.of({ repositoryRoot: Effect.fn("GitWorkflowService.repositoryRoot")(function (cwd) { return registry.detect({ cwd }).pipe( Effect.map((handle) => (handle?.kind === "git" ? handle.repository.rootPath : null)), Effect.mapError( (cause) => new GitManagerError({ operation: "GitWorkflowService.repositoryRoot", cwd, detail: "Failed to detect a VCS repository for this Git workflow.", cause, }), ), ); }), hasCommit: Effect.fn("GitWorkflowService.hasCommit")(function (input) { return ensureGitCommand("GitWorkflowService.hasCommit", input.cwd).pipe( Effect.andThen( git.execute({ operation: "GitWorkflowService.hasCommit", cwd: input.cwd, args: ["rev-parse", "--verify", `${input.refName}^{commit}`], allowNonZeroExit: true, }), ), Effect.map((result) => result.exitCode === 0), ); }), hasRefNamed: Effect.fn("GitWorkflowService.hasRefNamed")(function (input) { // Pattern characters would widen the ref match. return /[*?[\\]/.test(input.refName) ? Effect.succeed(false) : ensureGitCommand("GitWorkflowService.hasRefNamed", input.cwd).pipe( Effect.andThen( git.execute({ operation: "GitWorkflowService.hasRefNamed", cwd: input.cwd, args: [ "for-each-ref", "--count=1", "--format=%(refname)", `refs/**/${input.refName}`, ], }), ), Effect.map((result) => result.stdout.trim().length > 0), ); }), status: Effect.fn("GitWorkflowService.status")(function (input) { return detectGitRepositoryForStatus("GitWorkflowService.status", input.cwd).pipe( Effect.flatMap((isGitRepository) => isGitRepository ? gitManager.status(input) : Effect.succeed(nonRepositoryStatus()), ), ); }), localStatus: Effect.fn("GitWorkflowService.localStatus")(function (input) { return detectGitRepositoryForStatus("GitWorkflowService.localStatus", input.cwd).pipe( Effect.flatMap((isGitRepository) => isGitRepository ? gitManager.localStatus(input) : Effect.succeed(nonRepositoryLocalStatus()), ), ); }), currentBranch: Effect.fn("GitWorkflowService.currentBranch")(function* (cwd) { if (!(yield* detectGitRepositoryForStatus("GitWorkflowService.currentBranch", cwd))) { return null; } const result = yield* git.execute({ operation: "GitWorkflowService.currentBranch", cwd, args: ["symbolic-ref", "--quiet", "HEAD"], allowNonZeroExit: true, timeoutMs: 5_000, }); if (result.exitCode === 0) { return result.stdout.trim().replace(/^refs\/heads\//, "") || null; } if (result.exitCode === 1) return null; return yield* new GitCommandError({ operation: "GitWorkflowService.currentBranch", command: "git symbolic-ref", cwd, argumentCount: 3, ...(result.exitCode === null ? {} : { exitCode: result.exitCode }), stdoutLength: result.stdout.length, stderrLength: result.stderr.length, detail: "Failed to read the checked-out branch.", }); }), upstreamDivergence: Effect.fn("GitWorkflowService.upstreamDivergence")(function* (cwd) { const details = yield* git.statusDetailsRemote(cwd, { refreshUpstream: false }); return details.hasUpstream && details.branch !== null ? { refName: details.branch, aheadCount: details.aheadCount, behindCount: details.behindCount, } : null; }), remoteStatus: Effect.fn("GitWorkflowService.remoteStatus")(function (input, options) { return detectGitRepositoryForStatus("GitWorkflowService.remoteStatus", input.cwd).pipe( Effect.flatMap((isGitRepository) => isGitRepository ? gitManager.remoteStatus(input, options) : Effect.succeed(null), ), ); }), invalidateLocalStatus: gitManager.invalidateLocalStatus, invalidateRemoteStatus: gitManager.invalidateRemoteStatus, readRefSnapshot: git.readRefSnapshot, invalidateStatus: gitManager.invalidateStatus, headPath: Effect.fn("GitWorkflowService.headPath")(function (cwd) { return git .execute({ operation: "GitWorkflowService.headPath", cwd, args: ["rev-parse", "--path-format=absolute", "--git-path", "HEAD"], allowNonZeroExit: true, }) .pipe( Effect.map((result) => (result.exitCode === 0 ? result.stdout.trim() || null : null)), Effect.orElseSucceed(() => null), ); }), pullCurrentBranch: Effect.fn("GitWorkflowService.pullCurrentBranch")(function (cwd) { return ensureGitCommand("GitWorkflowService.pullCurrentBranch", cwd).pipe( Effect.andThen(git.pullCurrentBranch(cwd)), ); }), runStackedAction: Effect.fn("GitWorkflowService.runStackedAction")(function (input, options) { return ensureGit("GitWorkflowService.runStackedAction", input.cwd).pipe( Effect.flatMap((handle) => withCheckoutLease( handle.repository.rootPath, gitManager.runStackedAction(input, options), ), ), ); }), resolvePullRequest: routeGitManager( "GitWorkflowService.resolvePullRequest", gitManager.resolvePullRequest, ), preparePullRequestThread: Effect.fn("GitWorkflowService.preparePullRequestThread")( function (input) { return ensureGit("GitWorkflowService.preparePullRequestThread", input.cwd).pipe( Effect.flatMap((handle) => input.mode === "local" ? withCheckoutLease( handle.repository.rootPath, gitManager.preparePullRequestThread(input), ) : gitManager.preparePullRequestThread(input), ), ); }, ), listRefs: Effect.fn("GitWorkflowService.listRefs")(function (input) { return detectGitRepositoryForCommand("GitWorkflowService.listRefs", input.cwd).pipe( Effect.flatMap((isGitRepository) => isGitRepository ? git.listRefs(input) : Effect.succeed(nonRepositoryListRefs()), ), ); }), createWorktree: Effect.fn("GitWorkflowService.createWorktree")(function (input, options) { return ensureGitCommand("GitWorkflowService.createWorktree", input.cwd).pipe( Effect.andThen(gitManager.createWorktree(input, options)), ); }), listLocalBranchNames: Effect.fn("GitWorkflowService.listLocalBranchNames")(function (cwd) { return ensureGitCommand("GitWorkflowService.listLocalBranchNames", cwd).pipe( Effect.andThen(git.listLocalBranchNames(cwd)), ); }), fetchRemote: Effect.fn("GitWorkflowService.fetchRemote")(function (input) { return ensureGitCommand("GitWorkflowService.fetchRemote", input.cwd).pipe( Effect.andThen(git.fetchRemote(input)), ); }), remoteExists: Effect.fn("GitWorkflowService.remoteExists")(function (input) { return ensureGitCommand("GitWorkflowService.remoteExists", input.cwd).pipe( Effect.andThen(git.remoteExists(input)), ); }), remoteBranchExists: Effect.fn("GitWorkflowService.remoteBranchExists")(function (input) { return ensureGitCommand("GitWorkflowService.remoteBranchExists", input.cwd).pipe( Effect.andThen(git.remoteBranchExists(input)), ); }), resolvePrimaryRemoteName: Effect.fn("GitWorkflowService.resolvePrimaryRemoteName")( function (cwd) { return ensureGitCommand("GitWorkflowService.resolvePrimaryRemoteName", cwd).pipe( Effect.andThen(git.resolvePrimaryRemoteName(cwd)), ); }, ), resolveRemoteTrackingCommit: Effect.fn("GitWorkflowService.resolveRemoteTrackingCommit")( function (input) { return ensureGitCommand("GitWorkflowService.resolveRemoteTrackingCommit", input.cwd).pipe( Effect.andThen(git.resolveRemoteTrackingCommit(input)), ); }, ), resolveWorktreeBaseRemote: Effect.fn("GitWorkflowService.resolveWorktreeBaseRemote")( function (input) { return ensureGitCommand("GitWorkflowService.resolveWorktreeBaseRemote", input.cwd).pipe( Effect.andThen(git.resolveWorktreeBaseRemote(input)), ); }, ), fetchWorktreeBaseCommit: Effect.fn("GitWorkflowService.fetchWorktreeBaseCommit")( function (input) { return ensureGitCommand("GitWorkflowService.fetchWorktreeBaseCommit", input.cwd).pipe( Effect.andThen(git.fetchWorktreeBaseCommit(input)), ); }, ), resolveDefaultBranchName: Effect.fn("GitWorkflowService.resolveDefaultBranchName")( function (cwd, remoteName) { return ensureGitCommand("GitWorkflowService.resolveDefaultBranchName", cwd).pipe( Effect.andThen(git.resolveDefaultBranchName(cwd, remoteName)), ); }, ), removeWorktree: Effect.fn("GitWorkflowService.removeWorktree")(function (input) { return ensureGitCommand("GitWorkflowService.removeWorktree", input.cwd).pipe( Effect.andThen(git.removeWorktree(input)), ); }), pruneWorktrees: Effect.fn("GitWorkflowService.pruneWorktrees")(function (input) { return ensureGitCommand("GitWorkflowService.pruneWorktrees", input.cwd).pipe( Effect.andThen(git.pruneWorktrees(input)), ); }), deleteLocalBranch: Effect.fn("GitWorkflowService.deleteLocalBranch")(function (input) { return ensureGitCommand("GitWorkflowService.deleteLocalBranch", input.cwd).pipe( Effect.andThen(git.deleteLocalBranch(input)), ); }), createRef: Effect.fn("GitWorkflowService.createRef")(function (input) { return ensureGitCommand("GitWorkflowService.createRef", input.cwd).pipe( Effect.flatMap((handle) => input.switchRef ? withCheckoutLease(handle.repository.rootPath, git.createRef(input)) : git.createRef(input), ), ); }), switchRef: Effect.fn("GitWorkflowService.switchRef")(function (input) { return ensureGitCommand("GitWorkflowService.switchRef", input.cwd).pipe( Effect.flatMap((handle) => withCheckoutLease(handle.repository.rootPath, Effect.scoped(git.switchRef(input))), ), ); }), renameBranch: Effect.fn("GitWorkflowService.renameBranch")(function (input) { return ensureGit("GitWorkflowService.renameBranch", input.cwd).pipe( Effect.andThen(git.renameBranch(input)), ); }), }); }); export const layer = Layer.effect(GitWorkflowService, make);