@narumitw/pi-worktree 0.51.7 → 0.51.9

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/src/settings.ts CHANGED
@@ -8,290 +8,278 @@ export const SETTINGS_FILE = "pi-worktree.json";
8
8
  export type WorktreeSettingsSource = "default" | "user";
9
9
 
10
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;
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
18
  }
19
19
 
20
20
  export interface WorktreeSettingsState {
21
- effectiveRoot: string;
22
- source: WorktreeSettingsSource;
23
- configuredRoot?: string;
24
- warning?: string;
25
- canSave: boolean;
21
+ effectiveRoot: string;
22
+ source: WorktreeSettingsSource;
23
+ configuredRoot?: string;
24
+ warning?: string;
25
+ canSave: boolean;
26
26
  }
27
27
 
28
28
  export interface SettingsFileOperations {
29
- write(path: string, data: string): Promise<void>;
30
- rename(source: string, destination: string): Promise<void>;
29
+ write(path: string, data: string): Promise<void>;
30
+ rename(source: string, destination: string): Promise<void>;
31
31
  }
32
32
 
33
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
- flush?(): Promise<void>;
34
+ get(): Readonly<WorktreeSettingsState>;
35
+ getPath(): string;
36
+ reload(): Promise<Readonly<WorktreeSettingsState>>;
37
+ save(configuredRoot: string | undefined): Promise<Readonly<WorktreeSettingsState>>;
38
+ flush?(): Promise<void>;
39
39
  }
40
40
 
41
41
  interface RuntimeOptions {
42
- path?: string | (() => string);
43
- home?: string;
44
- platform?: NodeJS.Platform;
45
- operations?: Partial<SettingsFileOperations>;
42
+ path?: string | (() => string);
43
+ home?: string;
44
+ platform?: NodeJS.Platform;
45
+ operations?: Partial<SettingsFileOperations>;
46
46
  }
47
47
 
48
48
  const DEFAULT_FILE_OPERATIONS: SettingsFileOperations = {
49
- write: (path, data) =>
50
- writeFile(path, data, { encoding: "utf8", flag: "wx", mode: 0o600 }).then(() => undefined),
51
- rename,
49
+ write: (path, data) => writeFile(path, data, { encoding: "utf8", flag: "wx", mode: 0o600 }).then(() => undefined),
50
+ rename,
52
51
  };
53
52
 
54
53
  export function settingsFilePath(): string {
55
- return join(getAgentDir(), SETTINGS_FILE);
54
+ return join(getAgentDir(), SETTINGS_FILE);
56
55
  }
57
56
 
