(input: {
sourcePath: string;
baseRef?: string;
config: ServerConfig;
})
| 34 | } |
| 35 | |
| 36 | export async function createManagedWorktree(input: { |
| 37 | sourcePath: string; |
| 38 | baseRef?: string; |
| 39 | config: ServerConfig; |
| 40 | }): Promise<ManagedWorktree> { |
| 41 | const sourcePath = assertAllowedPath(input.sourcePath, input.config.allowedRoots); |
| 42 | |
| 43 | try { |
| 44 | const sourceStats = await stat(sourcePath); |
| 45 | if (!sourceStats.isDirectory()) { |
| 46 | throw new GitWorktreeError( |
| 47 | "GIT_REPOSITORY_NOT_FOUND", |
| 48 | `Cannot open workspace in worktree mode because the source path is not a directory: ${input.sourcePath}`, |
| 49 | ); |
| 50 | } |
| 51 | } catch (error) { |
| 52 | if (error instanceof GitWorktreeError) throw error; |
| 53 | throw new GitWorktreeError( |
| 54 | "GIT_REPOSITORY_NOT_FOUND", |
| 55 | `Cannot open workspace in worktree mode because the source path does not exist: ${input.sourcePath}`, |
| 56 | ); |
| 57 | } |
| 58 | |
| 59 | const sourceRoot = await resolveGitRoot(sourcePath, input.config.allowedRoots); |
| 60 | const baseRef = input.baseRef ?? "HEAD"; |
| 61 | const baseSha = await resolveBaseCommit(sourceRoot, baseRef); |
| 62 | const dirtySource = (await git(["status", "--porcelain=v1"], sourceRoot)).trim().length > 0; |
| 63 | const worktreePath = managedWorktreePath({ |
| 64 | worktreeRoot: input.config.worktreeRoot, |
| 65 | repoRoot: sourceRoot, |
| 66 | }); |
| 67 | |
| 68 | await mkdir(input.config.worktreeRoot, { recursive: true }); |
| 69 | assertAllowedPath(worktreePath, [input.config.worktreeRoot]); |
| 70 | |
| 71 | try { |
| 72 | await git(["worktree", "add", "--detach", worktreePath, baseSha], sourceRoot); |
| 73 | } catch (error) { |
| 74 | await rm(worktreePath, { recursive: true, force: true }); |
| 75 | const message = error instanceof Error ? error.message : String(error); |
| 76 | throw new GitWorktreeError( |
| 77 | "GIT_WORKTREE_CREATE_FAILED", |
| 78 | `Git failed to create the managed worktree. ${message}`, |
| 79 | ); |
| 80 | } |
| 81 | |
| 82 | return { |
| 83 | sourceRoot, |
| 84 | path: worktreePath, |
| 85 | baseRef, |
| 86 | baseSha, |
| 87 | dirtySource, |
| 88 | detached: true, |
| 89 | managed: true, |
| 90 | }; |
| 91 | } |
| 92 | |
| 93 | async function resolveGitRoot(path: string, allowedRoots: string[]): Promise<string> { |
no test coverage detected