@n-seiji/nuthatch 0.1.5 → 0.2.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/README.ja.md CHANGED
@@ -40,8 +40,8 @@ hop -- <branch> # 予約コマンドと被る branch 名をエスケープ
40
40
  hop --help # usage を表示 (-h / hop help でも同じ)
41
41
 
42
42
  hop --version # hop の version を表示
43
- hop --update # 最新リリースへ、インストールした方法のまま更新
44
- hop --update --check # --update が何をするかを報告するだけ — 何も変更しない
43
+ hop --update # standalone バイナリを最新リリースへ置換 (それ以外は更新方法を表示)
44
+ hop --update --check # 更新があるかを報告するだけ — 何も変更しない
45
45
  ```
46
46
 
47
47
  同じ branch が複数の worktree で checkout されている場合、branch だけを指定する
@@ -92,7 +92,7 @@ action を選ぶ間も一覧が見え続ける。横に並べられない幅 (
92
92
  | `Tab`, `→`, `Ctrl+L`, `Ctrl+F` | 選択中の候補の action panel を開く (ここで cd / 削除 / root 切替) |
93
93
  | `Ctrl+X` | 選択中の worktree を削除 (常に先に y/N を確認) |
94
94
  | `Ctrl+R` | root clone を選択中の branch へ切替 (`external` は先に y/N を確認) |
95
- | `↑`/`↓`, `Ctrl+P`/`Ctrl+N`, `Ctrl+K`/`Ctrl+J` | 選択を移動 (矢印・emacs・vim キーがすべて併用可) |
95
+ | `↑`/`↓`, `Ctrl+P`/`Ctrl+N`, `Ctrl+K` | 選択を移動 (矢印・emacs・vim キーがすべて併用可) |
96
96
  | `Esc` | 静かにキャンセル — exit 0、stdout は空のまま (shell wrapper は cd しない) |
97
97
  | `Ctrl+C` | 割り込みとしてキャンセル — exit 130、実際の SIGINT と同じ |
98
98
 
@@ -145,27 +145,27 @@ install script は `hop` を `~/.local/bin` に置き (`HOP_INSTALL_DIR` で
145
145
  ### 更新
146
146
 
147
147
  ```sh
148
- hop --update # 最新リリースへ、インストールした方法のまま更新
149
- hop --update --check # 報告だけ: current / latest / method / 実行されるコマンド
148
+ hop --update # standalone バイナリを最新リリースへ置換
149
+ hop --update --check # 報告だけ: current / latest / インストール方法 / すべきこと
150
150
  hop --version # 今どの version か
151
151
  ```
152
152
 
153
- `hop --update` は hop のインストール方法を判定する。`install.sh` で入れた
154
- バイナリは、置き場のディレクトリに書き込めて (バイナリと checksum の
155
- ダウンロードの前に確認する)、かつリリースに添付された `.sha256` と SHA-256 が
156
- 一致した場合にだけその場で差し替える — 不一致なら何も置換しない。
157
- mise / npm / bun 経由の install は、そのツール自身の upgrade コマンド
158
- (`mise upgrade …`、
159
- `npm install -g --prefix <hop が入っている prefix> @n-seiji/nuthatch@latest`、
160
- `bun add -g @n-seiji/nuthatch@latest`) をホームディレクトリで実行して更新する
161
- ので、グローバルの mise 設定で固定した version が優先され (hop は先に mise へ
162
- 問い合わせ、upgrade するものが無ければ警告する)、プロジェクトの `mise.toml`
163
- には左右されず、npm の更新は hop が今入っている prefix に入る。`npx` / `bunx`、
164
- ソースチェックアウト、Homebrew・Nix・aqua・proto など他のバージョン管理ツール
165
- が自分用にコピーを持っているバイナリ、hop が扱わない配置 (pnpm・yarn の
166
- global、プロジェクトの依存) は、代わりにどうすればよいかを示して拒否する。
167
- hop がネットワークに出るのはこれだけで、GitHub と npm の固定アドレスへの
168
- HTTPS リクエストのみ (タイムアウトとサイズ上限つき)。
153
+ `hop --update` が置換するのは `install.sh` で入れたバイナリだけで、置き場の
154
+ ディレクトリに書き込めて (バイナリと checksum のダウンロードの前に確認する)、
155
+ かつリリースに添付された `.sha256` と SHA-256 が一致した場合に限る — 不一致なら
156
+ 何も置換しない。それ以外のインストールでは、何も実行せず、リクエストも送らず、
157
+ 更新方法を 1 行表示して終了する (exit 1):
158
+
159
+ | インストール方法 | 更新方法 |
160
+ |---|---|
161
+ | `install.sh` (`~/.local/bin` のバイナリ) | `hop --update`、または `install.sh` を再実行 |
162
+ | mise | `mise upgrade` |
163
+ | npm / bun / pnpm / yarn の global | `npm i -g @n-seiji/nuthatch@latest` (または使っているパッケージマネージャの同等コマンド) |
164
+ | Homebrew・Nix・aqua・proto・ソースチェックアウト・その他のツール | そのツール自身の upgrade コマンド |
165
+
166
+ `hop --update --check` はどのインストール方法でも使え、同じ案内を報告する。
167
+ hop がネットワークに出るのは GitHub の固定アドレスへの HTTPS リクエストだけで、
168
+ タイムアウトとサイズ上限つき。
169
169
 
170
170
  ## トラブルシューティング
171
171
 
package/README.md CHANGED
@@ -42,8 +42,8 @@ hop -- <branch> # escape a branch name that collides with a reserved command
42
42
  hop --help # print usage (also -h / hop help)
43
43
 
44
44
  hop --version # print hop's version
45
- hop --update # update hop to the latest release, the way it was installed
46
- hop --update --check # only report what --update would do — changes nothing
45
+ hop --update # replace a standalone binary with the latest release (other installs: prints how to update)
46
+ hop --update --check # only report whether an update is available — changes nothing
47
47
  ```
