@autosk/worktree 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +75 -0
- package/index.ts +10 -0
- package/package.json +41 -0
- package/src/index.ts +308 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 wierdbytes
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
# @autosk/worktree
|
|
2
|
+
|
|
3
|
+
The shipped **isolation provider** for autoskd v2: per-task **git worktree**
|
|
4
|
+
isolation, attachable to any workflow. It ports v1's worktree behaviour onto
|
|
5
|
+
the v2 [`IsolationProvider`](../../sdk/src/workflow.ts) contract (design
|
|
6
|
+
`docs/plans/20260612-Bun-Daemon-Extensions.md` §3.5).
|
|
7
|
+
|
|
8
|
+
## Usage
|
|
9
|
+
|
|
10
|
+
```ts
|
|
11
|
+
import { statusStep } from "@autosk/sdk";
|
|
12
|
+
import { piAgent } from "@autosk/pi-agent";
|
|
13
|
+
import { worktreeIsolation } from "@autosk/worktree";
|
|
14
|
+
|
|
15
|
+
autosk.registerWorkflow({
|
|
16
|
+
name: "feature-dev",
|
|
17
|
+
firstStep: "dev",
|
|
18
|
+
// Agents are inline step values (the step key is the agent name).
|
|
19
|
+
steps: { dev: piAgent({ firstMessageFile: ".../dev.md" }), accept: statusStep("human") },
|
|
20
|
+
isolation: worktreeIsolation(),
|
|
21
|
+
});
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
Each isolated task runs in its own checkout so concurrent tasks never collide on
|
|
25
|
+
the working tree. The engine calls `acquire` before scheduling a session (its
|
|
26
|
+
returned `cwd` becomes `ctx.cwd`) and `release` on every transition.
|
|
27
|
+
|
|
28
|
+
## Behaviour
|
|
29
|
+
|
|
30
|
+
Deterministic mapping — **byte-identical to v1**, so a worktree allocated by
|
|
31
|
+
either stack resolves to the same place:
|
|
32
|
+
|
|
33
|
+
```text
|
|
34
|
+
~/.autosk/worktrees/<basename(canonRoot)>-<8hex(sha256(canonRoot))>/<task-id>
|
|
35
|
+
branch = autosk/<task-id>
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
- **acquire** — allocates the per-task worktree on branch `autosk/<task-id>`
|
|
39
|
+
(off `HEAD`), or re-uses it when a prior step kept it. A **missing** dir is
|
|
40
|
+
re-allocated on the *existing* branch (v1 "missing worktree auto-recovery").
|
|
41
|
+
Returns `{ cwd, meta: { branch, projectRoot } }`.
|
|
42
|
+
- **release(`{terminal:true}`)** (done / cancel) — removes the worktree dir but
|
|
43
|
+
**preserves** the `autosk/<task-id>` branch (so the work survives for review /
|
|
44
|
+
merge).
|
|
45
|
+
- **release(`{terminal:false}`)** (sibling step / human-park) — keeps the dir so
|
|
46
|
+
the next step re-uses the same checkout.
|
|
47
|
+
|
|
48
|
+
### Failure handling
|
|
49
|
+
|
|
50
|
+
The provider **only throws descriptive messages** — the engine wraps them
|
|
51
|
+
(`isolation_acquire_failed: …` on acquire, `isolation_release_failed: …` on a
|
|
52
|
+
happy-path release) and parks the task to `human`. It never parks or formats
|
|
53
|
+
those prefixes itself. Throw cases:
|
|
54
|
+
|
|
55
|
+
- **non-git root** — `not a git repository: <root>` (the project root isn't a
|
|
56
|
+
git repo).
|
|
57
|
+
- **stranded dir** — `worktree_stranded: …` (a directory sits at the worktree
|
|
58
|
+
path whose gitdir doesn't resolve to the project's — e.g. a foreign repo).
|
|
59
|
+
- **git missing** — `git binary not found on PATH`.
|
|
60
|
+
|
|
61
|
+
## Configuration
|
|
62
|
+
|
|
63
|
+
`worktreeIsolation(options?)`:
|
|
64
|
+
|
|
65
|
+
| Option | Default | Description |
|
|
66
|
+
| -------- | ------------------ | --------------------------------------------------------------------------- |
|
|
67
|
+
| `home` | `process.env.HOME` | Home dir the worktree tree lives under (`<home>/.autosk/worktrees/…`). Tests inject a temp home. |
|
|
68
|
+
| `gitBin` | `"git"` | `git` binary to shell out to. |
|
|
69
|
+
|
|
70
|
+
## Exports
|
|
71
|
+
|
|
72
|
+
- `worktreeIsolation(options?)` → `IsolationProvider`
|
|
73
|
+
- `branchFor(taskId)`, `pathFor(projectRoot, taskId, home?)`, `slugFor(canon)` —
|
|
74
|
+
the deterministic derivation helpers (exported for tooling / tests).
|
|
75
|
+
- `WORKTREE_TAG` — the provider tag (`"worktree"`) rendered by `workflow.get`.
|
package/index.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
// Root entry re-export.
|
|
2
|
+
//
|
|
3
|
+
// The compiled `autoskd` (`bun build --compile`) resolves an on-disk
|
|
4
|
+
// extension's bare `@autosk/*` imports with a minimal resolver that only honors
|
|
5
|
+
// a ROOT-LEVEL `index.ts`/`index.js` — it ignores `package.json` `exports` /
|
|
6
|
+
// `main` and any subdir target. So this package keeps its sources under `src/`
|
|
7
|
+
// but exposes a root `index.ts` the standalone daemon can find. (Interpreted
|
|
8
|
+
// Bun honors `exports` directly; this shim is what makes the published package
|
|
9
|
+
// loadable by the compiled binary.)
|
|
10
|
+
export * from "./src/index.ts";
|
package/package.json
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@autosk/worktree",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Shipped autoskd v2 isolation provider: per-task git worktree isolation (worktreeIsolation()) attachable to any workflow.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"author": "wierdbytes",
|
|
7
|
+
"homepage": "https://github.com/wierdbytes/autosk#readme",
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "git+https://github.com/wierdbytes/autosk.git",
|
|
11
|
+
"directory": "daemon/extensions/worktree"
|
|
12
|
+
},
|
|
13
|
+
"bugs": {
|
|
14
|
+
"url": "https://github.com/wierdbytes/autosk/issues"
|
|
15
|
+
},
|
|
16
|
+
"keywords": [
|
|
17
|
+
"autosk",
|
|
18
|
+
"autosk-extension",
|
|
19
|
+
"git-worktree",
|
|
20
|
+
"isolation"
|
|
21
|
+
],
|
|
22
|
+
"type": "module",
|
|
23
|
+
"publishConfig": {
|
|
24
|
+
"access": "public"
|
|
25
|
+
},
|
|
26
|
+
"exports": {
|
|
27
|
+
".": "./index.ts"
|
|
28
|
+
},
|
|
29
|
+
"types": "./index.ts",
|
|
30
|
+
"files": [
|
|
31
|
+
"index.ts",
|
|
32
|
+
"src/",
|
|
33
|
+
"README.md"
|
|
34
|
+
],
|
|
35
|
+
"dependencies": {
|
|
36
|
+
"@autosk/sdk": "^0.1.0"
|
|
37
|
+
},
|
|
38
|
+
"scripts": {
|
|
39
|
+
"typecheck": "tsc --noEmit -p tsconfig.json"
|
|
40
|
+
}
|
|
41
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,308 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@autosk/worktree` — the shipped `worktreeIsolation()` provider (plan §3.5).
|
|
3
|
+
*
|
|
4
|
+
* Ports v1's per-task git worktree isolation onto the v2
|
|
5
|
+
* {@link IsolationProvider} contract. The
|
|
6
|
+
* engine (`daemon/core/src/engine/session.ts`) calls `acquire` before scheduling
|
|
7
|
+
* an isolated session and `release` on every transition; FAILURES ARE WRAPPED BY
|
|
8
|
+
* THE ENGINE (`acquire` throw → `isolation_acquire_failed: <msg>`, happy-path
|
|
9
|
+
* `release` throw → `isolation_release_failed: <msg>`), so this provider just
|
|
10
|
+
* throws descriptive messages — it never parks or formats those prefixes itself.
|
|
11
|
+
*
|
|
12
|
+
* Deterministic mapping (byte-identical to the v1 Go/Rust slug so a worktree
|
|
13
|
+
* allocated by either stack resolves to the same place):
|
|
14
|
+
*
|
|
15
|
+
* ```text
|
|
16
|
+
* ~/.autosk/worktrees/<basename(canonRoot)>-<8hex(sha256(canonRoot))>/<task-id>
|
|
17
|
+
* branch = autosk/<task-id>
|
|
18
|
+
* ```
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
import { createHash } from "node:crypto";
|
|
22
|
+
import { mkdirSync, realpathSync, rmSync, statSync } from "node:fs";
|
|
23
|
+
import { basename, dirname, isAbsolute, join, resolve } from "node:path";
|
|
24
|
+
|
|
25
|
+
import type { IsolationHandle, IsolationProvider } from "@autosk/sdk";
|
|
26
|
+
|
|
27
|
+
/** Options for {@link worktreeIsolation}. */
|
|
28
|
+
export interface WorktreeIsolationOptions {
|
|
29
|
+
/**
|
|
30
|
+
* Home directory the worktree tree lives under (`<home>/.autosk/worktrees/…`).
|
|
31
|
+
* Defaults to `process.env.HOME`. Injected by tests so they never touch the
|
|
32
|
+
* operator's real `~/.autosk/`.
|
|
33
|
+
*/
|
|
34
|
+
home?: string;
|
|
35
|
+
/** `git` binary to shell out to. Defaults to `"git"`. */
|
|
36
|
+
gitBin?: string;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** The provider tag the registry/`workflow.get` renders for an isolated workflow. */
|
|
40
|
+
export const WORKTREE_TAG = "worktree";
|
|
41
|
+
|
|
42
|
+
/** Provider-internal bookkeeping carried on every {@link IsolationHandle}. */
|
|
43
|
+
interface WorktreeMeta extends Record<string, unknown> {
|
|
44
|
+
branch: string;
|
|
45
|
+
/** The canonical project root — `release` needs it to drive `git -C <root>`. */
|
|
46
|
+
projectRoot: string;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Builds the shipped worktree {@link IsolationProvider}. Attach it to a workflow
|
|
51
|
+
* via `isolation: worktreeIsolation()` (plan §3.6). `acquire` allocates (or
|
|
52
|
+
* re-uses / re-allocates) the per-task worktree and hands the engine its path as
|
|
53
|
+
* `ctx.cwd`; `release({terminal:true})` removes the dir but PRESERVES the
|
|
54
|
+
* `autosk/<task>` branch, `release({terminal:false})` keeps the dir so the next
|
|
55
|
+
* sibling step re-uses it.
|
|
56
|
+
*/
|
|
57
|
+
export function worktreeIsolation(opts: WorktreeIsolationOptions = {}): IsolationProvider {
|
|
58
|
+
const gitBin = opts.gitBin ?? "git";
|
|
59
|
+
|
|
60
|
+
return {
|
|
61
|
+
tag: WORKTREE_TAG,
|
|
62
|
+
|
|
63
|
+
async acquire({ projectRoot, taskId }): Promise<IsolationHandle> {
|
|
64
|
+
const canon = canonRoot(projectRoot);
|
|
65
|
+
const path = pathFor(canon, taskId, opts.home);
|
|
66
|
+
const branch = branchFor(taskId);
|
|
67
|
+
const meta: WorktreeMeta = { branch, projectRoot: canon };
|
|
68
|
+
|
|
69
|
+
await ensureGitAvailable(gitBin);
|
|
70
|
+
|
|
71
|
+
if (existsPath(path)) {
|
|
72
|
+
// Present already (a prior step kept it, or an external pre-existing dir):
|
|
73
|
+
// verify it is a healthy worktree OF THIS repo, else it is stranded.
|
|
74
|
+
await verifyHealthy(gitBin, canon, path);
|
|
75
|
+
return { cwd: path, meta };
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// Missing dir → (re)allocate on the existing branch (v1 "missing worktree
|
|
79
|
+
// auto-recovery"). A stale registration whose dir was rm'd out from under
|
|
80
|
+
// git is cleared by `worktree prune` (and a force-remove fallback) before
|
|
81
|
+
// the add, so the dir is genuinely recreated rather than reported existing.
|
|
82
|
+
await ensureGitRepo(gitBin, canon);
|
|
83
|
+
await pruneWorktrees(gitBin, canon);
|
|
84
|
+
if (await worktreeRegisteredAt(gitBin, canon, path)) {
|
|
85
|
+
await runGit(gitBin, canon, ["worktree", "remove", "--force", path]);
|
|
86
|
+
}
|
|
87
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
88
|
+
if (await branchExists(gitBin, canon, branch)) {
|
|
89
|
+
const r = await runGit(gitBin, canon, ["worktree", "add", path, branch]);
|
|
90
|
+
if (r.code !== 0) throw new Error(`worktree add (existing branch ${branch}): ${gitErr(r)}`);
|
|
91
|
+
} else {
|
|
92
|
+
const r = await runGit(gitBin, canon, ["worktree", "add", path, "-b", branch]);
|
|
93
|
+
if (r.code !== 0) throw new Error(`worktree add (new branch ${branch}): ${gitErr(r)}`);
|
|
94
|
+
}
|
|
95
|
+
return { cwd: path, meta };
|
|
96
|
+
},
|
|
97
|
+
|
|
98
|
+
async release(handle, { terminal }): Promise<void> {
|
|
99
|
+
// Non-terminal (sibling step / human-park): keep the dir so the next step
|
|
100
|
+
// re-uses the same checkout. Nothing to do.
|
|
101
|
+
if (!terminal) return;
|
|
102
|
+
const meta = (handle.meta ?? {}) as Partial<WorktreeMeta>;
|
|
103
|
+
const path = handle.cwd;
|
|
104
|
+
const canon = meta.projectRoot ? canonRoot(meta.projectRoot) : "";
|
|
105
|
+
await ensureGitAvailable(gitBin);
|
|
106
|
+
await onTerminal(gitBin, canon, path);
|
|
107
|
+
},
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// ---------------------------------------------------------------------------
|
|
112
|
+
// Deterministic path / branch derivation (byte-identical to v1).
|
|
113
|
+
// ---------------------------------------------------------------------------
|
|
114
|
+
|
|
115
|
+
/** Canonical branch name `autosk/<taskID>`. */
|
|
116
|
+
export function branchFor(taskId: string): string {
|
|
117
|
+
return `autosk/${taskId}`;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Absolute on-disk path for the `(projectRoot, taskID)` pair — the v1
|
|
122
|
+
* `PathFor`. `projectRoot` is canonicalised (symlinks resolved, lexically
|
|
123
|
+
* cleaned) so every caller computes the same slug.
|
|
124
|
+
*/
|
|
125
|
+
export function pathFor(projectRoot: string, taskId: string, home?: string): string {
|
|
126
|
+
if (projectRoot.trim() === "") throw new Error("project root is empty");
|
|
127
|
+
if (taskId.trim() === "") throw new Error("task id is empty");
|
|
128
|
+
const h = home ?? process.env.HOME ?? "";
|
|
129
|
+
if (h === "") throw new Error("user home dir not set");
|
|
130
|
+
const canon = canonRoot(projectRoot);
|
|
131
|
+
return join(h, ".autosk", "worktrees", slugFor(canon), taskId);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** `basename(canon) + "-" + 8hex(sha256(canon))` — the v1 `slugFor`. */
|
|
135
|
+
export function slugFor(canon: string): string {
|
|
136
|
+
const base = basename(canon);
|
|
137
|
+
const digest = createHash("sha256").update(canon, "utf8").digest();
|
|
138
|
+
const hex8 = digest.subarray(0, 4).toString("hex");
|
|
139
|
+
return `${base}-${hex8}`;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** Symlink-resolved, absolutised project root (v1 `canonRoot`). */
|
|
143
|
+
function canonRoot(projectRoot: string): string {
|
|
144
|
+
const abs = resolve(projectRoot);
|
|
145
|
+
try {
|
|
146
|
+
return realpathSync(abs);
|
|
147
|
+
} catch {
|
|
148
|
+
return abs; // lexical-clean fallback when the path can't be canonicalised
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// ---------------------------------------------------------------------------
|
|
153
|
+
// git verbs.
|
|
154
|
+
// ---------------------------------------------------------------------------
|
|
155
|
+
|
|
156
|
+
/** Verifies the worktree at `path` is a healthy checkout of the repo at `canon`. */
|
|
157
|
+
async function verifyHealthy(gitBin: string, canon: string, path: string): Promise<void> {
|
|
158
|
+
let wtGitdir: string;
|
|
159
|
+
try {
|
|
160
|
+
wtGitdir = await gitCommonDir(gitBin, path);
|
|
161
|
+
} catch (e) {
|
|
162
|
+
throw new Error(`worktree_stranded: ${path}: ${errMsg(e)}`);
|
|
163
|
+
}
|
|
164
|
+
let projGitdir: string;
|
|
165
|
+
try {
|
|
166
|
+
projGitdir = await gitCommonDir(gitBin, canon);
|
|
167
|
+
} catch (e) {
|
|
168
|
+
throw new Error(`not a git repository: ${canon}: ${errMsg(e)}`);
|
|
169
|
+
}
|
|
170
|
+
if (!sameDir(wtGitdir, projGitdir)) {
|
|
171
|
+
throw new Error(`worktree_stranded: worktree gitdir=${wtGitdir}, project gitdir=${projGitdir}`);
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** Removes the worktree dir on a terminal transition while PRESERVING its branch. */
|
|
176
|
+
async function onTerminal(gitBin: string, canon: string, path: string): Promise<void> {
|
|
177
|
+
// git itself broken / no project root → still try to reap the on-disk dir.
|
|
178
|
+
if (canon === "" || !(await isGitRepo(gitBin, canon))) {
|
|
179
|
+
if (existsPath(path)) rmSync(path, { recursive: true, force: true });
|
|
180
|
+
return;
|
|
181
|
+
}
|
|
182
|
+
if (await worktreeRegisteredAt(gitBin, canon, path)) {
|
|
183
|
+
const r = await runGit(gitBin, canon, ["worktree", "remove", "--force", path]);
|
|
184
|
+
if (r.code !== 0) throw new Error(`worktree remove ${path}: ${gitErr(r)}`);
|
|
185
|
+
return;
|
|
186
|
+
}
|
|
187
|
+
if (existsPath(path)) rmSync(path, { recursive: true, force: true });
|
|
188
|
+
await runGit(gitBin, canon, ["worktree", "prune"]); // best-effort
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** Throws a descriptive `not a git repository` error if `canon` is not a repo. */
|
|
192
|
+
async function ensureGitRepo(gitBin: string, canon: string): Promise<void> {
|
|
193
|
+
if (!(await isGitRepo(gitBin, canon))) {
|
|
194
|
+
throw new Error(`not a git repository: ${canon}`);
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
async function isGitRepo(gitBin: string, canon: string): Promise<boolean> {
|
|
199
|
+
const r = await runGit(gitBin, canon, ["rev-parse", "--git-dir"]);
|
|
200
|
+
return r.code === 0;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
async function branchExists(gitBin: string, canon: string, branch: string): Promise<boolean> {
|
|
204
|
+
const r = await runGit(gitBin, canon, ["show-ref", "--verify", "--quiet", `refs/heads/${branch}`]);
|
|
205
|
+
if (r.code === 0) return true;
|
|
206
|
+
if (r.code === 1) return false;
|
|
207
|
+
throw new Error(`show-ref ${branch}: ${gitErr(r)}`);
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
async function worktreeRegisteredAt(gitBin: string, canon: string, target: string): Promise<boolean> {
|
|
211
|
+
const r = await runGit(gitBin, canon, ["worktree", "list", "--porcelain"]);
|
|
212
|
+
if (r.code !== 0) throw new Error(`worktree list: ${gitErr(r)}`);
|
|
213
|
+
const canonTarget = canonRoot(target);
|
|
214
|
+
for (const raw of r.stdout.split("\n")) {
|
|
215
|
+
const line = raw.trim();
|
|
216
|
+
if (line.startsWith("worktree ")) {
|
|
217
|
+
const p = line.slice("worktree ".length).trim();
|
|
218
|
+
if (sameDir(p, target) || sameDir(p, canonTarget)) return true;
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
return false;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
async function pruneWorktrees(gitBin: string, canon: string): Promise<void> {
|
|
225
|
+
await runGit(gitBin, canon, ["worktree", "prune"]); // best-effort
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/** `git -C cwd rev-parse --git-common-dir`, absolutised + canonicalised. */
|
|
229
|
+
async function gitCommonDir(gitBin: string, cwd: string): Promise<string> {
|
|
230
|
+
const r = await runGit(gitBin, cwd, ["rev-parse", "--git-common-dir"]);
|
|
231
|
+
if (r.code !== 0) throw new Error(`rev-parse --git-common-dir: ${gitErr(r)}`);
|
|
232
|
+
const out = r.stdout.trim();
|
|
233
|
+
if (out === "") throw new Error("rev-parse --git-common-dir: empty output");
|
|
234
|
+
const abs = isAbsolute(out) ? out : join(cwd, out);
|
|
235
|
+
try {
|
|
236
|
+
return realpathSync(abs);
|
|
237
|
+
} catch {
|
|
238
|
+
return resolve(abs);
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/**
|
|
243
|
+
* Caches a SUCCESSFUL `<gitBin> --version` per binary (a failure is re-checked,
|
|
244
|
+
* never cached). Keyed by `gitBin` so a second provider built with a different
|
|
245
|
+
* binary is validated independently instead of short-circuiting on the first.
|
|
246
|
+
*/
|
|
247
|
+
const gitAvailableByBin = new Map<string, boolean>();
|
|
248
|
+
async function ensureGitAvailable(gitBin: string): Promise<void> {
|
|
249
|
+
if (gitAvailableByBin.get(gitBin) === true) return;
|
|
250
|
+
let ok = false;
|
|
251
|
+
try {
|
|
252
|
+
const proc = Bun.spawn([gitBin, "--version"], { stdout: "ignore", stderr: "ignore", stdin: "ignore" });
|
|
253
|
+
ok = (await proc.exited) === 0;
|
|
254
|
+
} catch {
|
|
255
|
+
ok = false;
|
|
256
|
+
}
|
|
257
|
+
if (ok) gitAvailableByBin.set(gitBin, true);
|
|
258
|
+
else throw new Error(`git binary not found on PATH (${gitBin})`);
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
interface GitResult {
|
|
262
|
+
code: number | null;
|
|
263
|
+
stdout: string;
|
|
264
|
+
stderr: string;
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/** Runs `git -C <cwd> <args...>`, capturing stdout/stderr/exit code. */
|
|
268
|
+
async function runGit(gitBin: string, cwd: string, args: string[]): Promise<GitResult> {
|
|
269
|
+
const proc = Bun.spawn([gitBin, "-C", cwd, ...args], {
|
|
270
|
+
stdin: "ignore",
|
|
271
|
+
stdout: "pipe",
|
|
272
|
+
stderr: "pipe",
|
|
273
|
+
});
|
|
274
|
+
const [stdout, stderr, code] = await Promise.all([
|
|
275
|
+
new Response(proc.stdout).text(),
|
|
276
|
+
new Response(proc.stderr).text(),
|
|
277
|
+
proc.exited,
|
|
278
|
+
]);
|
|
279
|
+
return { code, stdout, stderr };
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
function gitErr(r: GitResult): string {
|
|
283
|
+
const msg = `${r.stdout}${r.stderr}`.trim();
|
|
284
|
+
return msg === "" ? `exit ${r.code}` : msg;
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
// ---------------------------------------------------------------------------
|
|
288
|
+
// small helpers.
|
|
289
|
+
// ---------------------------------------------------------------------------
|
|
290
|
+
|
|
291
|
+
function existsPath(p: string): boolean {
|
|
292
|
+
// statSync follows symlinks (matches v1's os.Stat): a dangling symlink reads
|
|
293
|
+
// as absent, not occupied.
|
|
294
|
+
try {
|
|
295
|
+
statSync(p);
|
|
296
|
+
return true;
|
|
297
|
+
} catch {
|
|
298
|
+
return false;
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
function sameDir(a: string, b: string): boolean {
|
|
303
|
+
return resolve(a) === resolve(b);
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
function errMsg(e: unknown): string {
|
|
307
|
+
return e instanceof Error ? e.message : String(e);
|
|
308
|
+
}
|