@intra-mart/accel 2.0.0 → 3.0.0-dev.202611201537

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.
Files changed (69) hide show
  1. package/README.md +9 -3
  2. package/assets/githooks/.githooks/pre-commit/pre-commit_en +71 -32
  3. package/assets/githooks/.githooks/pre-commit/pre-commit_ja +67 -33
  4. package/assets/githooks/.githooks/pre-commit/pre-commit_zh_CN +66 -32
  5. package/assets/runtime/ensure.mjs +27 -16
  6. package/dist/asset/deployer.d.ts +0 -2
  7. package/dist/asset/deployer.js +1 -6
  8. package/dist/asset/installer.d.ts +18 -2
  9. package/dist/asset/installer.js +94 -17
  10. package/dist/commands/attach-existing-files.d.ts +7 -0
  11. package/dist/commands/attach-existing-files.js +47 -1
  12. package/dist/commands/attach.d.ts +2 -0
  13. package/dist/commands/attach.js +20 -4
  14. package/dist/commands/deploy.d.ts +5 -1
  15. package/dist/commands/deploy.js +10 -3
  16. package/dist/commands/detach.d.ts +3 -1
  17. package/dist/commands/detach.js +16 -4
  18. package/dist/commands/init.d.ts +2 -0
  19. package/dist/commands/init.js +8 -3
  20. package/dist/commands/login.d.ts +8 -0
  21. package/dist/commands/login.js +13 -1
  22. package/dist/commands/mobile/attach.js +2 -3
  23. package/dist/commands/mobile/init.js +5 -2
  24. package/dist/commands/mobile/shared.d.ts +1 -1
  25. package/dist/commands/mobile/shared.js +5 -2
  26. package/dist/commands/switch.d.ts +2 -0
  27. package/dist/commands/switch.js +2 -2
  28. package/dist/commands/update.d.ts +2 -0
  29. package/dist/commands/update.js +1 -1
  30. package/dist/git/config-file.d.ts +10 -2
  31. package/dist/git/config-file.js +177 -94
  32. package/dist/git/config-scopes.d.ts +17 -0
  33. package/dist/git/config-scopes.js +33 -0
  34. package/dist/git/index-file.js +23 -4
  35. package/dist/git/read-capped.d.ts +1 -0
  36. package/dist/git/read-capped.js +6 -3
  37. package/dist/git/repo-discovery.d.ts +26 -0
  38. package/dist/git/repo-discovery.js +213 -0
  39. package/dist/git/untracked.d.ts +1 -0
  40. package/dist/git/untracked.js +23 -1
  41. package/dist/git/worktree-status.js +26 -21
  42. package/dist/i18n/en.js +72 -6
  43. package/dist/i18n/ja.js +72 -6
  44. package/dist/i18n/zh_CN.js +72 -6
  45. package/dist/interactive/credentials-prompts.d.ts +4 -1
  46. package/dist/interactive/credentials-prompts.js +2 -1
  47. package/dist/interactive/hook-confirm.d.ts +2 -0
  48. package/dist/interactive/hook-confirm.js +16 -0
  49. package/dist/lib.d.ts +1 -0
  50. package/dist/utils/command-exists.d.ts +5 -0
  51. package/dist/utils/command-exists.js +7 -6
  52. package/dist/utils/external-command.d.ts +0 -1
  53. package/dist/utils/external-command.js +1 -29
  54. package/dist/utils/githooks-remove.d.ts +27 -0
  55. package/dist/utils/githooks-remove.js +196 -0
  56. package/dist/utils/githooks-state.d.ts +80 -0
  57. package/dist/utils/githooks-state.js +364 -0
  58. package/dist/utils/githooks-sync.d.ts +11 -2
  59. package/dist/utils/githooks-sync.js +360 -68
  60. package/dist/utils/managed-marker.d.ts +1 -0
  61. package/dist/utils/managed-marker.js +1 -0
  62. package/dist/utils/mcp-generate.d.ts +5 -1
  63. package/dist/utils/mcp-generate.js +13 -4
  64. package/dist/utils/output-tail.d.ts +11 -0
  65. package/dist/utils/output-tail.js +29 -0
  66. package/dist/utils/runtime-ensure.js +10 -4
  67. package/package.json +1 -1
  68. package/dist/git/repo-layout.d.ts +0 -5
  69. package/dist/git/repo-layout.js +0 -44
