@narumitw/pi-worktree 0.27.1 → 0.28.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.md +37 -7
- package/package.json +2 -2
- package/src/command.ts +42 -6
- package/src/git.ts +6 -5
- package/src/index.ts +1 -0
- package/src/settings.ts +291 -0
- package/src/worktree.ts +25 -2
package/README.md
CHANGED
|
@@ -11,7 +11,7 @@ Pi cannot change its parent process working directory with `cd`. This extension
|
|
|
11
11
|
- Shows compact main, linked, current, detached, locked, and prunable state in worktree selectors.
|
|
12
12
|
- Creates a new branch worktree or attaches an existing unoccupied local branch.
|
|
13
13
|
- Rejects occupied targets and unresolvable symbolic-link ancestors before Git can create a branch.
|
|
14
|
-
- Suggests
|
|
14
|
+
- Suggests `~/.worktrees/<main-worktree-name>/<branch>` by default and lets the user configure the root interactively.
|
|
15
15
|
- Optionally switches Pi into a newly created worktree while continuing the current conversation.
|
|
16
16
|
- Switches among existing registered worktrees through Pi's public session replacement API.
|
|
17
17
|
- Removes unlocked, non-current linked worktrees and preserves their branches.
|
|
@@ -54,25 +54,51 @@ Choose one action:
|
|
|
54
54
|
- **Switch worktree** — select another existing worktree and continue this Pi conversation there.
|
|
55
55
|
- **Remove worktree** — remove a linked worktree without deleting its branch; ignored-only data is listed for explicit confirmation.
|
|
56
56
|
- **Prune stale metadata** — inspect Git's dry-run output, then optionally run the matching prune.
|
|
57
|
+
- **Configure worktree root** — set a machine-local default root or submit a blank value to restore `~/.worktrees`.
|
|
57
58
|
|
|
58
|
-
`/worktree` intentionally does not accept text subcommands
|
|
59
|
+
The menu title shows the effective worktree root and whether it comes from the built-in default or the user settings file. `/worktree` intentionally does not accept text subcommands or expose argument autocomplete. Every change is initiated and confirmed through the interactive UI.
|
|
59
60
|
|
|
60
61
|
## 🌿 Add defaults
|
|
61
62
|
|
|
62
63
|
For a new branch, the current symbolic branch is the default start point. If Pi is running from detached HEAD, the command requires an explicit commit-ish. Git must resolve the start point to exactly one commit.
|
|
63
64
|
|
|
64
|
-
The
|
|
65
|
+
The default root is `~/.worktrees`, where `~` is Node's platform home directory. Suggestions use the registered main worktree's directory name, not the current linked-worktree cwd:
|
|
65
66
|
|
|
66
67
|
```text
|
|
67
68
|
main worktree: /home/user/workspace/project
|
|
68
69
|
branch: feat/login
|
|
69
|
-
|
|
70
|
+
root: /home/user/.worktrees
|
|
71
|
+
suggested: /home/user/.worktrees/project/feat-login
|
|
70
72
|
```
|
|
71
73
|
|
|
72
|
-
|
|
74
|
+
On Windows, the equivalent default is such as `C:\Users\Alice\.worktrees`. Branch `/` characters become `-`. The extension does not add hashes or collision suffixes: if two normalized paths collide or the target already exists, Add stops before Git mutation.
|
|
75
|
+
|
|
76
|
+
Leave the path input blank to accept the suggestion. A custom absolute path is used directly; a custom relative path is resolved from the current Pi cwd. The target itself must not exist, and its nearest existing ancestor must resolve without a broken or looping symbolic link. Existing registered worktrees are never moved when this default changes.
|
|
73
77
|
|
|
74
78
|
The MVP does not expose `--force`, `-B`, `--detach`, `--orphan`, or lock options.
|
|
75
79
|
|
|
80
|
+
## ⚙️ Worktree root settings
|
|
81
|
+
|
|
82
|
+
The machine-local user settings file is:
|
|
83
|
+
|
|
84
|
+
```text
|
|
85
|
+
<getAgentDir()>/pi-worktree.json
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
For a default Pi installation this is typically `~/.pi/agent/pi-worktree.json`. Configure it through **Configure worktree root** or edit it manually:
|
|
89
|
+
|
|
90
|
+
```json
|
|
91
|
+
{
|
|
92
|
+
"worktreeRoot": "~/worktrees"
|
|
93
|
+
}
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
`worktreeRoot` accepts `~`, a home-prefixed path such as `~/worktrees`, or a native-platform absolute path. It does not expand `$VAR`, `%VAR%`, or other shell syntax. Empty, relative, NUL-containing, non-string, and invalid paths are rejected. There is no project override or extension-specific environment variable.
|
|
97
|
+
|
|
98
|
+
A missing `worktreeRoot` uses `~/.worktrees`. Submitting a blank value in the interactive action removes the override. Unknown JSON fields survive interactive saves and resets. Settings reload on every `session_start`, including `/reload` and workspace replacement; a successful interactive save applies immediately to the next Add flow.
|
|
99
|
+
|
|
100
|
+
Malformed or invalid settings are warned about but never overwritten. An initial failure uses `~/.worktrees`; a later failure retains the last valid effective root. Interactive configuration remains blocked until the invalid file is fixed manually.
|
|
101
|
+
|
|
76
102
|
## 🔀 Pi workspace switching
|
|
77
103
|
|
|
78
104
|
Switching uses Pi's public `SessionManager` and `ctx.switchSession()` APIs:
|
|
@@ -96,6 +122,7 @@ A successfully created Git worktree is never rolled back merely because Pi sessi
|
|
|
96
122
|
- Removal and prune inspect reflogs, pseudorefs, per-worktree refs, and `FETCH_HEAD`. Historical commits reachable only through this administrative recovery state are listed by full OID in the destructive confirmation; approval removes those recovery pointers, so Git may later garbage-collect the commits. Create a branch or tag instead when any listed commit should survive.
|
|
97
123
|
- Staged-only administrative index state, a missing attached branch ref, or an unreachable current detached HEAD still blocks prune without an override.
|
|
98
124
|
- Removal never deletes a branch and never uses `--force`.
|
|
125
|
+
- Remove invokes only argv-based `git worktree remove <path>`; production runtime never invokes a shell, `rm`, `rm -rf`, or a Node filesystem directory-deletion API for worktrees.
|
|
99
126
|
- Prune always runs `git worktree prune --dry-run --verbose` before confirmation, inspects candidates omitted from porcelain, rechecks the exact preview and recovery-risk set after confirmation, and uses Git's default expiry. Remove likewise rechecks worktree identity, inventory, administrative path, and the approved recovery-risk set before mutation.
|
|
100
127
|
- The extension does not commit, push, rebase, repair, move, lock, or unlock worktrees.
|
|
101
128
|
|
|
@@ -106,23 +133,26 @@ Use Git directly when you intentionally need force removal, branch deletion, cus
|
|
|
106
133
|
- Git must be installed and the current Pi cwd must be inside a non-bare Git worktree.
|
|
107
134
|
- The command requires a UI-capable Pi mode; print and JSON modes cannot drive its dialogs.
|
|
108
135
|
- Project trust and cwd-bound extension/resource loading during a switch remain owned by Pi.
|
|
109
|
-
- The extension registers no LLM tool, background watcher, settings
|
|
136
|
+
- The extension registers no LLM tool, background watcher, project settings, or statusline item.
|
|
110
137
|
|
|
111
138
|
## 📁 Package layout
|
|
112
139
|
|
|
113
140
|
```text
|
|
114
141
|
extensions/pi-worktree/
|
|
115
142
|
├── src/
|
|
143
|
+
│ ├── index.ts
|
|
116
144
|
│ ├── command.ts
|
|
117
145
|
│ ├── git.ts
|
|
118
146
|
│ ├── session.ts
|
|
147
|
+
│ ├── settings.ts
|
|
119
148
|
│ └── worktree.ts
|
|
120
149
|
├── test/
|
|
121
150
|
│ ├── command.test.ts
|
|
122
151
|
│ ├── git.integration.test.ts
|
|
123
152
|
│ ├── git.test.ts
|
|
124
153
|
│ ├── remove-ignored-command.test.ts
|
|
125
|
-
│
|
|
154
|
+
│ ├── session.test.ts
|
|
155
|
+
│ └── settings.test.ts
|
|
126
156
|
├── package.json
|
|
127
157
|
├── README.md
|
|
128
158
|
├── LICENSE
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@narumitw/pi-worktree",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.28.0",
|
|
4
4
|
"description": "Pi extension for safe interactive Git worktree management and workspace switching.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -20,7 +20,7 @@
|
|
|
20
20
|
],
|
|
21
21
|
"pi": {
|
|
22
22
|
"extensions": [
|
|
23
|
-
"./src/
|
|
23
|
+
"./src/index.ts"
|
|
24
24
|
]
|
|
25
25
|
},
|
|
26
26
|
"scripts": {
|
package/src/command.ts
CHANGED
|
@@ -30,21 +30,23 @@ import {
|
|
|
30
30
|
worktreeInventory,
|
|
31
31
|
} from "./git.js";
|
|
32
32
|
import { switchToWorktree } from "./session.js";
|
|
33
|
+
import type { WorktreeSettingsRuntime } from "./settings.js";
|
|
33
34
|
|
|
34
35
|
const ACTION_ADD = "Add worktree";
|
|
35
36
|
const ACTION_SWITCH = "Switch worktree";
|
|
36
37
|
const ACTION_REMOVE = "Remove worktree";
|
|
37
38
|
const ACTION_PRUNE = "Prune stale metadata";
|
|
38
|
-
const
|
|
39
|
+
const ACTION_CONFIGURE_ROOT = "Configure worktree root";
|
|
40
|
+
const ACTIONS = [ACTION_ADD, ACTION_SWITCH, ACTION_REMOVE, ACTION_PRUNE, ACTION_CONFIGURE_ROOT];
|
|
39
41
|
|
|
40
42
|
interface AdministrativeHistoryRisk {
|
|
41
43
|
label: string;
|
|
42
44
|
oids: string[];
|
|
43
45
|
}
|
|
44
46
|
|
|
45
|
-
export function registerWorktreeCommand(pi: ExtensionAPI): void {
|
|
47
|
+
export function registerWorktreeCommand(pi: ExtensionAPI, settings: WorktreeSettingsRuntime): void {
|
|
46
48
|
pi.registerCommand("worktree", {
|
|
47
|
-
description: "Interactively
|
|
49
|
+
description: "Interactively manage Git worktrees and their default root",
|
|
48
50
|
handler: async (args, ctx) => {
|
|
49
51
|
if (args.trim()) {
|
|
50
52
|
safeNotify(
|
|
@@ -63,13 +65,17 @@ export function registerWorktreeCommand(pi: ExtensionAPI): void {
|
|
|
63
65
|
await ctx.waitForIdle();
|
|
64
66
|
const records = await listWorktrees(pi, ctx.cwd, ctx.signal);
|
|
65
67
|
const currentPath = await currentWorktreePath(pi, ctx.cwd, ctx.signal);
|
|
68
|
+
const root = settings.get();
|
|
69
|
+
const warning = root.warning ? " — settings warning" : "";
|
|
66
70
|
const action = await ctx.ui.select(
|
|
67
|
-
stripTerminalControls(
|
|
71
|
+
stripTerminalControls(
|
|
72
|
+
`Git worktrees (${records.length}) — current: ${currentPath}\nWorktree root: ${root.effectiveRoot} (${root.source})${warning}`,
|
|
73
|
+
),
|
|
68
74
|
ACTIONS,
|
|
69
75
|
);
|
|
70
76
|
switch (action) {
|
|
71
77
|
case ACTION_ADD:
|
|
72
|
-
await addFlow(pi, ctx, records);
|
|
78
|
+
await addFlow(pi, ctx, records, root.effectiveRoot);
|
|
73
79
|
return;
|
|
74
80
|
case ACTION_SWITCH:
|
|
75
81
|
await switchFlow(pi, ctx, records, currentPath);
|
|
@@ -80,6 +86,9 @@ export function registerWorktreeCommand(pi: ExtensionAPI): void {
|
|
|
80
86
|
case ACTION_PRUNE:
|
|
81
87
|
await pruneFlow(pi, ctx, records);
|
|
82
88
|
return;
|
|
89
|
+
case ACTION_CONFIGURE_ROOT:
|
|
90
|
+
await configureRootFlow(ctx, settings);
|
|
91
|
+
return;
|
|
83
92
|
}
|
|
84
93
|
} catch (error) {
|
|
85
94
|
safeNotify(ctx, formatError(error), "error");
|
|
@@ -88,10 +97,37 @@ export function registerWorktreeCommand(pi: ExtensionAPI): void {
|
|
|
88
97
|
});
|
|
89
98
|
}
|
|
90
99
|
|
|
100
|
+
async function configureRootFlow(
|
|
101
|
+
ctx: ExtensionCommandContext,
|
|
102
|
+
settings: WorktreeSettingsRuntime,
|
|
103
|
+
): Promise<void> {
|
|
104
|
+
const current = await settings.reload();
|
|
105
|
+
if (!current.canSave) {
|
|
106
|
+
throw new Error(
|
|
107
|
+
current.warning ?? `Fix ${settings.getPath()} before changing pi-worktree settings.`,
|
|
108
|
+
);
|
|
109
|
+
}
|
|
110
|
+
const requested = await ctx.ui.input(
|
|
111
|
+
"Worktree root (blank restores ~/.worktrees)",
|
|
112
|
+
stripTerminalControls(current.configuredRoot ?? current.effectiveRoot),
|
|
113
|
+
);
|
|
114
|
+
if (requested === undefined) return;
|
|
115
|
+
const configuredRoot = requested.trim() || undefined;
|
|
116
|
+
const updated = await settings.save(configuredRoot);
|
|
117
|
+
safeNotify(
|
|
118
|
+
ctx,
|
|
119
|
+
configuredRoot === undefined
|
|
120
|
+
? `Worktree root reset to ${updated.effectiveRoot}.`
|
|
121
|
+
: `Worktree root saved as ${updated.effectiveRoot}.`,
|
|
122
|
+
"info",
|
|
123
|
+
);
|
|
124
|
+
}
|
|
125
|
+
|
|
91
126
|
async function addFlow(
|
|
92
127
|
pi: ExtensionAPI,
|
|
93
128
|
ctx: ExtensionCommandContext,
|
|
94
129
|
records: readonly WorktreeRecord[],
|
|
130
|
+
worktreeRoot: string,
|
|
95
131
|
): Promise<void> {
|
|
96
132
|
const main = records[0];
|
|
97
133
|
if (!main) throw new Error("Git returned no registered worktrees.");
|
|
@@ -133,7 +169,7 @@ async function addFlow(
|
|
|
133
169
|
startOid = await resolveCommit(pi, ctx.cwd, startLabel, ctx.signal);
|
|
134
170
|
}
|
|
135
171
|
|
|
136
|
-
const suggestedPath = defaultWorktreePath(main.path, branch);
|
|
172
|
+
const suggestedPath = defaultWorktreePath(main.path, branch, worktreeRoot);
|
|
137
173
|
const requestedPath = await ctx.ui.input(
|
|
138
174
|
stripTerminalControls(`Worktree path (blank uses ${suggestedPath})`),
|
|
139
175
|
stripTerminalControls(suggestedPath),
|
package/src/git.ts
CHANGED
|
@@ -120,11 +120,12 @@ export function worktreeForBranch(
|
|
|
120
120
|
return records.find((record) => record.branchRef === branchRef);
|
|
121
121
|
}
|
|
122
122
|
|
|
123
|
-
export function defaultWorktreePath(
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
123
|
+
export function defaultWorktreePath(
|
|
124
|
+
mainWorktreePath: string,
|
|
125
|
+
branch: string,
|
|
126
|
+
worktreeRoot: string,
|
|
127
|
+
): string {
|
|
128
|
+
return resolve(worktreeRoot, basename(mainWorktreePath), branch.replaceAll("/", "-"));
|
|
128
129
|
}
|
|
129
130
|
|
|
130
131
|
export function buildAddArguments(input: AddArguments): string[] {
|
package/src/index.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { default } from "./worktree.js";
|
package/src/settings.ts
ADDED
|
@@ -0,0 +1,291 @@
|
|
|
1
|
+
import { lstat, mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { dirname, join, posix, win32 } from "node:path";
|
|
4
|
+
import { getAgentDir } from "@earendil-works/pi-coding-agent";
|
|
5
|
+
|
|
6
|
+
export const SETTINGS_FILE = "pi-worktree.json";
|
|
7
|
+
|
|
8
|
+
export type WorktreeSettingsSource = "default" | "user";
|
|
9
|
+
|
|
10
|
+
export interface LoadedWorktreeSettings {
|
|
11
|
+
kind: "missing" | "loaded" | "invalid";
|
|
12
|
+
path: string;
|
|
13
|
+
effectiveRoot: string;
|
|
14
|
+
source: WorktreeSettingsSource;
|
|
15
|
+
configuredRoot?: string;
|
|
16
|
+
document?: Record<string, unknown>;
|
|
17
|
+
warning?: string;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export interface WorktreeSettingsState {
|
|
21
|
+
effectiveRoot: string;
|
|
22
|
+
source: WorktreeSettingsSource;
|
|
23
|
+
configuredRoot?: string;
|
|
24
|
+
warning?: string;
|
|
25
|
+
canSave: boolean;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface SettingsFileOperations {
|
|
29
|
+
write(path: string, data: string): Promise<void>;
|
|
30
|
+
rename(source: string, destination: string): Promise<void>;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface WorktreeSettingsRuntime {
|
|
34
|
+
get(): Readonly<WorktreeSettingsState>;
|
|
35
|
+
getPath(): string;
|
|
36
|
+
reload(): Promise<Readonly<WorktreeSettingsState>>;
|
|
37
|
+
save(configuredRoot: string | undefined): Promise<Readonly<WorktreeSettingsState>>;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
interface RuntimeOptions {
|
|
41
|
+
path?: string | (() => string);
|
|
42
|
+
home?: string;
|
|
43
|
+
platform?: NodeJS.Platform;
|
|
44
|
+
operations?: Partial<SettingsFileOperations>;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const DEFAULT_FILE_OPERATIONS: SettingsFileOperations = {
|
|
48
|
+
write: (path, data) =>
|
|
49
|
+
writeFile(path, data, { encoding: "utf8", flag: "wx", mode: 0o600 }).then(() => undefined),
|
|
50
|
+
rename,
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
export function settingsFilePath(): string {
|
|
54
|
+
return join(getAgentDir(), SETTINGS_FILE);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export function defaultWorktreeRoot(
|
|
58
|
+
home = homedir(),
|
|
59
|
+
platform: NodeJS.Platform = process.platform,
|
|
60
|
+
): string {
|
|
61
|
+
return platformPath(platform).join(home, ".worktrees");
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export function resolveWorktreeRoot(
|
|
65
|
+
value: string,
|
|
66
|
+
home = homedir(),
|
|
67
|
+
platform: NodeJS.Platform = process.platform,
|
|
68
|
+
): string {
|
|
69
|
+
if (!value || value.includes("\0")) {
|
|
70
|
+
throw new Error("worktreeRoot must be a non-empty path without NUL characters.");
|
|
71
|
+
}
|
|
72
|
+
if (hasShellVariableSyntax(value)) {
|
|
73
|
+
throw new Error("worktreeRoot must not contain shell variable syntax.");
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const path = platformPath(platform);
|
|
77
|
+
let candidate = value;
|
|
78
|
+
if (value === "~") {
|
|
79
|
+
candidate = home;
|
|
80
|
+
} else if (value.startsWith("~/") || (platform === "win32" && value.startsWith("~\\"))) {
|
|
81
|
+
candidate = path.resolve(home, value.slice(2));
|
|
82
|
+
} else if (value.startsWith("~")) {
|
|
83
|
+
throw new Error("worktreeRoot supports only ~ itself or a path beginning with ~/.");
|
|
84
|
+
}
|
|
85
|
+
if (!path.isAbsolute(candidate)) {
|
|
86
|
+
throw new Error("worktreeRoot must be an absolute path or begin with ~/.");
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
try {
|
|
90
|
+
const normalized = path.normalize(candidate);
|
|
91
|
+
if (!normalized || !path.isAbsolute(normalized)) {
|
|
92
|
+
throw new Error("normalization did not produce an absolute path");
|
|
93
|
+
}
|
|
94
|
+
return normalized;
|
|
95
|
+
} catch (error) {
|
|
96
|
+
throw new Error(`worktreeRoot could not be normalized: ${formatError(error)}`);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export async function loadWorktreeSettings(
|
|
101
|
+
path = settingsFilePath(),
|
|
102
|
+
home = homedir(),
|
|
103
|
+
platform: NodeJS.Platform = process.platform,
|
|
104
|
+
): Promise<LoadedWorktreeSettings> {
|
|
105
|
+
const fallback = defaultWorktreeRoot(home, platform);
|
|
106
|
+
let text: string;
|
|
107
|
+
try {
|
|
108
|
+
const stats = await lstat(path);
|
|
109
|
+
if (stats.isSymbolicLink()) return invalid(path, fallback, "symbolic links are not accepted");
|
|
110
|
+
if (!stats.isFile()) return invalid(path, fallback, "settings path is not a regular file");
|
|
111
|
+
text = await readFile(path, "utf8");
|
|
112
|
+
} catch (error) {
|
|
113
|
+
if (isNodeError(error) && error.code === "ENOENT") {
|
|
114
|
+
return {
|
|
115
|
+
kind: "missing",
|
|
116
|
+
path,
|
|
117
|
+
effectiveRoot: fallback,
|
|
118
|
+
source: "default",
|
|
119
|
+
document: {},
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
return invalid(path, fallback, formatError(error));
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
try {
|
|
126
|
+
const document = JSON.parse(text) as unknown;
|
|
127
|
+
if (!isRecord(document)) return invalid(path, fallback, "the top level must be a JSON object");
|
|
128
|
+
if (!Object.hasOwn(document, "worktreeRoot")) {
|
|
129
|
+
return {
|
|
130
|
+
kind: "loaded",
|
|
131
|
+
path,
|
|
132
|
+
effectiveRoot: fallback,
|
|
133
|
+
source: "default",
|
|
134
|
+
document,
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
if (typeof document.worktreeRoot !== "string") {
|
|
138
|
+
return invalid(path, fallback, "worktreeRoot must be a string");
|
|
139
|
+
}
|
|
140
|
+
const effectiveRoot = resolveWorktreeRoot(document.worktreeRoot, home, platform);
|
|
141
|
+
return {
|
|
142
|
+
kind: "loaded",
|
|
143
|
+
path,
|
|
144
|
+
effectiveRoot,
|
|
145
|
+
source: "user",
|
|
146
|
+
configuredRoot: document.worktreeRoot,
|
|
147
|
+
document,
|
|
148
|
+
};
|
|
149
|
+
} catch (error) {
|
|
150
|
+
return invalid(path, fallback, formatError(error));
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
export async function saveWorktreeSettings(
|
|
155
|
+
document: Record<string, unknown>,
|
|
156
|
+
configuredRoot: string | undefined,
|
|
157
|
+
path = settingsFilePath(),
|
|
158
|
+
operations: Partial<SettingsFileOperations> = {},
|
|
159
|
+
): Promise<Record<string, unknown>> {
|
|
160
|
+
const nextDocument = { ...document };
|
|
161
|
+
if (configuredRoot === undefined) delete nextDocument.worktreeRoot;
|
|
162
|
+
else nextDocument.worktreeRoot = configuredRoot;
|
|
163
|
+
|
|
164
|
+
await mkdir(dirname(path), { recursive: true });
|
|
165
|
+
const temporaryPath = temporaryFilePath(path);
|
|
166
|
+
try {
|
|
167
|
+
await (operations.write ?? DEFAULT_FILE_OPERATIONS.write)(
|
|
168
|
+
temporaryPath,
|
|
169
|
+
`${JSON.stringify(nextDocument, null, 2)}\n`,
|
|
170
|
+
);
|
|
171
|
+
await (operations.rename ?? DEFAULT_FILE_OPERATIONS.rename)(temporaryPath, path);
|
|
172
|
+
return nextDocument;
|
|
173
|
+
} catch (error) {
|
|
174
|
+
await unlink(temporaryPath).catch(() => undefined);
|
|
175
|
+
throw error;
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
export function createWorktreeSettingsRuntime(
|
|
180
|
+
options: RuntimeOptions = {},
|
|
181
|
+
): WorktreeSettingsRuntime {
|
|
182
|
+
const home = options.home ?? homedir();
|
|
183
|
+
const platform = options.platform ?? process.platform;
|
|
184
|
+
let resolvedPath: string | undefined;
|
|
185
|
+
const getPath = () => {
|
|
186
|
+
resolvedPath ??=
|
|
187
|
+
typeof options.path === "function" ? options.path() : (options.path ?? settingsFilePath());
|
|
188
|
+
return resolvedPath;
|
|
189
|
+
};
|
|
190
|
+
let document: Record<string, unknown> = {};
|
|
191
|
+
let operationQueue = Promise.resolve();
|
|
192
|
+
const enqueue = <T>(operation: () => Promise<T>): Promise<T> => {
|
|
193
|
+
const result = operationQueue.then(operation, operation);
|
|
194
|
+
operationQueue = result.then(
|
|
195
|
+
() => undefined,
|
|
196
|
+
() => undefined,
|
|
197
|
+
);
|
|
198
|
+
return result;
|
|
199
|
+
};
|
|
200
|
+
let state: WorktreeSettingsState = {
|
|
201
|
+
effectiveRoot: defaultWorktreeRoot(home, platform),
|
|
202
|
+
source: "default",
|
|
203
|
+
canSave: true,
|
|
204
|
+
};
|
|
205
|
+
|
|
206
|
+
return {
|
|
207
|
+
get: () => Object.freeze({ ...state }),
|
|
208
|
+
getPath,
|
|
209
|
+
reload() {
|
|
210
|
+
return enqueue(async () => {
|
|
211
|
+
const loaded = await loadWorktreeSettings(getPath(), home, platform);
|
|
212
|
+
if (loaded.kind === "invalid") {
|
|
213
|
+
state = { ...state, warning: loaded.warning, canSave: false };
|
|
214
|
+
return Object.freeze({ ...state });
|
|
215
|
+
}
|
|
216
|
+
document = loaded.document ?? {};
|
|
217
|
+
state = stateFromLoaded(loaded);
|
|
218
|
+
return Object.freeze({ ...state });
|
|
219
|
+
});
|
|
220
|
+
},
|
|
221
|
+
save(configuredRoot) {
|
|
222
|
+
return enqueue(async () => {
|
|
223
|
+
if (!state.canSave) {
|
|
224
|
+
throw new Error(`Fix the pi-worktree settings file at ${getPath()} before changing it.`);
|
|
225
|
+
}
|
|
226
|
+
const effectiveRoot =
|
|
227
|
+
configuredRoot === undefined
|
|
228
|
+
? defaultWorktreeRoot(home, platform)
|
|
229
|
+
: resolveWorktreeRoot(configuredRoot, home, platform);
|
|
230
|
+
const nextDocument = await saveWorktreeSettings(
|
|
231
|
+
document,
|
|
232
|
+
configuredRoot,
|
|
233
|
+
getPath(),
|
|
234
|
+
options.operations,
|
|
235
|
+
);
|
|
236
|
+
document = nextDocument;
|
|
237
|
+
state = {
|
|
238
|
+
effectiveRoot,
|
|
239
|
+
source: configuredRoot === undefined ? "default" : "user",
|
|
240
|
+
...(configuredRoot === undefined ? {} : { configuredRoot }),
|
|
241
|
+
canSave: true,
|
|
242
|
+
};
|
|
243
|
+
return Object.freeze({ ...state });
|
|
244
|
+
});
|
|
245
|
+
},
|
|
246
|
+
};
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
function stateFromLoaded(loaded: LoadedWorktreeSettings): WorktreeSettingsState {
|
|
250
|
+
return {
|
|
251
|
+
effectiveRoot: loaded.effectiveRoot,
|
|
252
|
+
source: loaded.source,
|
|
253
|
+
...(loaded.configuredRoot === undefined ? {} : { configuredRoot: loaded.configuredRoot }),
|
|
254
|
+
...(loaded.warning === undefined ? {} : { warning: loaded.warning }),
|
|
255
|
+
canSave: true,
|
|
256
|
+
};
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
function invalid(path: string, fallback: string, reason: string): LoadedWorktreeSettings {
|
|
260
|
+
return {
|
|
261
|
+
kind: "invalid",
|
|
262
|
+
path,
|
|
263
|
+
effectiveRoot: fallback,
|
|
264
|
+
source: "default",
|
|
265
|
+
warning: `${SETTINGS_FILE} ignored (${path}: ${reason}); using the safe default or last valid root without overwriting the file.`,
|
|
266
|
+
};
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
function platformPath(platform: NodeJS.Platform): typeof posix | typeof win32 {
|
|
270
|
+
return platform === "win32" ? win32 : posix;
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
function hasShellVariableSyntax(value: string): boolean {
|
|
274
|
+
return /\$|%[^%]+%/u.test(value);
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
function temporaryFilePath(path: string): string {
|
|
278
|
+
return `${path}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
282
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
function isNodeError(error: unknown): error is NodeJS.ErrnoException {
|
|
286
|
+
return error instanceof Error && "code" in error;
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
function formatError(error: unknown): string {
|
|
290
|
+
return error instanceof Error ? error.message : String(error);
|
|
291
|
+
}
|
package/src/worktree.ts
CHANGED
|
@@ -1,6 +1,29 @@
|
|
|
1
1
|
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
2
2
|
import { registerWorktreeCommand } from "./command.js";
|
|
3
|
+
import {
|
|
4
|
+
createWorktreeSettingsRuntime,
|
|
5
|
+
settingsFilePath,
|
|
6
|
+
type WorktreeSettingsRuntime,
|
|
7
|
+
} from "./settings.js";
|
|
3
8
|
|
|
4
|
-
|
|
5
|
-
|
|
9
|
+
interface WorktreeExtensionOptions {
|
|
10
|
+
settings?: WorktreeSettingsRuntime;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export default function worktreeExtension(
|
|
14
|
+
pi: ExtensionAPI,
|
|
15
|
+
options: WorktreeExtensionOptions = {},
|
|
16
|
+
): void {
|
|
17
|
+
const settings = options.settings ?? createWorktreeSettingsRuntime({ path: settingsFilePath });
|
|
18
|
+
registerWorktreeCommand(pi, settings);
|
|
19
|
+
|
|
20
|
+
pi.on("session_start", async (_event, ctx) => {
|
|
21
|
+
const loaded = await settings.reload();
|
|
22
|
+
if (!loaded.warning || !ctx.hasUI) return;
|
|
23
|
+
try {
|
|
24
|
+
ctx.ui.notify(loaded.warning, "warning");
|
|
25
|
+
} catch {
|
|
26
|
+
// A replacement session may invalidate its predecessor context during async startup.
|
|
27
|
+
}
|
|
28
|
+
});
|
|
6
29
|
}
|