58
- export function defaultWorktreeRoot(
59
- home = homedir(),
60
- platform: NodeJS.Platform = process.platform,
61
- ): string {
62
- return platformPath(platform).join(home, ".worktrees");
57
+ export function defaultWorktreeRoot(home = homedir(), platform: NodeJS.Platform = process.platform): string {
58
+ return platformPath(platform).join(home, ".worktrees");
63
59
  }
64
60
 
65
61
  export function resolveWorktreeRoot(
66
- value: string,
67
- home = homedir(),
68
- platform: NodeJS.Platform = process.platform,
62
+ value: string,
63
+ home = homedir(),
64
+ platform: NodeJS.Platform = process.platform,
69
65
  ): string {
70
- if (!value || value.includes("\0")) {
71
- throw new Error("worktreeRoot must be a non-empty path without NUL characters.");
72
- }
73
- if (hasShellVariableSyntax(value)) {
74
- throw new Error("worktreeRoot must not contain shell variable syntax.");
75
- }
66
+ if (!value || value.includes("\0")) {
67
+ throw new Error("worktreeRoot must be a non-empty path without NUL characters.");
68
+ }
69
+ if (hasShellVariableSyntax(value)) {
70
+ throw new Error("worktreeRoot must not contain shell variable syntax.");
71
+ }
76
72
 
77
- const path = platformPath(platform);
78
- let candidate = value;
79
- if (value === "~") {
80
- candidate = home;
81
- } else if (value.startsWith("~/") || (platform === "win32" && value.startsWith("~\\"))) {
82
- candidate = path.resolve(home, value.slice(2));
83
- } else if (value.startsWith("~")) {
84
- throw new Error("worktreeRoot supports only ~ itself or a path beginning with ~/.");
85
- }
86
- if (!path.isAbsolute(candidate)) {
87
- throw new Error("worktreeRoot must be an absolute path or begin with ~/.");
88
- }
73
+ const path = platformPath(platform);
74
+ let candidate = value;
75
+ if (value === "~") {
76
+ candidate = home;
77
+ } else if (value.startsWith("~/") || (platform === "win32" && value.startsWith("~\\"))) {
78
+ candidate = path.resolve(home, value.slice(2));
79
+ } else if (value.startsWith("~")) {
80
+ throw new Error("worktreeRoot supports only ~ itself or a path beginning with ~/.");
81
+ }
82
+ if (!path.isAbsolute(candidate)) {
83
+ throw new Error("worktreeRoot must be an absolute path or begin with ~/.");
84
+ }
89
85
 
90
- try {
91
- const normalized = path.normalize(candidate);
92
- if (!normalized || !path.isAbsolute(normalized)) {
93
- throw new Error("normalization did not produce an absolute path");
94
- }
95
- return normalized;
96
- } catch (error) {
97
- throw new Error(`worktreeRoot could not be normalized: ${formatError(error)}`);
98
- }
86
+ try {
87
+ const normalized = path.normalize(candidate);
88
+ if (!normalized || !path.isAbsolute(normalized)) {
89
+ throw new Error("normalization did not produce an absolute path");
90
+ }
91
+ return normalized;
92
+ } catch (error) {
93
+ throw new Error(`worktreeRoot could not be normalized: ${formatError(error)}`);
94
+ }
99
95
  }
100
96
 
101
97
  export async function loadWorktreeSettings(
102
- path = settingsFilePath(),
103
- home = homedir(),
104
- platform: NodeJS.Platform = process.platform,
98
+ path = settingsFilePath(),
99
+ home = homedir(),
100
+ platform: NodeJS.Platform = process.platform,
105
101
  ): Promise<LoadedWorktreeSettings> {
106
- const fallback = defaultWorktreeRoot(home, platform);
107
- let text: string;
108
- try {
109
- const stats = await lstat(path);
110
- if (stats.isSymbolicLink()) return invalid(path, fallback, "symbolic links are not accepted");
111
- if (!stats.isFile()) return invalid(path, fallback, "settings path is not a regular file");
112
- text = await readFile(path, "utf8");
113
- } catch (error) {
114
- if (isNodeError(error) && error.code === "ENOENT") {
115
- return {
116
- kind: "missing",
117
- path,
118
- effectiveRoot: fallback,
119
- source: "default",
120
- document: {},
121
- };
122
- }
123
- return invalid(path, fallback, formatError(error));
124
- }
102
+ const fallback = defaultWorktreeRoot(home, platform);
103
+ let text: string;
104
+ try {
105
+ const stats = await lstat(path);
106
+ if (stats.isSymbolicLink()) return invalid(path, fallback, "symbolic links are not accepted");
107
+ if (!stats.isFile()) return invalid(path, fallback, "settings path is not a regular file");
108
+ text = await readFile(path, "utf8");
109
+ } catch (error) {
110
+ if (isNodeError(error) && error.code === "ENOENT") {
111
+ return {
112
+ kind: "missing",
113
+ path,
114
+ effectiveRoot: fallback,
115
+ source: "default",
116
+ document: {},
117
+ };
118
+ }
119
+ return invalid(path, fallback, formatError(error));
120
+ }
125
121
 
126
- try {
127
- const document = JSON.parse(text) as unknown;
128
- if (!isRecord(document)) return invalid(path, fallback, "the top level must be a JSON object");
129
- if (!Object.hasOwn(document, "worktreeRoot")) {
130
- return {
131
- kind: "loaded",
132
- path,
133
- effectiveRoot: fallback,
134
- source: "default",
135
- document,
136
- };
137
- }
138
- if (typeof document.worktreeRoot !== "string") {
139
- return invalid(path, fallback, "worktreeRoot must be a string");
140
- }
141
- const effectiveRoot = resolveWorktreeRoot(document.worktreeRoot, home, platform);
142
- return {
143
- kind: "loaded",
144
- path,
145
- effectiveRoot,
146
- source: "user",
147
- configuredRoot: document.worktreeRoot,
148
- document,
149
- };
150
- } catch (error) {
151
- return invalid(path, fallback, formatError(error));
152
- }
122
+ try {
123
+ const document = JSON.parse(text) as unknown;
124
+ if (!isRecord(document)) return invalid(path, fallback, "the top level must be a JSON object");
125
+ if (!Object.hasOwn(document, "worktreeRoot")) {
126
+ return {
127
+ kind: "loaded",
128
+ path,
129
+ effectiveRoot: fallback,
130
+ source: "default",
131
+ document,
132
+ };
133
+ }
134
+ if (typeof document.worktreeRoot !== "string") {
135
+ return invalid(path, fallback, "worktreeRoot must be a string");
136
+ }
137
+ const effectiveRoot = resolveWorktreeRoot(document.worktreeRoot, home, platform);
138
+ return {
139
+ kind: "loaded",
140
+ path,
141
+ effectiveRoot,
142
+ source: "user",
143
+ configuredRoot: document.worktreeRoot,
144
+ document,
145
+ };
146
+ } catch (error) {
147
+ return invalid(path, fallback, formatError(error));
148
+ }
153
149
  }
154
150
 
155
151
  export async function saveWorktreeSettings(
156
- document: Record<string, unknown>,
157
- configuredRoot: string | undefined,
158
- path = settingsFilePath(),
159
- operations: Partial<SettingsFileOperations> = {},
152
+ document: Record<string, unknown>,
153
+ configuredRoot: string | undefined,
154
+ path = settingsFilePath(),
155
+ operations: Partial<SettingsFileOperations> = {},
160
156
  ): Promise<Record<string, unknown>> {
161
- const nextDocument = { ...document };
162
- if (configuredRoot === undefined) delete nextDocument.worktreeRoot;
163
- else nextDocument.worktreeRoot = configuredRoot;
157
+ const nextDocument = { ...document };
158
+ if (configuredRoot === undefined) delete nextDocument.worktreeRoot;
159
+ else nextDocument.worktreeRoot = configuredRoot;
164
160
 
165
- await mkdir(dirname(path), { recursive: true });
166
- const temporaryPath = temporaryFilePath(path);
167
- try {
168
- await (operations.write ?? DEFAULT_FILE_OPERATIONS.write)(
169
- temporaryPath,
170
- `${JSON.stringify(nextDocument, null, 2)}\n`,
171
- );
172
- await (operations.rename ?? DEFAULT_FILE_OPERATIONS.rename)(temporaryPath, path);
173
- return nextDocument;
174
- } catch (error) {
175
- await unlink(temporaryPath).catch(() => undefined);
176
- throw error;
177
- }
161
+ await mkdir(dirname(path), { recursive: true });
162
+ const temporaryPath = temporaryFilePath(path);
163
+ try {
164
+ await (operations.write ?? DEFAULT_FILE_OPERATIONS.write)(
165
+ temporaryPath,
166
+ `${JSON.stringify(nextDocument, null, 2)}\n`,
167
+ );
168
+ await (operations.rename ?? DEFAULT_FILE_OPERATIONS.rename)(temporaryPath, path);
169
+ return nextDocument;
170
+ } catch (error) {
171
+ await unlink(temporaryPath).catch(() => undefined);
172
+ throw error;
173
+ }
178
174
  }
179
175
 
180
- export function createWorktreeSettingsRuntime(
181
- options: RuntimeOptions = {},
182
- ): WorktreeSettingsRuntime {
183
- const home = options.home ?? homedir();
184
- const platform = options.platform ?? process.platform;
185
- let resolvedPath: string | undefined;
186
- const getPath = () => {
187
- resolvedPath ??=
188
- typeof options.path === "function" ? options.path() : (options.path ?? settingsFilePath());
189
- return resolvedPath;
190
- };
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
- };
176
+ export function createWorktreeSettingsRuntime(options: RuntimeOptions = {}): WorktreeSettingsRuntime {
177
+ const home = options.home ?? homedir();
178
+ const platform = options.platform ?? process.platform;
179
+ let resolvedPath: string | undefined;
180
+ const getPath = () => {
181
+ resolvedPath ??= typeof options.path === "function" ? options.path() : (options.path ?? settingsFilePath());
182
+ return resolvedPath;
183
+ };
184
+ let operationQueue = Promise.resolve();
185
+ const enqueue = <T>(operation: () => Promise<T>): Promise<T> => {
186
+ const result = operationQueue.then(operation, operation);
187
+ operationQueue = result.then(
188
+ () => undefined,
189
+ () => undefined,
190
+ );
191
+ return result;
192
+ };
193
+ let state: WorktreeSettingsState = {
194
+ effectiveRoot: defaultWorktreeRoot(home, platform),
195
+ source: "default",
196
+ canSave: true,
197
+ };
205
198
 
206
- return {
207
- get: () => Object.freeze({ ...state }),
208
- getPath,
209
- async flush() {
210
- await operationQueue;
211
- },
212
- reload() {
213
- return enqueue(async () => {
214
- const loaded = await loadWorktreeSettings(getPath(), home, platform);
215
- if (loaded.kind === "invalid") {
216
- state = { ...state, warning: loaded.warning, canSave: false };
217
- return Object.freeze({ ...state });
218
- }
219
- state = stateFromLoaded(loaded);
220
- return Object.freeze({ ...state });
221
- });
222
- },
223
- save(configuredRoot) {
224
- return enqueue(async () => {
225
- if (!state.canSave) {
226
- throw new Error(`Fix the pi-worktree settings file at ${getPath()} before changing it.`);
227
- }
228
- const effectiveRoot =
229
- configuredRoot === undefined
230
- ? defaultWorktreeRoot(home, platform)
231
- : resolveWorktreeRoot(configuredRoot, home, platform);
232
- const latest = await loadWorktreeSettings(getPath(), home, platform);
233
- if (latest.kind === "invalid") {
234
- state = { ...state, warning: latest.warning, canSave: false };
235
- throw new Error(`Fix the pi-worktree settings file at ${getPath()} before changing it.`);
236
- }
237
- await saveWorktreeSettings(
238
- latest.document ?? {},
239
- configuredRoot,
240
- getPath(),
241
- options.operations,
242
- );
243
- state = {
244
- effectiveRoot,
245
- source: configuredRoot === undefined ? "default" : "user",
246
- ...(configuredRoot === undefined ? {} : { configuredRoot }),
247
- canSave: true,
248
- };
249
- return Object.freeze({ ...state });
250
- });
251
- },
252
- };
199
+ return {
200
+ get: () => Object.freeze({ ...state }),
201
+ getPath,
202
+ async flush() {
203
+ await operationQueue;
204
+ },
205
+ reload() {
206
+ return enqueue(async () => {
207
+ const loaded = await loadWorktreeSettings(getPath(), home, platform);
208
+ if (loaded.kind === "invalid") {
209
+ state = { ...state, warning: loaded.warning, canSave: false };
210
+ return Object.freeze({ ...state });
211
+ }
212
+ state = stateFromLoaded(loaded);
213
+ return Object.freeze({ ...state });
214
+ });
215
+ },
216
+ save(configuredRoot) {
217
+ return enqueue(async () => {
218
+ if (!state.canSave) {
219
+ throw new Error(`Fix the pi-worktree settings file at ${getPath()} before changing it.`);
220
+ }
221
+ const effectiveRoot =
222
+ configuredRoot === undefined
223
+ ? defaultWorktreeRoot(home, platform)
224
+ : resolveWorktreeRoot(configuredRoot, home, platform);
225
+ const latest = await loadWorktreeSettings(getPath(), home, platform);
226
+ if (latest.kind === "invalid") {
227
+ state = { ...state, warning: latest.warning, canSave: false };
228
+ throw new Error(`Fix the pi-worktree settings file at ${getPath()} before changing it.`);
229
+ }
230
+ await saveWorktreeSettings(latest.document ?? {}, configuredRoot, getPath(), options.operations);
231
+ state = {
232
+ effectiveRoot,
233
+ source: configuredRoot === undefined ? "default" : "user",
234
+ ...(configuredRoot === undefined ? {} : { configuredRoot }),
235
+ canSave: true,
236
+ };
237
+ return Object.freeze({ ...state });
238
+ });
239
+ },
240
+ };
253
241
  }
254
242
 
255
243
  function stateFromLoaded(loaded: LoadedWorktreeSettings): WorktreeSettingsState {
256
- return {
257
- effectiveRoot: loaded.effectiveRoot,
258
- source: loaded.source,
259
- ...(loaded.configuredRoot === undefined ? {} : { configuredRoot: loaded.configuredRoot }),
260
- ...(loaded.warning === undefined ? {} : { warning: loaded.warning }),
261
- canSave: true,
262
- };
244
+ return {
245
+ effectiveRoot: loaded.effectiveRoot,
246
+ source: loaded.source,
247
+ ...(loaded.configuredRoot === undefined ? {} : { configuredRoot: loaded.configuredRoot }),
248
+ ...(loaded.warning === undefined ? {} : { warning: loaded.warning }),
249
+ canSave: true,
250
+ };
263
251
  }
264
252
 
265
253
  function invalid(path: string, fallback: string, reason: string): LoadedWorktreeSettings {
266
- return {
267
- kind: "invalid",
268
- path,
269
- effectiveRoot: fallback,
270
- source: "default",
271
- warning: `${SETTINGS_FILE} ignored (${path}: ${reason}); using the safe default or last valid root without overwriting the file.`,
272
- };
254
+ return {
255
+ kind: "invalid",
256
+ path,
257
+ effectiveRoot: fallback,
258
+ source: "default",
259
+ warning: `${SETTINGS_FILE} ignored (${path}: ${reason}); using the safe default or last valid root without overwriting the file.`,
260
+ };
273
261
  }
274
262
 
275
263
  function platformPath(platform: NodeJS.Platform): typeof posix | typeof win32 {
276
- return platform === "win32" ? win32 : posix;
264
+ return platform === "win32" ? win32 : posix;
277
265
  }
278
266
 
279
267
  function hasShellVariableSyntax(value: string): boolean {
280
- return /\$|%[^%]+%/u.test(value);
268
+ return /\$|%[^%]+%/u.test(value);
281
269
  }
282
270
 
283
271
  function temporaryFilePath(path: string): string {
284
- return `${path}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`;
272
+ return `${path}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`;
285
273
  }
286
274
 
287
275
  function isRecord(value: unknown): value is Record<string, unknown> {
288
- return typeof value === "object" && value !== null && !Array.isArray(value);
276
+ return typeof value === "object" && value !== null && !Array.isArray(value);
289
277
  }
290
278
 
291
279
  function isNodeError(error: unknown): error is NodeJS.ErrnoException {
292
- return error instanceof Error && "code" in error;
280
+ return error instanceof Error && "code" in error;
293
281
  }
294
282
 
295
283
  function formatError(error: unknown): string {
296
- return error instanceof Error ? error.message : String(error);
284
+ return error instanceof Error ? error.message : String(error);
297
285
  }