@@ -62,4 +62,4 @@ export declare const buildMobileSettings: (opts: {
62
62
  }) => MobileProjectSettings;
63
63
  export declare const withSpinner: <T>(input: Pick<MobileRunInput, "logger">, message: string, run: () => Promise<T>) => Promise<T>;
64
64
  export declare const expoSkillsHintForAddedAgents: (previousAgents: readonly string[], nextAgents: readonly string[], mobile: MobileMeta, locale: string) => string | undefined;
65
- export declare const finishMobile: (input: MobileRunInput, mode: MobileMode, projectDir: string, settings: MobileProjectSettings, plan: ExpoSkillsPlan | undefined) => Promise<void>;
65
+ export declare const finishMobile: (input: MobileRunInput, mode: MobileMode, projectDir: string, settings: MobileProjectSettings, plan: ExpoSkillsPlan | undefined, updateHint?: string) => Promise<void>;
@@ -10,7 +10,8 @@ import { withFetchOnce } from "../../asset/fetch-once.js";
10
10
  import { formatSdkNotAvailable, hasMobileRootDirs, listMobileRootDirs, } from "../../asset/root-selection.js";
11
11
  import { sanitizeDisplayText } from "../../utils/sanitize-text.js";
12
12
  import { selectAssetProvider } from "../asset-provider.js";
13
- import { buildSkillsAddRequest, expoSkillsAgentsFor, formatCommandLine, formatManualSkillsCommand, formatOutputTail, } from "../../utils/external-command.js";
13
+ import { buildSkillsAddRequest, expoSkillsAgentsFor, formatCommandLine, formatManualSkillsCommand, } from "../../utils/external-command.js";
14
+ import { formatOutputTail } from "../../utils/output-tail.js";
14
15
  import { generateMcpConfigsBestEffort, } from "../../utils/mcp-generate.js";
15
16
  import { syncDependencyArtifactsAndEnsureBestEffort, } from "../../utils/runtime-ensure.js";
16
17
  import { detectDefaultAgents } from "../../interactive/agent-detect.js";
@@ -227,7 +228,7 @@ const installExpoSkills = async (input, plan, projectDir, packageManager) => {
227
228
  }
228
229
  return undefined;
229
230
  };