48
48
 
49
49
  If Git reports the same branch checked out in multiple worktrees, the
@@ -100,7 +100,7 @@ below the list instead.
100
100
  | `Tab`, `→`, `Ctrl+L`, `Ctrl+F` | Open the action panel for the selected candidate (cd / delete / switch root here) |
101
101
  | `Ctrl+X` | Delete the selected worktree (always asks y/N first) |
102
102
  | `Ctrl+R` | Switch the root clone to the selected branch (asks y/N first for an `external` worktree) |
103
- | `↑`/`↓`, `Ctrl+P`/`Ctrl+N`, `Ctrl+K`/`Ctrl+J` | Move the selection (arrow, emacs, and vim keys all work side by side) |
103
+ | `↑`/`↓`, `Ctrl+P`/`Ctrl+N`, `Ctrl+K` | Move the selection (arrow, emacs, and vim keys all work side by side) |
104
104
  | `Esc` | Cancel quietly — exit 0, stdout stays empty (the shell wrapper just doesn't cd) |
105
105
  | `Ctrl+C` | Cancel like an interrupt — exit 130, same as a real SIGINT |
106
106
 
@@ -151,27 +151,27 @@ binary yet — use the npm install instead.
151
151
  ### Updating
152
152
 
153
153
  ```sh
154
- hop --update # update to the latest release, the way hop was installed
155
- hop --update --check # just report: current, latest, method, and the command it would run
154
+ hop --update # replace a standalone binary with the latest release
155
+ hop --update --check # just report: current, latest, how hop was installed, what to do
156
156
  hop --version # which version do I have?
157
157
  ```
158
158
 
159
- `hop --update` detects how hop was installed. A binary from `install.sh` is
160
- replaced in place, but only if its directory is writable (checked before the
161
- binary or its checksum is downloaded) and only after its SHA-256 matches the
162
- `.sha256` attached to the release — on a mismatch nothing is replaced. A mise /
163
- npm / bun install is updated by running that tool's own upgrade command from
164
- your home directory (`mise upgrade …`,
165
- `npm install -g --prefix <the prefix hop lives in> @n-seiji/nuthatch@latest`,
166
- `bun add -g @n-seiji/nuthatch@latest`), so a version pinned in your global mise
167
- config still wins (hop asks mise first and warns when it has nothing to
168
- upgrade), a project's own `mise.toml` cannot interfere, and an npm update lands
169
- in the prefix hop is already in. `npx` / `bunx`, a source checkout, a binary
170
- that Homebrew, Nix, aqua, proto or another version manager keeps its own copy
171
- of, and layouts hop does not drive (a pnpm or yarn global, a project
172
- dependency) are refused with a note on what to do instead. This is the only
173
- thing hop does over the network: HTTPS requests to fixed GitHub and npm
174
- addresses, each with a timeout and a size cap.
159
+ `hop --update` only replaces the binary that `install.sh` installs, and only if
160
+ its directory is writable (checked before the binary or its checksum is
161
+ downloaded) and its SHA-256 matches the `.sha256` attached to the release; on a
162
+ mismatch nothing is replaced. For any other install it runs nothing, makes no
163
+ request, and prints one line saying how to update it (exit 1):
164
+
165
+ | Installed with | Update with |
166
+ |---|---|
167
+ | `install.sh` (binary in `~/.local/bin`) | `hop --update`, or re-run `install.sh` |
168
+ | mise | `mise upgrade` |
169
+ | npm / bun / pnpm / yarn global | `npm i -g @n-seiji/nuthatch@latest` (or your package manager's equivalent) |
170
+ | Homebrew, Nix, aqua, proto, a source checkout, any other tool | that tool's own upgrade command |
171
+
172
+ `hop --update --check` works for every install and reports the same hint. The
173
+ only network traffic is HTTPS requests to fixed GitHub addresses, each with a
174
+ timeout and a size cap.
175
175
 
176
176
  ## Troubleshooting
177
177
 
@@ -0,0 +1,207 @@
1
+ import {
2
+ messageOf
3
+ } from "./cli-ph0gp56k.js";
4
+ import {
5
+ upstreamStateOf
6
+ } from "./cli-btqjpf1q.js";
7
+ import {
8
+ withRepoLock
9
+ } from "./cli-wcnyhk4w.js";
10
+ import {
11
+ loadRepoContext,
12
+ nestedWorktrees,
13
+ worktreeDirtyState
14
+ } from "./cli-fqz7emfm.js";
15
+ import {
16
+ EXIT_USAGE_ERROR,
17
+ ok,
18
+ fail
19
+ } from "./cli-77yanq37.js";
20
+
21
+ // src/domain/garbage.ts
22
+ var classifyGarbage = (input) => {
23
+ if (input.prunable) {
24
+ return "prunable";
25
+ }
26
+ if (!input.clean) {
27
+ return null;
28
+ }
29
+ if (input.mergedIntoDefault === true) {
30
+ return "merged";
31
+ }
32
+ if (input.upstreamGone && input.allCommitsReachableFromDefault === true) {
33
+ return "gone";
34
+ }
35
+ return null;
36
+ };
37
+
38
+ // src/commands/clean-candidates.ts
39
+ var buildCleanCandidates = async (git, fs, context, ext) => {
40
+ const [defaultRef, upstreams] = await Promise.all([
41
+ git.resolveDefaultBranchRef(context.rootPath),
42
+ git.upstreamStates(context.rootPath)
43
+ ]);
44
+ const targets = context.worktrees.filter((wt) => wt.kind === "managed" || ext && wt.kind === "external");
45
+ const results = await Promise.all(targets.map(async (wt) => {
46
+ const reason = await classifyWorktree(wt, { git, fs, defaultRef, upstreams, context });
47
+ if (reason === null) {
48
+ return null;
49
+ }
50
+ return { branch: wt.branch ?? "", path: wt.path, reason };
51
+ }));
52
+ return results.filter((candidate) => candidate !== null);
53
+ };
54
+ var branchMergeFacts = async (git, rootPath, branch, { defaultRef, upstreams }) => {
55
+ const upstreamGone = upstreamStateOf(upstreams, branch).kind === "gone";
56
+ const mergedIntoDefault = defaultRef === null ? "unknown" : await git.isAncestor(rootPath, branch, defaultRef);
57
+ const allCommitsReachableFromDefault = defaultRef === null || mergedIntoDefault === true || !upstreamGone ? "unknown" : await git.hasEquivalentCommits(rootPath, branch, defaultRef);
58
+ return {
59
+ prunable: false,
60
+ upstreamGone,
61
+ mergedIntoDefault,
62
+ allCommitsReachableFromDefault
63
+ };
64
+ };
65
+ var classifyWorktree = async (wt, { git, fs, defaultRef, upstreams, context }) => {
66
+ if (wt.prunable) {
67
+ return classifyGarbage({
68
+ prunable: true,
69
+ clean: false,
70
+ mergedIntoDefault: "unknown",
71
+ upstreamGone: false,
72
+ allCommitsReachableFromDefault: "unknown"
73
+ });
74
+ }
75
+ if (wt.branch === null) {
76
+ return null;
77
+ }
78
+ const { rootPath, worktrees } = context;
79
+ const facts = await branchMergeFacts(git, rootPath, wt.branch, { defaultRef, upstreams });
80
+ if (classifyGarbage({ ...facts, clean: true }) === null) {
81
+ return null;
82
+ }
83
+ const dirtyState = await worktreeDirtyState(git, fs, worktrees, wt);
84
+ const input = { ...facts, clean: dirtyState === false };
85
+ return classifyGarbage(input);
86
+ };
87
+
88
+ // src/commands/clean.ts
89
+ var clean = async (git, fs, term, options) => {
90
+ const context = await loadRepoContext(git, fs, options.cwd);
91
+ const candidates = await buildCleanCandidates(git, fs, context, options.ext);
92
+ if (options.dryRun) {
93
+ return ok({ data: { candidates } });
94
+ }
95
+ if (candidates.length === 0) {
96
+ return ok({ data: { candidates, removed: [] } });
97
+ }
98
+ if (!options.yes) {
99
+ if (!term.isTTY()) {
100
+ return fail(EXIT_USAGE_ERROR, "hop clean would remove worktrees; re-run with --yes (non-interactive) or --dry-run to only list candidates.");
101
+ }
102
+ for (const candidate of candidates) {
103
+ term.logStderr(`${candidate.reason} ${candidate.branch} ${candidate.path}`);
104
+ }
105
+ const confirmed = await term.confirm(`Remove ${candidates.length} worktree(s) above?`);
106
+ if (!confirmed) {
107
+ return ok({ data: { candidates, removed: [] } });
108
+ }
109
+ }
110
+ return executeClean({
111
+ git,
112
+ fs,
113
+ context,
114
+ candidates,
115
+ cleanOptions: options
116
+ });
117
+ };
118
+ var removeCandidate = async ({
119
+ git,
120
+ rootPath,
121
+ candidate,
122
+ deleteBranch,
123
+ worktrees
124
+ }) => {
125
+ if (nestedWorktrees(worktrees, candidate.path).length > 0) {
126
+ return "nested";
127
+ }
128
+ try {
129
+ await git.removeWorktree(rootPath, candidate.path, false);
130
+ if (deleteBranch && candidate.branch.length > 0) {
131
+ await git.deleteBranch(rootPath, candidate.branch);
132
+ }
133
+ return "removed";
134
+ } catch {
135
+ return "failed";
136
+ }
137
+ };
138
+ var canDeletePrunableBranch = async (git, rootPath, candidate, facts) => {
139
+ if (candidate.reason !== "prunable") {
140
+ return true;
141
+ }
142
+ if (candidate.branch.length === 0) {
143
+ return false;
144
+ }
145
+ try {
146
+ const branchFacts = await branchMergeFacts(git, rootPath, candidate.branch, facts);
147
+ return classifyGarbage({ ...branchFacts, clean: true }) !== null;
148
+ } catch {
149
+ return false;
150
+ }
151
+ };
152
+ var executeClean = ({
153
+ git,
154
+ fs,
155
+ context,
156
+ candidates,
157
+ cleanOptions
158
+ }) => withRepoLock(context.commonDir, async () => {
159
+ try {
160
+ const fresh = await loadRepoContext(git, fs, context.rootPath);
161
+ const freshCandidates = await buildCleanCandidates(git, fs, fresh, cleanOptions.ext);
162
+ const freshByPath = new Map(freshCandidates.map((candidate) => [candidate.path, candidate]));
163
+ const stillValid = candidates.flatMap((candidate) => {
164
+ const freshCandidate = freshByPath.get(candidate.path);
165
+ return freshCandidate === undefined ? [] : [freshCandidate];
166
+ });
167
+ const [defaultRef, upstreams] = await Promise.all([
168
+ git.resolveDefaultBranchRef(fresh.rootPath),
169
+ git.upstreamStates(fresh.rootPath)
170
+ ]);
171
+ const removed = [];
172
+ const warnings = [];
173
+ for (const candidate of stillValid) {
174
+ const branchSafe = await canDeletePrunableBranch(git, fresh.rootPath, candidate, {
175
+ defaultRef,
176
+ upstreams
177
+ });
178
+ const deleteBranch = cleanOptions.withBranch && branchSafe;
179
+ if (cleanOptions.withBranch && candidate.reason === "prunable" && candidate.branch.length > 0 && !branchSafe) {
180
+ warnings.push(`Keeping branch "${candidate.branch}": prunable worktree is not confirmed merged or gone.`);
181
+ }
182
+ const outcome = await removeCandidate({
183
+ git,
184
+ rootPath: fresh.rootPath,
185
+ candidate,
186
+ deleteBranch,
187
+ worktrees: fresh.worktrees
188
+ });
189
+ if (outcome === "removed") {
190
+ removed.push(candidate.branch);
191
+ } else if (outcome === "nested") {
192
+ warnings.push(`Skipped ${candidate.path}: still contains a registered worktree.`);
193
+ }
194
+ }
195
+ return ok({
196
+ data: { candidates: [...candidates], removed },
197
+ ...warnings.length === 0 ? {} : { warnings }
198
+ });
199
+ } catch (error) {
200
+ throw new Error(`Failed to clean worktrees: ${messageOf(error)}`, {
201
+ cause: error
202
+ });
203
+ }
204
+ });
205
+ export {
206
+ clean
207
+ };
@@ -0,0 +1,30 @@
1
+ // src/infra/term.ts
2
+ import { createInterface } from "node:readline";
3
+ var colorEnabled = (stream) => stream.isTTY === true && (process.env["NO_COLOR"] ?? "") === "";
4
+ var createTermPort = () => ({
5
+ isTTY() {
6
+ return process.stderr.isTTY === true && process.stdin.isTTY === true;
7
+ },
8
+ logStderr(message) {
9
+ process.stderr.write(`${message}
10
+ `);
11
+ },
12
+ confirm(message) {
13
+ return new Promise((resolve) => {
14
+ const rl = createInterface({
15
+ input: process.stdin,
16
+ output: process.stderr,
17
+ terminal: false
18
+ });
19
+ rl.question(`${message} [y/N] `, (answer) => {
20
+ rl.close();
21
+ resolve(answer.trim().toLowerCase() === "y");
22
+ });
23
+ rl.once("close", () => {
24
+ resolve(false);
25
+ });
26
+ });
27
+ }
28
+ });
29
+
30
+ export { colorEnabled, createTermPort };
@@ -0,0 +1,21 @@
1
+ // src/domain/result.ts
2
+ var EXIT_SUCCESS = 0;
3
+ var EXIT_GENERAL_ERROR = 1;
4
+ var EXIT_USAGE_ERROR = 2;
5
+ var EXIT_SAFE_REJECTION = 3;
6
+ var EXIT_CANCELLED = 130;
7
+ var ok = (fields = {}) => ({
8
+ ok: true,
9
+ exitCode: EXIT_SUCCESS,
10
+ ...fields
11
+ });
12
+ var fail = (exitCode, errorMessage, warnings) => ({
13
+ ok: false,
14
+ exitCode,
15
+ errorMessage,
16
+ ...warnings === undefined || warnings.length === 0 ? {} : { warnings }
17
+ });
18
+ var pass = (value) => ({ ok: true, value });
19
+ var reject = (rejection) => ({ ok: false, rejection });
20
+
21
+ export { EXIT_SUCCESS, EXIT_GENERAL_ERROR, EXIT_USAGE_ERROR, EXIT_SAFE_REJECTION, EXIT_CANCELLED, ok, fail, pass, reject };
@@ -0,0 +1,187 @@
1
+ import {
2
+ messageOf
3
+ } from "./cli-ph0gp56k.js";
4
+ import {
5
+ withRepoLock
6
+ } from "./cli-wcnyhk4w.js";
7
+ import {
8
+ loadRepoContext,
9
+ isWorktreeDirty,
10
+ resolveBranchCheckout
11
+ } from "./cli-fqz7emfm.js";
12
+ import {
13
+ EXIT_SAFE_REJECTION,
14
+ ok,
15
+ fail,
16
+ pass,
17
+ reject
18
+ } from "./cli-77yanq37.js";
19
+
20
+ // src/commands/root-holder-swap.ts
21
+ var holderRejection = (branch, holderPath, reason) => fail(EXIT_SAFE_REJECTION, `Branch "${branch}" is already checked out at ${holderPath}, and it ${reason}. Not swapping — cd there instead of using hop root.`);
22
+ var prunableHolderRejection = (branch, holderPath) => fail(EXIT_SAFE_REJECTION, `Branch "${branch}" is held by a stale worktree registration at ${holderPath} (git reports it prunable). Not swapping — if that worktree was moved, re-link it with "git worktree repair <new path>"; otherwise drop the registration first ("hop rm ${branch}" or "git worktree prune").`);
23
+ var multipleHoldersRejection = (branch, holders) => fail(EXIT_SAFE_REJECTION, `Branch "${branch}" is checked out at ${holders.length} worktrees at once (${holders.map((holder) => holder.path).join(", ")}). Not swapping — hop won't guess which one to detach.`);
24
+ var resolveHolderSwap = async ({
25
+ git,
26
+ fresh,
27
+ target,
28
+ switchOptions,
29
+ policy
30
+ }) => {
31
+ if (target === "-") {
32
+ return pass(null);
33
+ }
34
+ const freshHolders = fresh.worktrees.filter((wt) => wt.branch === target && wt.kind !== "root");
35
+ if (freshHolders.length > 1) {
36
+ return reject(multipleHoldersRejection(target, freshHolders));
37
+ }
38
+ const [freshHolder] = freshHolders;
39
+ if (freshHolder === undefined) {
40
+ return pass(null);
41
+ }
42
+ if (policy.expectedPath !== undefined && freshHolder.path !== policy.expectedPath) {
43
+ return reject(holderRejection(target, freshHolder.path, `changed from the picker selection at ${policy.expectedPath}`));
44
+ }
45
+ if (freshHolder.kind === "external" && !policy.allowExternal) {
46
+ return reject(holderRejection(target, freshHolder.path, "is external and requires confirmation before it can be put into detached HEAD"));
47
+ }
48
+ if (switchOptions.createBranch === true) {
49
+ return reject(holderRejection(target, freshHolder.path, "wasn't visible when hop checked existing local branches (e.g. it has no commits yet, or was created after that check)"));
50
+ }
51
+ if (freshHolder.locked) {
52
+ return reject(holderRejection(target, freshHolder.path, `is locked by git${freshHolder.lockReason === null ? "" : ` (${freshHolder.lockReason})`}`));
53
+ }
54
+ if (freshHolder.prunable) {
55
+ return reject(prunableHolderRejection(target, freshHolder.path));
56
+ }
57
+ const holderDirty = await isWorktreeDirty(git, fresh.worktrees, freshHolder.path);
58
+ if (holderDirty) {
59
+ return reject(holderRejection(target, freshHolder.path, "has uncommitted or untracked changes"));
60
+ }
61
+ await git.detachHead(freshHolder.path);
62
+ return pass({ path: freshHolder.path, branch: target });
63
+ };
64
+
65
+ // src/commands/root.ts
66
+ var root2 = async (git, fs, options) => {
67
+ const context = await loadRepoContext(git, fs, options.cwd);
68
+ if (options.target === undefined) {
69
+ return ok({
70
+ path: context.rootPath,
71
+ data: {
72
+ branch: rootBranchOf(context),
73
+ switched: false,
74
+ detachedHolder: null
75
+ }
76
+ });
77
+ }
78
+ const dirtyRejection = await dirtyRootRejection(git, context);
79
+ if (dirtyRejection !== null) {
80
+ return dirtyRejection;
81
+ }
82
+ if (options.target === "-") {
83
+ return switchAndReport({
84
+ git,
85
+ fs,
86
+ context,
87
+ target: "-",
88
+ switchOptions: {},
89
+ holderPolicy: { allowExternal: true }
90
+ });
91
+ }
92
+ const checkout = await resolveBranchCheckout(git, context.rootPath, options.target, options.track);
93
+ if (!checkout.ok) {
94
+ return checkout.rejection;
95
+ }
96
+ return switchAndReport({
97
+ git,
98
+ fs,
99
+ context,
100
+ target: options.target,
101
+ switchOptions: checkout.value,
102
+ holderPolicy: {
103
+ allowExternal: options.allowExternalHolderSwap ?? true,
104
+ ...options.expectedHolderPath === undefined ? {} : { expectedPath: options.expectedHolderPath }
105
+ }
106
+ });
107
+ };
108
+ var rootBranchOf = ({ worktrees }) => worktrees.find((wt) => wt.kind === "root")?.branch ?? null;
109
+ var dirtyRootRejection = async (git, context) => {
110
+ const dirty = await isWorktreeDirty(git, context.worktrees, context.rootPath);
111
+ if (!dirty) {
112
+ return null;
113
+ }
114
+ return fail(EXIT_SAFE_REJECTION, "Root clone has uncommitted or untracked changes. Commit, stash, or discard them before switching.");
115
+ };
116
+ var rollBackSwitch = async (git, { rootPath, previousBranch, detachedHolder }) => {
117
+ const warnings = [];
118
+ if (previousBranch !== null) {
119
+ try {
120
+ await git.switchBranch(rootPath, previousBranch, {});
121
+ } catch {
122
+ warnings.push(`Could not restore ${rootPath} to its original branch (${previousBranch})`);
123
+ }
124
+ }
125
+ if (detachedHolder !== null) {
126
+ try {
127
+ await git.switchBranch(detachedHolder.path, detachedHolder.branch, {});
128
+ } catch {
129
+ warnings.push(`Could not restore ${detachedHolder.path} to its original branch (${detachedHolder.branch}); it remains in detached HEAD`);
130
+ }
131
+ }
132
+ return warnings;
133
+ };
134
+ var switchAndReport = ({
135
+ git,
136
+ fs,
137
+ context,
138
+ target,
139
+ switchOptions,
140
+ holderPolicy
141
+ }) => withRepoLock(context.commonDir, async () => {
142
+ let detachedHolder = null;
143
+ let previousBranch = null;
144
+ try {
145
+ const fresh = await loadRepoContext(git, fs, context.rootPath);
146
+ previousBranch = rootBranchOf(fresh);
147
+ const stillDirty = await dirtyRootRejection(git, fresh);
148
+ if (stillDirty !== null) {
149
+ return stillDirty;
150
+ }
151
+ const holderSwap = await resolveHolderSwap({
152
+ git,
153
+ fresh,
154
+ target,
155
+ switchOptions,
156
+ policy: holderPolicy
157
+ });
158
+ if (!holderSwap.ok) {
159
+ return holderSwap.rejection;
160
+ }
161
+ detachedHolder = holderSwap.value;
162
+ await git.switchBranch(fresh.rootPath, target, switchOptions);
163
+ let resolvedBranch = target;
164
+ if (target === "-") {
165
+ const afterSwitch = await loadRepoContext(git, fs, fresh.rootPath);
166
+ resolvedBranch = rootBranchOf(afterSwitch);
167
+ }
168
+ return ok({
169
+ path: fresh.rootPath,
170
+ data: {
171
+ branch: resolvedBranch,
172
+ switched: true,
173
+ detachedHolder: detachedHolder?.path ?? null
174
+ },
175
+ warnings: detachedHolder === null ? [] : [`Put ${detachedHolder.path} into detached HEAD`]
176
+ });
177
+ } catch (error) {
178
+ const warnings = await rollBackSwitch(git, {
179
+ rootPath: context.rootPath,
180
+ previousBranch,
181
+ detachedHolder
182
+ });
183
+ return fail(EXIT_SAFE_REJECTION, `Failed to switch root: ${messageOf(error)}`, warnings);
184
+ }
185
+ });
186
+
187
+ export { root2 };
@@ -0,0 +1,20 @@
1
+ // src/domain/classify.ts
2
+ var isWithin = (parent, child) => {
3
+ if (parent === child) {
4
+ return false;
5
+ }
6
+ const parentWithSlash = parent.endsWith("/") ? parent : `${parent}/`;
7
+ return child.startsWith(parentWithSlash);
8
+ };
9
+ var isWithinOrSelf = (parent, child) => parent === child || isWithin(parent, child);
10
+ var classifyWorktreePath = (path, rootPath, managedRoot) => {
11
+ if (path === rootPath) {
12
+ return "root";
13
+ }
14
+ if (path === managedRoot || isWithin(managedRoot, path)) {
15
+ return "managed";
16
+ }
17
+ return "external";
18
+ };
19
+
20
+ export { isWithin, isWithinOrSelf, classifyWorktreePath };