230
- export const finishMobile = async (input, mode, projectDir, settings, plan) => {
231
+ export const finishMobile = async (input, mode, projectDir, settings, plan, updateHint) => {
231
232
  const { logger, locale } = input;
232
233
  let expoSkillsCommand;
233
234
  if (plan?.install) {
@@ -242,6 +243,8 @@ export const finishMobile = async (input, mode, projectDir, settings, plan) => {
242
243
  runImpl: input.runEnsure,
243
244
  });
244
245
  await generateMcpConfigsBestEffort(projectDir, logger, input.generateMcpConfigs);
246
+ if (updateHint !== undefined)
247
+ logger.info(updateHint);
245
248
  logger.success(getMessage("progress.complete", locale));
246
249
  printNextSteps({
247
250
  projectDir,
@@ -1,6 +1,7 @@
1
1
  import type { Logger } from "../core/logger.js";
2
2
  import { type Release } from "../core/catalog.js";
3
3
  import { type UpdaterProgressCallbacks } from "../asset/updater.js";
4
+ import { runInstallBuild } from "../asset/installer.js";
4
5
  import { type PresetSummary } from "../utils/preset-io.js";
5
6
  import { type generateMcpConfigs } from "../utils/mcp-generate.js";
6
7
  import { type runEnsure, type syncDependencyArtifacts } from "../utils/runtime-ensure.js";
@@ -27,6 +28,7 @@ export type RunSwitchDeps = {
27
28
  generateMcpConfigs?: typeof generateMcpConfigs;
28
29
  syncDependencyArtifacts?: typeof syncDependencyArtifacts;
29
30
  runEnsure?: typeof runEnsure;
31
+ runInstallBuild?: typeof runInstallBuild;
30
32
  };
31
33
  export declare const runSwitch: (deps: RunSwitchDeps) => Promise<void>;
32
34
  export declare const switchCommand: import("citty").CommandDef<{
@@ -184,8 +184,8 @@ const runSwitchInner = async (deps) => {
184
184
  if (!isMobileSettings(newSettings) &&
185
185
  !deps.skipInstall &&
186
186
  installTriggerChanged(changedPaths)) {
187
- const { success } = runInstallBuild(projectDir, newSettings.packageManager, buildProgressCallbacks(locale, logger));
188
- if (!success && summary.skippedSwitch.length > 0) {
187
+ const { outcome } = await (deps.runInstallBuild ?? runInstallBuild)(projectDir, newSettings.packageManager, { logger, locale, progress: buildProgressCallbacks(locale, logger) });
188
+ if (outcome === "failed" && summary.skippedSwitch.length > 0) {
189
189
  const list = summary.skippedSwitch
190
190
  .map((c) => ` - ${sanitizeDisplayText(c)}`)
191
191
  .join("\n");
@@ -1,6 +1,7 @@
1
1
  import { type PromptOptions, type ResolvedOptions } from "../core/validation.js";
2
2
  import type { Logger } from "../core/logger.js";
3
3
  import { type UpdaterProgressCallbacks } from "../asset/updater.js";
4
+ import { runInstallBuild } from "../asset/installer.js";
4
5
  import { type PresetSummary } from "../utils/preset-io.js";
5
6
  import { type generateMcpConfigs } from "../utils/mcp-generate.js";
6
7
  import { type pruneRuntimeIds, type runEnsure, type syncDependencyArtifacts } from "../utils/runtime-ensure.js";
@@ -64,6 +65,7 @@ export type RunUpdateDeps = {
64
65
  syncDependencyArtifacts?: typeof syncDependencyArtifacts;
65
66
  runEnsure?: typeof runEnsure;
66
67
  pruneRuntimeIds?: typeof pruneRuntimeIds;
68
+ runInstallBuild?: typeof runInstallBuild;
67
69
  };
68
70
  export declare const runUpdate: (deps: RunUpdateDeps) => Promise<void>;
69
71
  export type UpdateContext = {
@@ -497,7 +497,7 @@ const applyUpdate = async (a) => {
497
497
  summary.changedFileCount > 0 &&
498
498
  !hasConflicts &&
499
499
  !skipInstall) {
500
- runInstallBuild(projectDir, newSettings.packageManager, buildProgressCallbacks(locale, logger));
500
+ await (deps.runInstallBuild ?? runInstallBuild)(projectDir, newSettings.packageManager, { logger, locale, progress: buildProgressCallbacks(locale, logger) });
501
501
  }
502
502
  if (ensureReady && !skipInstall) {
503
503
  await runEnsureBestEffort(projectDir, logger, deps.runEnsure);
@@ -1,3 +1,11 @@
1
+ export type ConfigNotEditableReason = "symlink" | "notRegularFile" | "tooLarge" | "unreadable" | "invalidEncoding" | "keyOnHeaderLine";
2
+ export declare class ConfigNotEditableError extends Error {
3
+ readonly configPath: string;
4
+ readonly reason: ConfigNotEditableReason;
5
+ constructor(configPath: string, reason: ConfigNotEditableReason);
6
+ }
7
+ export declare const isConfigNotEditableError: (err: unknown) => err is ConfigNotEditableError;
1
8
  export declare const readConfigValue: (configPath: string, section: string, key: string) => Promise<string | undefined>;
2
- export declare const parseConfigBool: (value: string | undefined, fallback: boolean) => boolean;
3
- export declare const writeConfigValue: (configPath: string, section: string, key: string, value: string) => Promise<void>;
9
+ export declare const parseGitBool: (value: string | null) => boolean | undefined;
10
+ export declare const readConfigBool: (configPath: string, section: string, key: string) => Promise<boolean>;
11
+ export declare const deleteConfigKey: (configPath: string, section: string, key: string) => Promise<boolean>;
@@ -1,28 +1,72 @@
1
1
  import { randomBytes } from "node:crypto";
2
- import { lstat, rename, writeFile } from "node:fs/promises";
3
- import { readTextFileCapped } from "./read-capped.js";
4
- const SECTION_PATTERN = /^\s*\[([A-Za-z0-9.-]+)(\s+"(?:[^"\\]|\\.)*")?\]\s*(?:[#;].*)?$/;
5
- const KEY_PATTERN = /^\s*([A-Za-z][A-Za-z0-9-]*)\s*(?:=\s*(.*))?$/;
2
+ import { chmod, lstat, rename, unlink, writeFile } from "node:fs/promises";
3
+ import { readFileCapped, readTextFileCapped } from "./read-capped.js";
4
+ const SECTION_HEAD = /^\s*\[([A-Za-z0-9.-]+)(\s+"(?:[^"\\]|\\[\s\S])*")?\]/;
5
+ const KEY_PATTERN = /^\s*([A-Za-z][A-Za-z0-9-]*)\s*(?:=[ \t\r]*([\s\S]*))?$/;
6
+ const BLANK_OR_COMMENT = /^\s*(?:[#;][\s\S]*)?$/;
7
+ const parseSectionHeader = (line) => {
8
+ let match = SECTION_HEAD.exec(line);
9
+ if (match === null)
10
+ return null;
11
+ let rest = line.slice(match[0].length);
12
+ for (let next = SECTION_HEAD.exec(rest); next !== null; next = SECTION_HEAD.exec(rest)) {
13
+ match = next;
14
+ rest = rest.slice(next[0].length);
15
+ }
16
+ return {
17
+ name: match[1].toLowerCase(),
18
+ plain: match[2] === undefined,
19
+ rest: BLANK_OR_COMMENT.test(rest) ? undefined : rest,
20
+ };
21
+ };
22
+ export class ConfigNotEditableError extends Error {
23
+ configPath;
24
+ reason;
25
+ constructor(configPath, reason) {
26
+ super(`config file is not editable (${reason}): ${configPath}`);
27
+ this.configPath = configPath;
28
+ this.reason = reason;
29
+ this.name = "ConfigNotEditableError";
30
+ }
31
+ }
32
+ export const isConfigNotEditableError = (err) => err instanceof ConfigNotEditableError;
6
33
  const MAX_CONFIG_BYTES = 1024 * 1024;
7
- const MAX_CONTINUATIONS = 100;
8
- const endsWithContinuation = (line) => {
9
- let backslashes = 0;
10
- for (let i = line.length - 1; i >= 0 && line[i] === "\\"; i--)
11
- backslashes++;
12
- return backslashes % 2 === 1;
34
+ const scanContinuation = (line, inQuote) => {
35
+ let quoted = inQuote;
36
+ for (let i = 0; i < line.length; i++) {
37
+ const ch = line[i];
38
+ if (ch === "\\") {
39
+ if (i === line.length - 1)
40
+ return { continues: true, inQuote: quoted };
41
+ i++;
42
+ continue;
43
+ }
44
+ if (ch === '"') {
45
+ quoted = !quoted;
46
+ continue;
47
+ }
48
+ if (!quoted && (ch === "#" || ch === ";"))
49
+ break;
50
+ }
51
+ return { continues: false, inQuote: quoted };
13
52
  };
14
53
  const logicalLines = (content) => {
15
- const physical = content.replace(/^\uFEFF/, "").split(/\r\n|\n|\r/);
54
+ const physical = content
55
+ .replace(/^\uFEFF/, "")
56
+ .split("\n")
57
+ .map((line) => line.replace(/\r$/, ""));
16
58
  const lines = [];
17
59
  for (let i = 0; i < physical.length; i++) {
60
+ const parts = [];
18
61
  let line = physical[i];
19
- let joins = 0;
20
- while (endsWithContinuation(line) &&
21
- i + 1 < physical.length &&
22
- ++joins <= MAX_CONTINUATIONS) {
23
- line = line.slice(0, -1) + physical[++i];
62
+ let state = scanContinuation(line, false);
63
+ while (state.continues && i + 1 < physical.length) {
64
+ parts.push(line.slice(0, -1));
65
+ line = physical[++i];
66
+ state = scanContinuation(line, state.inQuote);
24
67
  }
25
- lines.push(line);
68
+ parts.push(line);
69
+ lines.push(parts.join(""));
26
70
  }
27
71
  return lines;
28
72
  };
@@ -49,14 +93,14 @@ const parseValue = (raw) => {
49
93
  if (!inQuote && (ch === "#" || ch === ";"))
50
94
  break;
51
95
  value += ch;
52
- if (!inQuote && (ch === " " || ch === "\t"))
96
+ if (!inQuote && (ch === " " || ch === "\t" || ch === "\r"))
53
97
  trailingSpaces++;
54
98
  else
55
99
  trailingSpaces = 0;
56
100
  }
57
101
  return trailingSpaces > 0 ? value.slice(0, -trailingSpaces) : value;
58
102
  };
59
- export const readConfigValue = async (configPath, section, key) => {
103
+ const readConfigEntry = async (configPath, section, key) => {
60
104
  const content = await readTextFileCapped(configPath, MAX_CONFIG_BYTES);
61
105
  if (content === null)
62
106
  return undefined;
@@ -65,114 +109,153 @@ export const readConfigValue = async (configPath, section, key) => {
65
109
  let inTargetSection = false;
66
110
  let result;
67
111
  for (const line of logicalLines(content)) {
68
- const sectionMatch = SECTION_PATTERN.exec(line);
69
- if (sectionMatch !== null) {
70
- inTargetSection =
71
- sectionMatch[1].toLowerCase() === sectionLower &&
72
- sectionMatch[2] === undefined;
73
- continue;
112
+ let body = line;
113
+ const header = parseSectionHeader(line);
114
+ if (header !== null) {
115
+ inTargetSection = header.name === sectionLower && header.plain;
116
+ if (header.rest === undefined)
117
+ continue;
118
+ body = header.rest;
74
119
  }
75
120
  if (!inTargetSection)
76
121
  continue;
77
- const keyMatch = KEY_PATTERN.exec(line);
122
+ const keyMatch = KEY_PATTERN.exec(body);
78
123
  if (keyMatch === null || keyMatch[1].toLowerCase() !== keyLower)
79
124
  continue;
80
- result = keyMatch[2] === undefined ? "" : parseValue(keyMatch[2]);
125
+ result = { value: keyMatch[2] === undefined ? null : parseValue(keyMatch[2]) };
81
126
  }
82
127
  return result;
83
128
  };
84
- export const parseConfigBool = (value, fallback) => {
85
- if (value === undefined)
86
- return fallback;
87
- const lower = value.toLowerCase();
88
- if (["", "true", "yes", "on", "1"].includes(lower))
129
+ export const readConfigValue = async (configPath, section, key) => {
130
+ const entry = await readConfigEntry(configPath, section, key);
131
+ return entry === undefined ? undefined : (entry.value ?? "");
132
+ };
133
+ const UNIT_FACTORS = {
134
+ "": 1,
135
+ k: 1024,
136
+ m: 1024 * 1024,
137
+ g: 1024 * 1024 * 1024,
138
+ };
139
+ const INT_MAX = 2147483647;
140
+ const INT_MIN = -2147483648;
141
+ const parseGitInt = (value) => {
142
+ const match = /^[\t\n\v\f\r ]*([+-]?)(0[xX][0-9a-fA-F]+|0[0-7]*|[1-9][0-9]*)([kKmMgG]?)$/.exec(value);
143
+ if (match === null)
144
+ return undefined;
145
+ const [, sign, digits, unit] = match;
146
+ const magnitude = /^0[xX]/.test(digits)
147
+ ? Number.parseInt(digits.slice(2), 16)
148
+ : digits.startsWith("0")
149
+ ? Number.parseInt(digits, 8)
150
+ : Number.parseInt(digits, 10);
151
+ const signed = sign === "-" ? -magnitude : magnitude;
152
+ const factor = UNIT_FACTORS[unit.toLowerCase()];
153
+ if (signed > Math.trunc(INT_MAX / factor) || signed < Math.trunc(INT_MIN / factor)) {
154
+ return undefined;
155
+ }
156
+ return signed * factor;
157
+ };
158
+ export const parseGitBool = (value) => {
159
+ if (value === null)
160
+ return true;
161
+ if (value === "")
162
+ return false;
163
+ if (/^(?:true|yes|on)$/i.test(value))
89
164
  return true;
90
- if (["false", "no", "off", "0"].includes(lower))
165
+ if (/^(?:false|no|off)$/i.test(value))
91
166
  return false;
92
- return fallback;
167
+ const number = parseGitInt(value);
168
+ return number === undefined ? undefined : number !== 0;
169
+ };
170
+ export const readConfigBool = async (configPath, section, key) => {
171
+ const entry = await readConfigEntry(configPath, section, key);
172
+ return entry !== undefined && parseGitBool(entry.value) === true;
93
173
  };
94
174
  const isValidSectionName = (name) => /^[A-Za-z0-9.-]+$/.test(name);
95
175
  const isValidKeyName = (name) => /^[A-Za-z][A-Za-z0-9-]*$/.test(name);
96
- const formatValue = (value) => {
97
- if (/[\0-\x08\x0b-\x1f\x7f]/.test(value)) {
98
- throw new Error("config value contains unsupported control characters");
99
- }
100
- return /[\s#;"\\]/.test(value)
101
- ? `"${value
102
- .replace(/\\/g, "\\\\")
103
- .replace(/"/g, '\\"')
104
- .replace(/\n/g, "\\n")
105
- .replace(/\t/g, "\\t")}"`
106
- : value;
176
+ const replaceConfigFile = async (configPath, body, mode) => {
177
+ const tmpPath = `${configPath}.accel-${randomBytes(4).toString("hex")}.tmp`;
178
+ try {
179
+ await writeFile(tmpPath, body, { encoding: "utf-8", flag: "wx", mode });
180
+ await chmod(tmpPath, mode);
181
+ await rename(tmpPath, configPath);
182
+ }
183
+ catch (err) {
184
+ await unlink(tmpPath).catch(() => { });
185
+ throw err;
186
+ }
107
187
  };
108
- export const writeConfigValue = async (configPath, section, key, value) => {
188
+ export const deleteConfigKey = async (configPath, section, key) => {
109
189
  if (!isValidSectionName(section) || !isValidKeyName(key)) {
110
190
  throw new Error(`invalid config section/key: [${section}] ${key}`);
111
191
  }
112
- let content = "";
113
192
  const stats = await lstat(configPath).catch((err) => {
114
193
  if (err.code === "ENOENT")
115
194
  return null;
116
195
  throw err;
117
196
  });
118
- if (stats !== null) {
119
- const existing = await readTextFileCapped(configPath, MAX_CONFIG_BYTES);
120
- if (existing === null) {
121
- throw new Error(`config file is not editable: ${configPath}`);
122
- }
123
- content = existing;
197
+ if (stats === null)
198
+ return false;
199
+ if (stats.isSymbolicLink()) {
200
+ throw new ConfigNotEditableError(configPath, "symlink");
201
+ }
202
+ if (!stats.isFile()) {
203
+ throw new ConfigNotEditableError(configPath, "notRegularFile");
204
+ }
205
+ if (stats.size > MAX_CONFIG_BYTES) {
206
+ throw new ConfigNotEditableError(configPath, "tooLarge");
207
+ }
208
+ const bytes = await readFileCapped(configPath, MAX_CONFIG_BYTES);
209
+ if (bytes === null) {
210
+ throw new ConfigNotEditableError(configPath, "unreadable");
211
+ }
212
+ const content = bytes.toString("utf-8");
213
+ if (!Buffer.from(content, "utf-8").equals(bytes)) {
214
+ throw new ConfigNotEditableError(configPath, "invalidEncoding");
124
215
  }
125
216
  const sectionLower = section.toLowerCase();
126
217
  const keyLower = key.toLowerCase();
127
- const newLine = `\t${key} = ${formatValue(value)}`;
128
218
  const physical = content.split("\n");
219
+ const kept = [];
129
220
  let inTargetSection = false;
130
221
  let continuation = false;
131
- let replaceAt = -1;
132
- let insertAfter = -1;
133
- for (let i = 0; i < physical.length; i++) {
134
- const line = physical[i].replace(/\r$/, "");
222
+ let inQuote = false;
223
+ let deleting = false;
224
+ let removed = 0;
225
+ for (const raw of physical) {
226
+ const line = raw.replace(/\r$/, "");
135
227
  if (continuation) {
136
- continuation = endsWithContinuation(line);
228
+ ({ continues: continuation, inQuote } = scanContinuation(line, inQuote));
229
+ if (!deleting)
230
+ kept.push(raw);
137
231
  continue;
138
232
  }
139
- continuation = endsWithContinuation(line);
140
- const sectionMatch = SECTION_PATTERN.exec(line);
141
- if (sectionMatch !== null) {
142
- const isTarget = sectionMatch[1].toLowerCase() === sectionLower &&
143
- sectionMatch[2] === undefined;
144
- if (isTarget && insertAfter === -1)
145
- insertAfter = i;
146
- inTargetSection = isTarget;
233
+ ({ continues: continuation, inQuote } = scanContinuation(line, false));
234
+ deleting = false;
235
+ const header = parseSectionHeader(line);
236
+ if (header !== null) {
237
+ inTargetSection = header.name === sectionLower && header.plain;
238
+ const keyMatch = inTargetSection && header.rest !== undefined
239
+ ? KEY_PATTERN.exec(header.rest)
240
+ : null;
241
+ if (keyMatch !== null && keyMatch[1].toLowerCase() === keyLower) {
242
+ throw new ConfigNotEditableError(configPath, "keyOnHeaderLine");
243
+ }
244
+ kept.push(raw);
147
245
  continue;
148
246
  }
149
- if (!inTargetSection || replaceAt !== -1)
150
- continue;
151
- const keyMatch = KEY_PATTERN.exec(line);
152
- if (keyMatch !== null && keyMatch[1].toLowerCase() === keyLower) {
153
- replaceAt = i;
247
+ if (inTargetSection) {
248
+ const keyMatch = KEY_PATTERN.exec(line);
249
+ if (keyMatch !== null && keyMatch[1].toLowerCase() === keyLower) {
250
+ deleting = true;
251
+ removed++;
252
+ continue;
253
+ }
154
254
  }
255
+ kept.push(raw);
155
256
  }
156
- let lines;
157
- if (replaceAt !== -1) {
158
- lines = [...physical];
159
- lines[replaceAt] = newLine;
160
- }
161
- else if (insertAfter !== -1) {
162
- lines = [...physical];
163
- lines.splice(insertAfter + 1, 0, newLine);
164
- }
165
- else {
166
- lines = [...physical];
167
- if (lines.length > 0 && lines[lines.length - 1] === "")
168
- lines.pop();
169
- if (lines.length === 1 && lines[0] === "")
170
- lines = [];
171
- lines.push(`[${section}]`, newLine);
172
- }
173
- const text = lines.join("\n");
174
- const body = text.endsWith("\n") ? text : `${text}\n`;
175
- const tmpPath = `${configPath}.accel-${randomBytes(4).toString("hex")}.tmp`;
176
- await writeFile(tmpPath, body, "utf-8");
177
- await rename(tmpPath, configPath);
257
+ if (removed === 0)
258
+ return false;
259
+ await replaceConfigFile(configPath, kept.join("\n"), stats.mode & 0o7777);
260
+ return true;
178
261
  };
@@ -0,0 +1,17 @@
1
+ export type ConfigScope = "user" | "local" | "worktree";
2
+ export type ScopedConfigValue = {
3
+ scope: ConfigScope;
4
+ path: string;
5
+ value: string;
6
+ };
7
+ export type UserConfigLocation = {
8
+ home: string;
9
+ xdgConfig: string;
10
+ paths: string[];
11
+ };
12
+ export declare const resolveUserConfigPaths: (env: NodeJS.ProcessEnv) => UserConfigLocation;
13
+ export declare const expandTilde: (path: string, home: string) => string;
14
+ export declare const readScopedConfigValues: (dirs: {
15
+ gitDir: string;
16
+ commonDir: string;
17
+ }, section: string, key: string, env: NodeJS.ProcessEnv) => Promise<ScopedConfigValue[]>;
@@ -0,0 +1,33 @@
1
+ import { homedir } from "node:os";
2
+ import { join, parse, resolve } from "node:path";
3
+ import { readConfigBool, readConfigValue } from "./config-file.js";
4
+ export const resolveUserConfigPaths = (env) => {
5
+ const envHome = env["HOME"];
6
+ const home = envHome === undefined ? homedir() : envHome === "" ? parse(resolve("/")).root : envHome;
7
+ const xdgConfig = env["XDG_CONFIG_HOME"] !== undefined && env["XDG_CONFIG_HOME"] !== ""
8
+ ? env["XDG_CONFIG_HOME"]
9
+ : join(home, ".config");
10
+ const globalOverride = env["GIT_CONFIG_GLOBAL"];
11
+ const paths = globalOverride !== undefined && globalOverride !== ""
12
+ ? [globalOverride]
13
+ : [join(xdgConfig, "git", "config"), join(home, ".gitconfig")];
14
+ return { home, xdgConfig, paths };
15
+ };
16
+ export const expandTilde = (path, home) => path === "~" ? home : path.startsWith("~/") ? join(home, path.slice(2)) : path;
17
+ export const readScopedConfigValues = async (dirs, section, key, env) => {
18
+ const found = [];
19
+ const collect = async (scope, path) => {
20
+ const value = await readConfigValue(path, section, key);
21
+ if (value !== undefined)
22
+ found.push({ scope, path, value });
23
+ };
24
+ for (const path of resolveUserConfigPaths(env).paths) {
25
+ await collect("user", path);
26
+ }
27
+ const localPath = join(dirs.commonDir, "config");
28
+ await collect("local", localPath);
29
+ if (await readConfigBool(localPath, "extensions", "worktreeConfig")) {
30
+ await collect("worktree", join(dirs.gitDir, "config.worktree"));
31
+ }
32
+ return found;
33
+ };
@@ -1,5 +1,5 @@
1
1
  import { createHash } from "node:crypto";
2
- import { readFile, stat } from "node:fs/promises";
2
+ import { open, stat } from "node:fs/promises";
3
3
  import { join } from "node:path";
4
4
  const HEADER_SIZE = 12;
5
5
  const CHECKSUM_SIZE = 20;
@@ -92,9 +92,28 @@ export const readGitIndex = async (gitDir) => {
92
92
  let buf;
93
93
  let indexMtimeSec;
94
94
  try {
95
- const stats = await stat(indexPath);
96
- indexMtimeSec = Math.floor(stats.mtimeMs / 1000);
97
- buf = await readFile(indexPath);
95
+ if (!(await stat(indexPath)).isFile())
96
+ return null;
97
+ const handle = await open(indexPath, "r");
98
+ try {
99
+ const stats = await handle.stat();
100
+ if (!stats.isFile())
101
+ return null;
102
+ indexMtimeSec = Math.floor(stats.mtimeMs / 1000);
103
+ const size = Number(stats.size);
104
+ buf = Buffer.alloc(size);
105
+ let pos = 0;
106
+ while (pos < size) {
107
+ const { bytesRead } = await handle.read(buf, pos, size - pos, pos);
108
+ if (bytesRead === 0)
109
+ break;
110
+ pos += bytesRead;
111
+ }
112
+ buf = buf.subarray(0, pos);
113
+ }
114
+ finally {
115
+ await handle.close().catch(() => { });
116
+ }
98
117
  }
99
118
  catch (err) {
100
119
  if (err.code === "ENOENT") {
@@ -1 +1,2 @@
1
1
  export declare const readTextFileCapped: (path: string, maxBytes: number) => Promise<string | null>;
2
+ export declare const readFileCapped: (path: string, maxBytes: number) => Promise<Buffer | null>;
@@ -1,7 +1,10 @@
1
- import { open } from "node:fs/promises";
2
- export const readTextFileCapped = async (path, maxBytes) => {
1
+ import { open, stat } from "node:fs/promises";
2
+ export const readTextFileCapped = async (path, maxBytes) => (await readFileCapped(path, maxBytes))?.toString("utf-8") ?? null;
3
+ export const readFileCapped = async (path, maxBytes) => {
3
4
  let handle;
4
5
  try {
6
+ if (!(await stat(path)).isFile())
7
+ return null;
5
8
  handle = await open(path, "r");
6
9
  const stats = await handle.stat();
7
10
  if (!stats.isFile() || stats.size > maxBytes)
@@ -15,7 +18,7 @@ export const readTextFileCapped = async (path, maxBytes) => {
15
18
  break;
16
19
  pos += bytesRead;
17
20
  }
18
- return buf.subarray(0, pos).toString("utf-8");
21
+ return buf.subarray(0, pos);
19
22
  }
20
23
  catch {
21
24
  return null;
@@ -0,0 +1,26 @@
1
+ export type RepoLayout = {
2
+ gitDir: string;
3
+ commonDir: string;
4
+ worktreeRoot: string;
5
+ projectRel: string;
6
+ linkedWorktree: boolean;
7
+ };
8
+ export type RepoDiscovery = {
9
+ kind: "none";
10
+ } | {
11
+ kind: "unverified";
12
+ gitPath: string;
13
+ worktreeRoot: string;
14
+ layout?: RepoLayout;
15
+ } | {
16
+ kind: "found";
17
+ layout: RepoLayout;
18
+ };
19
+ export type DiscoverOptions = {
20
+ env?: NodeJS.ProcessEnv;
21
+ };
22
+ export declare const comparablePath: (path: string) => string;
23
+ export declare const isOutsideRelative: (rel: string) => boolean;
24
+ export declare const parseEnvBool: (value: string | undefined) => boolean;
25
+ export declare const parseCeilingDirectories: (value: string | undefined, start: string) => Promise<Set<string>>;
26
+ export declare const discoverRepository: (projectDir: string, opts?: DiscoverOptions) => Promise<RepoDiscovery>;