pi-charset 0.1.4 → 0.1.6
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/CHANGELOG.md +64 -0
- package/CHANGELOG.zh-CN.md +64 -0
- package/CONTRIBUTING.md +33 -0
- package/CONTRIBUTING.zh-CN.md +33 -0
- package/README.md +35 -6
- package/README.zh-CN.md +35 -6
- package/docs/ACCEPTANCE.md +30 -2
- package/docs/COMPATIBILITY.md +6 -1
- package/docs/CONFIG-GUIDE.md +4 -1
- package/docs/DESIGN-REVIEW.md +54 -0
- package/docs/EDIT-ENGINE.md +46 -0
- package/docs/EDITING-PLAN.md +16 -0
- package/docs/MCP-AND-MULTI-AGENT.md +111 -0
- package/docs/MODEL-EVAL.md +92 -0
- package/docs/PROGRESS.md +311 -0
- package/docs/RELEASING.md +4 -2
- package/docs/zh-CN/ACCEPTANCE.md +30 -2
- package/docs/zh-CN/COMPATIBILITY.md +6 -1
- package/docs/zh-CN/CONFIG-GUIDE.md +4 -1
- package/docs/zh-CN/DESIGN-REVIEW.md +54 -0
- package/docs/zh-CN/EDIT-ENGINE.md +46 -0
- package/docs/zh-CN/EDITING-PLAN.md +415 -0
- package/docs/zh-CN/MCP-AND-MULTI-AGENT.md +111 -0
- package/docs/zh-CN/MODEL-EVAL.md +92 -0
- package/docs/zh-CN/PROGRESS.md +311 -0
- package/docs/zh-CN/RELEASING.md +4 -2
- package/docs/zh-CN/editing-plan-architecture.png +0 -0
- package/examples/all-utf8.jsonc +1 -0
- package/examples/embedded-c.jsonc +1 -0
- package/examples/legacy-java-web.jsonc +1 -0
- package/examples/mixed-repo.jsonc +1 -0
- package/package.json +14 -2
- package/prompts/charset-setup.md +3 -3
- package/schema/pi-charset.schema.json +118 -0
- package/skills/charset-rules/SKILL.md +8 -2
- package/src/config.ts +524 -185
- package/src/edit/apply-patch-core.ts +275 -0
- package/src/edit/apply-patch.ts +78 -0
- package/src/edit/diagnostics.ts +48 -0
- package/src/edit/hashline.ts +438 -0
- package/src/edit/patch.ts +655 -0
- package/src/edit/paths.ts +42 -0
- package/src/edit/plan.ts +107 -0
- package/src/edit/tool.ts +451 -0
- package/src/edit-preview.ts +48 -277
- package/src/encoding/classify.ts +235 -65
- package/src/encoding/common-scripts.ts +66 -0
- package/src/encoding/converter.ts +114 -16
- package/src/encoding/fast-codec.ts +469 -0
- package/src/encoding/file-stamp.ts +55 -0
- package/src/encoding/line-endings.ts +66 -73
- package/src/encoding/mime.ts +12 -43
- package/src/encoding/stream-transcode.ts +135 -30
- package/src/grep-core.ts +687 -0
- package/src/grep.ts +25 -463
- package/src/index.ts +458 -49
- package/src/journal.ts +459 -0
- package/src/maintenance.ts +375 -0
- package/src/mcp/server.ts +651 -0
- package/src/operations.ts +759 -127
- package/src/read-view.ts +924 -0
- package/src/resolve.ts +113 -101
- package/src/scaffold.ts +9 -4
- package/src/shell-guard.ts +617 -0
- package/src/shell.ts +85 -33
- package/src/sysnote.ts +4 -6
- package/src/version.ts +1 -1
- package/tools/charset-core.mjs +251 -0
- package/tools/pi-charset-cli.mjs +369 -0
- package/tools/pi-charset-mcp.mjs +103 -0
- package/tools/scan-encoding.mjs +30 -28
package/src/config.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// Configuration loader, validator, and zero-config sibling inference (.pi-charset.json).
|
|
2
|
-
import { readdirSync, readFileSync, statSync } from "node:fs";
|
|
3
|
-
import { readFile, stat } from "node:fs/promises";
|
|
2
|
+
import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
|
|
3
|
+
import { readdir, readFile, stat } from "node:fs/promises";
|
|
4
|
+
import * as os from "node:os";
|
|
4
5
|
import * as path from "node:path";
|
|
5
6
|
import micromatch from "micromatch";
|
|
6
7
|
import { normalizePathKey } from "./path-key";
|
|
@@ -9,36 +10,39 @@ import {
|
|
|
9
10
|
isGBEncoding,
|
|
10
11
|
isSingleByteEncoding,
|
|
11
12
|
isStatefulEncoding,
|
|
13
|
+
isSupportedEncoding,
|
|
12
14
|
normalizeEncoding,
|
|
13
15
|
} from "./encoding/converter";
|
|
14
|
-
import { classifyBuffer, DEFAULT_AUTO_CANDIDATES } from "./encoding/classify";
|
|
15
|
-
import {
|
|
16
|
+
import { classifyBuffer, decideFamilyFromBuffers, DEFAULT_AUTO_CANDIDATES, exactRoundTrip, familyOf, preferFamily, quickKind, type Verdict } from "./encoding/classify";
|
|
17
|
+
import { fileStampKey, sameFileStamp, stampFromStat, type FileStamp } from "./encoding/file-stamp";
|
|
18
|
+
import { detectLineEndingKind, type LineEndingStyle } from "./encoding/line-endings";
|
|
16
19
|
|
|
17
20
|
export const CONFIG_FILENAME = ".pi-charset.json";
|
|
18
21
|
|
|
19
|
-
function resolveConfigPathSync(dir: string): { path: string;
|
|
22
|
+
function resolveConfigPathSync(dir: string): { path: string; stamp: FileStamp } | null {
|
|
20
23
|
const p = path.join(dir, CONFIG_FILENAME);
|
|
21
|
-
try {
|
|
22
|
-
const st = statSync(p);
|
|
23
|
-
return { path: p, stat: st };
|
|
24
|
-
} catch {
|
|
25
|
-
return null;
|
|
26
|
-
}
|
|
24
|
+
try { return { path: p, stamp: stampFromStat(statSync(p)) }; } catch { return null; }
|
|
27
25
|
}
|
|
28
26
|
|
|
29
|
-
async function resolveConfigPath(dir: string): Promise<{ path: string;
|
|
27
|
+
async function resolveConfigPath(dir: string): Promise<{ path: string; stamp: FileStamp } | null> {
|
|
30
28
|
const p = path.join(dir, CONFIG_FILENAME);
|
|
31
|
-
try {
|
|
32
|
-
const st = await stat(p);
|
|
33
|
-
return { path: p, stat: st };
|
|
34
|
-
} catch {
|
|
35
|
-
return null;
|
|
36
|
-
}
|
|
29
|
+
try { return { path: p, stamp: stampFromStat(await stat(p)) }; } catch { return null; }
|
|
37
30
|
}
|
|
38
31
|
|
|
39
32
|
export type ReadStrategy = "auto" | "config";
|
|
40
33
|
export type UnmappableStrategy = "error" | "escape" | "drop-to-gb18030";
|
|
41
34
|
export type NewFileLineEnding = "CRLF" | "LF";
|
|
35
|
+
export type ShellGuardMode = "block" | "warn" | "off";
|
|
36
|
+
export type LocaleMode = "auto" | "en" | "zh-CN";
|
|
37
|
+
|
|
38
|
+
/** Resolve active diagnostic/UI locale ("en" or "zh-CN"). Defaults to "zh-CN" unless configured or PI_CHARSET_LOCALE=en. */
|
|
39
|
+
export function resolveLocale(locale?: LocaleMode): "en" | "zh-CN" {
|
|
40
|
+
if (locale === "en" || locale === "zh-CN") return locale;
|
|
41
|
+
const env = (process.env.PI_CHARSET_LOCALE ?? "").trim().toLowerCase();
|
|
42
|
+
if (env === "en" || env.startsWith("en-") || env.startsWith("en_")) return "en";
|
|
43
|
+
if (env === "zh" || env.startsWith("zh-") || env.startsWith("zh_")) return "zh-CN";
|
|
44
|
+
return "zh-CN";
|
|
45
|
+
}
|
|
42
46
|
|
|
43
47
|
function normalizeNewFileLineEnding(raw: unknown, where: string, warnings: string[]): NewFileLineEnding | undefined {
|
|
44
48
|
if (raw === undefined) return undefined;
|
|
@@ -57,6 +61,8 @@ export interface OverrideRule {
|
|
|
57
61
|
unmappable?: UnmappableStrategy;
|
|
58
62
|
autoCandidates?: string[];
|
|
59
63
|
protectUtf8?: boolean;
|
|
64
|
+
/** Prefer configured non-UTF-8 CJK encoding over BOM-less UTF-8 when bytes satisfy both (guards short GBK headers). */
|
|
65
|
+
preferSourceOverUtf8?: boolean;
|
|
60
66
|
verifyWrite?: boolean;
|
|
61
67
|
newFileLineEnding?: NewFileLineEnding;
|
|
62
68
|
}
|
|
@@ -68,11 +74,21 @@ export interface EncodingConfig {
|
|
|
68
74
|
unmappable?: UnmappableStrategy;
|
|
69
75
|
verifyWrite?: boolean;
|
|
70
76
|
protectUtf8?: boolean;
|
|
77
|
+
/** Prefer configured non-UTF-8 CJK encoding over BOM-less UTF-8 when bytes satisfy both (guards short GBK headers). */
|
|
78
|
+
preferSourceOverUtf8?: boolean;
|
|
71
79
|
autoCandidates?: string[];
|
|
72
80
|
/** Shell output transcoding mode: false (default) | true/"auto" | explicit encoding name. */
|
|
73
81
|
transcodeBash?: BashTranscodeMode;
|
|
74
82
|
/** When transcodeBash is enabled, use the target file's own read encoding for single-file dump commands. */
|
|
75
83
|
bashFileDump?: boolean;
|
|
84
|
+
/** Opt-in: after a verified write or edit, commit only that file to git (Aider-style auto-commit). */
|
|
85
|
+
autoCommit?: boolean;
|
|
86
|
+
/** Opt-in: annotate text lines returned by read with `<line>:<2-hex>|` Hashline anchors. */
|
|
87
|
+
hashlines?: boolean;
|
|
88
|
+
/** Guard bash/powershell against encoding-corrupting file writes (python -c, iconv, sed -i, Set-Content, redirects). Default: "block". */
|
|
89
|
+
shellGuard?: ShellGuardMode;
|
|
90
|
+
/** Message locale for commands and write-gate diagnostics: "auto" | "en" | "zh-CN". */
|
|
91
|
+
locale?: LocaleMode;
|
|
76
92
|
newFileLineEnding?: NewFileLineEnding;
|
|
77
93
|
overrides?: OverrideRule[];
|
|
78
94
|
}
|
|
@@ -83,8 +99,7 @@ interface CacheEntry {
|
|
|
83
99
|
config: EncodingConfig;
|
|
84
100
|
configPath: string;
|
|
85
101
|
warnings: string[];
|
|
86
|
-
|
|
87
|
-
size: number;
|
|
102
|
+
stamp: FileStamp;
|
|
88
103
|
}
|
|
89
104
|
|
|
90
105
|
export interface FoundConfig {
|
|
@@ -104,11 +119,18 @@ export interface ResolvedConfig {
|
|
|
104
119
|
unmappable: UnmappableStrategy;
|
|
105
120
|
verifyWrite: boolean;
|
|
106
121
|
protectUtf8: boolean;
|
|
122
|
+
preferSourceOverUtf8?: boolean;
|
|
107
123
|
autoCandidates: string[];
|
|
108
124
|
force: boolean;
|
|
109
125
|
newFileLineEnding: NewFileLineEnding | null;
|
|
110
126
|
matchedPattern: string | null;
|
|
111
127
|
warnings: string[];
|
|
128
|
+
/** Opt-in Aider-style auto-commit after verified writes; see src/journal.ts. */
|
|
129
|
+
autoCommit?: boolean;
|
|
130
|
+
/** Opt-in Hashline `<line>:<hash>|` annotations on `read` output. */
|
|
131
|
+
hashlines?: boolean;
|
|
132
|
+
/** Resolved message locale for diagnostics. */
|
|
133
|
+
locale?: LocaleMode;
|
|
112
134
|
/** True when synthesized by zero-config adaptive inference without a .pi-charset.json file. */
|
|
113
135
|
adaptive?: boolean;
|
|
114
136
|
}
|
|
@@ -119,9 +141,13 @@ interface ConfigDefaults {
|
|
|
119
141
|
unmappable: UnmappableStrategy;
|
|
120
142
|
verifyWrite: boolean;
|
|
121
143
|
protectUtf8: boolean;
|
|
144
|
+
preferSourceOverUtf8?: boolean;
|
|
122
145
|
autoCandidates: string[];
|
|
123
146
|
transcodeBash: BashTranscodeMode;
|
|
124
147
|
bashFileDump: boolean;
|
|
148
|
+
autoCommit: boolean;
|
|
149
|
+
hashlines: boolean;
|
|
150
|
+
shellGuard: ShellGuardMode;
|
|
125
151
|
}
|
|
126
152
|
|
|
127
153
|
const DEFAULTS: ConfigDefaults = {
|
|
@@ -133,6 +159,9 @@ const DEFAULTS: ConfigDefaults = {
|
|
|
133
159
|
autoCandidates: [...DEFAULT_AUTO_CANDIDATES],
|
|
134
160
|
transcodeBash: false,
|
|
135
161
|
bashFileDump: true,
|
|
162
|
+
autoCommit: false,
|
|
163
|
+
hashlines: false,
|
|
164
|
+
shellGuard: "block",
|
|
136
165
|
};
|
|
137
166
|
|
|
138
167
|
const NARROW_CJK_ORDER = ["GBK", "Big5", "Shift_JIS", "EUC-KR", "EUC-JP", "GB18030"] as const;
|
|
@@ -142,17 +171,106 @@ const BINARY_SKIP_EXT = new Set([
|
|
|
142
171
|
]);
|
|
143
172
|
|
|
144
173
|
const dirCache = new Map<string, CacheEntry | null>();
|
|
174
|
+
const MAX_DIR_CACHE = 2000;
|
|
145
175
|
let _configGen = 0;
|
|
146
176
|
|
|
177
|
+
function setDirCache(key: string, value: CacheEntry | null): void {
|
|
178
|
+
const prev = dirCache.get(key);
|
|
179
|
+
const changed =
|
|
180
|
+
prev !== undefined &&
|
|
181
|
+
((prev === null) !== (value === null) ||
|
|
182
|
+
(prev !== null && value !== null && (prev.configPath !== value.configPath || !sameFileStamp(prev.stamp, value.stamp))));
|
|
183
|
+
if (dirCache.size >= MAX_DIR_CACHE && !dirCache.has(key)) dirCache.clear();
|
|
184
|
+
dirCache.set(key, value);
|
|
185
|
+
if (changed) {
|
|
186
|
+
siblingInference.clear();
|
|
187
|
+
_configGen++;
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
export interface RuntimeConfigDefaults {
|
|
192
|
+
sourceEncoding?: string;
|
|
193
|
+
writeEncoding?: string;
|
|
194
|
+
newFileLineEnding?: NewFileLineEnding;
|
|
195
|
+
preferSourceOverUtf8?: boolean;
|
|
196
|
+
protectUtf8?: boolean;
|
|
197
|
+
unmappable?: UnmappableStrategy;
|
|
198
|
+
hashlines?: boolean;
|
|
199
|
+
autoCommit?: boolean;
|
|
200
|
+
locale?: LocaleMode;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
let runtimeDefaults: RuntimeConfigDefaults | null = null;
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* Configure process-level defaults (used by `pi-charset-mcp` CLI flags and `PI_CHARSET_*` env vars)
|
|
207
|
+
* so users can run or pin encoding policies with zero `.pi-charset.json` files on disk.
|
|
208
|
+
*/
|
|
209
|
+
export function setRuntimeDefaults(defaults: RuntimeConfigDefaults | null): void {
|
|
210
|
+
if (!defaults || Object.values(defaults).every((v) => v === undefined)) {
|
|
211
|
+
runtimeDefaults = null;
|
|
212
|
+
} else {
|
|
213
|
+
const clean: RuntimeConfigDefaults = {};
|
|
214
|
+
if (defaults.sourceEncoding) clean.sourceEncoding = normalizeEncoding(defaults.sourceEncoding);
|
|
215
|
+
if (defaults.writeEncoding) clean.writeEncoding = normalizeEncoding(defaults.writeEncoding);
|
|
216
|
+
if (defaults.newFileLineEnding === "CRLF" || defaults.newFileLineEnding === "LF") {
|
|
217
|
+
clean.newFileLineEnding = defaults.newFileLineEnding;
|
|
218
|
+
}
|
|
219
|
+
if (typeof defaults.preferSourceOverUtf8 === "boolean") clean.preferSourceOverUtf8 = defaults.preferSourceOverUtf8;
|
|
220
|
+
if (typeof defaults.protectUtf8 === "boolean") clean.protectUtf8 = defaults.protectUtf8;
|
|
221
|
+
if (defaults.unmappable === "error" || defaults.unmappable === "escape" || defaults.unmappable === "drop-to-gb18030") {
|
|
222
|
+
clean.unmappable = defaults.unmappable;
|
|
223
|
+
}
|
|
224
|
+
if (typeof defaults.hashlines === "boolean") clean.hashlines = defaults.hashlines;
|
|
225
|
+
if (typeof defaults.autoCommit === "boolean") clean.autoCommit = defaults.autoCommit;
|
|
226
|
+
if (defaults.locale === "auto" || defaults.locale === "en" || defaults.locale === "zh-CN") {
|
|
227
|
+
clean.locale = defaults.locale;
|
|
228
|
+
}
|
|
229
|
+
runtimeDefaults = Object.keys(clean).length > 0 ? clean : null;
|
|
230
|
+
}
|
|
231
|
+
_configGen++;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
export function getRuntimeDefaults(): RuntimeConfigDefaults | null {
|
|
235
|
+
return runtimeDefaults;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
function runtimeFoundConfig(startDir: string): FoundConfig | null {
|
|
239
|
+
if (!runtimeDefaults?.sourceEncoding) return null;
|
|
240
|
+
const config: EncodingConfig = {
|
|
241
|
+
...DEFAULTS,
|
|
242
|
+
sourceEncoding: runtimeDefaults.sourceEncoding,
|
|
243
|
+
...(runtimeDefaults.writeEncoding ? { writeEncoding: runtimeDefaults.writeEncoding } : { writeEncoding: runtimeDefaults.sourceEncoding }),
|
|
244
|
+
...(runtimeDefaults.newFileLineEnding ? { newFileLineEnding: runtimeDefaults.newFileLineEnding } : {}),
|
|
245
|
+
...(runtimeDefaults.preferSourceOverUtf8 !== undefined ? { preferSourceOverUtf8: runtimeDefaults.preferSourceOverUtf8 } : {}),
|
|
246
|
+
...(runtimeDefaults.protectUtf8 !== undefined ? { protectUtf8: runtimeDefaults.protectUtf8 } : {}),
|
|
247
|
+
...(runtimeDefaults.unmappable ? { unmappable: runtimeDefaults.unmappable } : {}),
|
|
248
|
+
...(runtimeDefaults.hashlines !== undefined ? { hashlines: runtimeDefaults.hashlines } : {}),
|
|
249
|
+
...(runtimeDefaults.autoCommit !== undefined ? { autoCommit: runtimeDefaults.autoCommit } : {}),
|
|
250
|
+
...(runtimeDefaults.locale ? { locale: runtimeDefaults.locale } : {}),
|
|
251
|
+
};
|
|
252
|
+
return { config, configDir: path.resolve(startDir), configPath: "(runtime CLI/env flags)", warnings: [] };
|
|
253
|
+
}
|
|
254
|
+
|
|
147
255
|
export function configGeneration(): number {
|
|
148
256
|
return _configGen;
|
|
149
257
|
}
|
|
150
258
|
|
|
151
259
|
export function clearConfigCache(): void {
|
|
152
260
|
dirCache.clear();
|
|
261
|
+
siblingInference.clear();
|
|
262
|
+
projectHintsCache.clear();
|
|
153
263
|
_configGen++;
|
|
154
264
|
}
|
|
155
265
|
|
|
266
|
+
/** Invalidate cached zero-config sibling inference for one directory after any file mutation inside it. */
|
|
267
|
+
export function invalidateSiblingInference(dir: string): void {
|
|
268
|
+
const prefix = normalizePathKey(path.resolve(dir)) + "\u0000";
|
|
269
|
+
for (const key of [...siblingInference.keys()]) {
|
|
270
|
+
if (key.startsWith(prefix)) siblingInference.delete(key);
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
|
|
156
274
|
/** Pick the narrowest encoding from NARROW_CJK_ORDER that appears in candidates (e.g. GBK over GB18030 when 2-byte clean). */
|
|
157
275
|
export function pickNarrowestCandidate(candidates: string[], fallback = "GB18030"): string {
|
|
158
276
|
for (const pref of NARROW_CJK_ORDER) {
|
|
@@ -167,18 +285,19 @@ function sameExtGroup(extA: string, extB: string): boolean {
|
|
|
167
285
|
return cFamily.has(extA) && cFamily.has(extB);
|
|
168
286
|
}
|
|
169
287
|
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
288
|
+
// Inference over a directory repeats for every read of an ASCII file and every new-file write, so it is
|
|
289
|
+
// cached per (directory, extension group, target name) and revalidated against the selected siblings'
|
|
290
|
+
// unified FileStamp (dev, ino, size, mtimeMs, ctimeMs).
|
|
291
|
+
const siblingInference = new Map<string, { signature: string; encoding: string; eol: NewFileLineEnding | null }>();
|
|
292
|
+
|
|
293
|
+
type SiblingCandidate = { name: string; abs: string; stamp: FileStamp };
|
|
294
|
+
|
|
295
|
+
function selectSiblingEntries(
|
|
296
|
+
entries: readonly import("node:fs").Dirent[],
|
|
297
|
+
targetExt: string,
|
|
298
|
+
excludeBase: string,
|
|
299
|
+
): import("node:fs").Dirent[] {
|
|
300
|
+
return entries
|
|
182
301
|
.filter((e) => e.isFile() && e.name !== excludeBase && !e.name.startsWith(".") && !BINARY_SKIP_EXT.has(path.extname(e.name).toLowerCase()))
|
|
183
302
|
.sort((a, b) => {
|
|
184
303
|
const aMatch = sameExtGroup(path.extname(a.name).toLowerCase(), targetExt) ? 0 : 1;
|
|
@@ -186,180 +305,403 @@ function inferFromSiblings(dir: string, targetExt: string, excludeBase: string):
|
|
|
186
305
|
return aMatch - bMatch || a.name.localeCompare(b.name);
|
|
187
306
|
})
|
|
188
307
|
.slice(0, 16);
|
|
308
|
+
}
|
|
189
309
|
|
|
310
|
+
function scoreSiblingBuffers(buffers: readonly Buffer[]): { encoding: string; eol: NewFileLineEnding | null; hasSignal: boolean } {
|
|
190
311
|
let cjkCount = 0;
|
|
191
312
|
let utf8Count = 0;
|
|
192
313
|
let crlfCount = 0;
|
|
193
314
|
let lfCount = 0;
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
for (const
|
|
197
|
-
const
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
if (st.size === 0 || st.size > 256 * 1024) continue;
|
|
205
|
-
let buf: Buffer;
|
|
206
|
-
try {
|
|
207
|
-
buf = readFileSync(p);
|
|
208
|
-
} catch {
|
|
315
|
+
let pending: Buffer[] = [];
|
|
316
|
+
let legacyTotal = 0;
|
|
317
|
+
for (const buf of buffers) {
|
|
318
|
+
const quick = quickKind(buf);
|
|
319
|
+
if (quick) {
|
|
320
|
+
if (quick.kind === "binary" || quick.kind === "unknown") continue;
|
|
321
|
+
const eol = detectLineEndingKind(buf);
|
|
322
|
+
if (eol === "CRLF") crlfCount++;
|
|
323
|
+
else if (eol === "LF") lfCount++;
|
|
324
|
+
if (quick.kind === "utf8" || quick.kind === "utf8-bom") utf8Count++;
|
|
209
325
|
continue;
|
|
210
326
|
}
|
|
211
|
-
const v = classifyBuffer(buf, null);
|
|
212
|
-
if (v.kind === "binary" || v.kind === "unknown") continue;
|
|
213
327
|
const eol = detectLineEndingKind(buf);
|
|
214
328
|
if (eol === "CRLF") crlfCount++;
|
|
215
329
|
else if (eol === "LF") lfCount++;
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
330
|
+
pending.push(buf);
|
|
331
|
+
legacyTotal++;
|
|
332
|
+
}
|
|
333
|
+
// Candidates outside NARROW_CJK_ORDER still get tested, after the narrow ones, in their default order.
|
|
334
|
+
const candidates = [...NARROW_CJK_ORDER, ...DEFAULT_AUTO_CANDIDATES.filter((c) => !(NARROW_CJK_ORDER as readonly string[]).includes(c))];
|
|
335
|
+
// Score each sibling from its own first non-ASCII byte without concatenating raw multi-byte buffers.
|
|
336
|
+
const decision = pending.length
|
|
337
|
+
? decideFamilyFromBuffers(pending, new Set(candidates.map(familyOf)), 4096)
|
|
338
|
+
: { family: null, confident: false };
|
|
339
|
+
const ordered = decision.confident ? preferFamily(candidates, decision.family) : candidates;
|
|
340
|
+
let common: string | null = null;
|
|
341
|
+
for (const enc of ordered) {
|
|
342
|
+
if (!pending.length) break;
|
|
343
|
+
const remaining: Buffer[] = [];
|
|
344
|
+
for (const buf of pending) {
|
|
345
|
+
if (exactRoundTrip(buf, enc)) common = enc;
|
|
346
|
+
else remaining.push(buf);
|
|
221
347
|
}
|
|
348
|
+
pending = remaining;
|
|
222
349
|
}
|
|
350
|
+
// Legacy siblings still pending after every candidate are undecodable and ignored, as before.
|
|
351
|
+
cjkCount = legacyTotal - pending.length;
|
|
223
352
|
|
|
224
353
|
const dominantEol: NewFileLineEnding | null = crlfCount > lfCount ? "CRLF" : lfCount > crlfCount ? "LF" : null;
|
|
225
|
-
if (cjkCount
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
354
|
+
if (cjkCount === 0 && utf8Count === 0) return { encoding: "UTF-8", eol: null, hasSignal: false };
|
|
355
|
+
// Line endings are inherited only from legacy-encoded siblings; UTF-8 trees keep the host default.
|
|
356
|
+
return cjkCount > 0 && cjkCount >= utf8Count
|
|
357
|
+
? { encoding: common ?? "GB18030", eol: dominantEol, hasSignal: true }
|
|
358
|
+
: { encoding: "UTF-8", eol: null, hasSignal: true };
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
function siblingSignature(selected: readonly SiblingCandidate[]): string {
|
|
362
|
+
return selected.map((s) => `${s.name}:${fileStampKey(s.stamp)}`).join("|");
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
function storeSiblingInference(cacheKey: string, signature: string, result: { encoding: string; eol: NewFileLineEnding | null }): void {
|
|
366
|
+
if (siblingInference.size > 2000) siblingInference.clear();
|
|
367
|
+
siblingInference.set(cacheKey, { signature, encoding: result.encoding, eol: result.eol });
|
|
230
368
|
}
|
|
231
369
|
|
|
370
|
+
const MAX_PARENT_SIBLING_DEPTH = 3;
|
|
371
|
+
const NORMALIZED_TMPDIR = normalizePathKey(path.resolve(os.tmpdir()));
|
|
372
|
+
|
|
373
|
+
function isBoundaryDir(dir: string): boolean {
|
|
374
|
+
return normalizePathKey(path.resolve(dir)) === NORMALIZED_TMPDIR;
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
function hasGitRoot(dir: string): boolean {
|
|
378
|
+
try { return existsSync(path.join(dir, ".git")); } catch { return false; }
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
export interface ProjectHint {
|
|
382
|
+
readonly source: string;
|
|
383
|
+
readonly encoding?: string;
|
|
384
|
+
readonly lineEnding?: LineEndingStyle;
|
|
385
|
+
readonly detail: string;
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
const HINT_FILES = [".editorconfig", ".gitattributes", "pom.xml", "CMakeLists.txt"] as const;
|
|
389
|
+
const projectHintsCache = new Map<string, { sig: string; hints: ProjectHint[] }>();
|
|
390
|
+
|
|
232
391
|
/**
|
|
233
|
-
*
|
|
234
|
-
* -
|
|
235
|
-
* - New files and pure-ASCII files inherit the dominant encoding and line ending of sibling files in the same directory (defaulting to UTF-8).
|
|
392
|
+
* Inspect .editorconfig, .gitattributes, pom.xml, and CMakeLists.txt in `dir` for declared encoding/EOL conventions.
|
|
393
|
+
* Stamp-validated cache avoids re-reading or re-parsing unchanged hint files across repeated zero-config lookups.
|
|
236
394
|
*/
|
|
237
|
-
export function
|
|
238
|
-
const
|
|
239
|
-
|
|
240
|
-
|
|
395
|
+
export function detectProjectHints(dir: string): ProjectHint[] {
|
|
396
|
+
const absDir = path.resolve(dir);
|
|
397
|
+
const key = normalizePathKey(absDir);
|
|
398
|
+
const stamps: (FileStamp | null)[] = HINT_FILES.map((name) => {
|
|
241
399
|
try {
|
|
242
|
-
|
|
400
|
+
const st = statSync(path.join(absDir, name));
|
|
401
|
+
return st.isFile() && st.size <= 256 * 1024 ? stampFromStat(st) : null;
|
|
243
402
|
} catch {
|
|
244
|
-
|
|
403
|
+
return null;
|
|
404
|
+
}
|
|
405
|
+
});
|
|
406
|
+
const sig = stamps.map((s) => (s ? fileStampKey(s) : "-")).join("|");
|
|
407
|
+
const cached = projectHintsCache.get(key);
|
|
408
|
+
if (cached && cached.sig === sig) return cached.hints;
|
|
409
|
+
|
|
410
|
+
const readHint = (idx: number): string | null => {
|
|
411
|
+
if (!stamps[idx]) return null;
|
|
412
|
+
try { return readFileSync(path.join(absDir, HINT_FILES[idx]), "utf8"); } catch { return null; }
|
|
413
|
+
};
|
|
414
|
+
const normSupported = (raw: string | undefined): string | undefined => {
|
|
415
|
+
if (!raw) return undefined;
|
|
416
|
+
const clean = raw.toLowerCase() === "utf-8-bom" ? "UTF-8" : raw;
|
|
417
|
+
return isSupportedEncoding(clean) ? normalizeEncoding(clean) : undefined;
|
|
418
|
+
};
|
|
419
|
+
|
|
420
|
+
const hints: ProjectHint[] = [];
|
|
421
|
+
const ec = readHint(0);
|
|
422
|
+
if (ec) {
|
|
423
|
+
const cm = /^\s*charset\s*=\s*([^\s#;]+)/im.exec(ec);
|
|
424
|
+
const em = /^\s*end_of_line\s*=\s*(crlf|lf)\b/im.exec(ec);
|
|
425
|
+
if (cm || em) {
|
|
426
|
+
const rawCharset = cm?.[1]?.trim();
|
|
427
|
+
const encoding = normSupported(rawCharset);
|
|
428
|
+
const lineEnding = em ? (em[1].toUpperCase() as LineEndingStyle) : undefined;
|
|
429
|
+
hints.push({
|
|
430
|
+
source: ".editorconfig",
|
|
431
|
+
...(encoding ? { encoding } : {}),
|
|
432
|
+
...(lineEnding ? { lineEnding } : {}),
|
|
433
|
+
detail: [rawCharset ? `charset=${rawCharset}` : "", lineEnding ? `end_of_line=${lineEnding.toLowerCase()}` : ""].filter(Boolean).join(", "),
|
|
434
|
+
});
|
|
245
435
|
}
|
|
246
436
|
}
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
force: false,
|
|
262
|
-
newFileLineEnding: null,
|
|
263
|
-
matchedPattern: null,
|
|
264
|
-
warnings: [],
|
|
265
|
-
adaptive: true,
|
|
266
|
-
};
|
|
437
|
+
|
|
438
|
+
const ga = readHint(1);
|
|
439
|
+
if (ga) {
|
|
440
|
+
const wm = /working-tree-encoding=([^\s#]+)/i.exec(ga);
|
|
441
|
+
const em = /\beol=(crlf|lf)\b/i.exec(ga);
|
|
442
|
+
if (wm || em) {
|
|
443
|
+
const encoding = normSupported(wm?.[1]);
|
|
444
|
+
const lineEnding = em ? (em[1].toUpperCase() as LineEndingStyle) : undefined;
|
|
445
|
+
hints.push({
|
|
446
|
+
source: ".gitattributes",
|
|
447
|
+
...(encoding ? { encoding } : {}),
|
|
448
|
+
...(lineEnding ? { lineEnding } : {}),
|
|
449
|
+
detail: [wm ? `working-tree-encoding=${wm[1]}` : "", em ? `eol=${em[1].toLowerCase()}` : ""].filter(Boolean).join(", "),
|
|
450
|
+
});
|
|
267
451
|
}
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
const pom = readHint(2);
|
|
455
|
+
const pm = pom && /<project\.build\.sourceEncoding>\s*([^<\s]+)\s*<\/project\.build\.sourceEncoding>/i.exec(pom);
|
|
456
|
+
if (pm) {
|
|
457
|
+
const encoding = normSupported(pm[1]);
|
|
458
|
+
if (encoding) hints.push({ source: "pom.xml", encoding, detail: `project.build.sourceEncoding=${pm[1]}` });
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
const cmk = readHint(3);
|
|
462
|
+
const cm = cmk && /(?:\/source-charset:|-finput-charset=)([A-Za-z0-9._-]+)/i.exec(cmk);
|
|
463
|
+
if (cm) {
|
|
464
|
+
const encoding = normSupported(cm[1]);
|
|
465
|
+
if (encoding) hints.push({ source: "CMakeLists.txt", encoding, detail: cm[0] });
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
if (projectHintsCache.size > MAX_DIR_CACHE) projectHintsCache.clear();
|
|
469
|
+
projectHintsCache.set(key, { sig, hints });
|
|
470
|
+
return hints;
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
/**
|
|
474
|
+
* Zero-config fallback: inspect existing project declaration files in `dir` and up to 3 parent directories
|
|
475
|
+
* so users never need to duplicate existing team encoding/EOL settings into .pi-charset.json.
|
|
476
|
+
*/
|
|
477
|
+
function inferFromProjectFiles(dir: string): { encoding: string; eol: NewFileLineEnding | null } | null {
|
|
478
|
+
let cur = path.resolve(dir);
|
|
479
|
+
for (let depth = 0; depth <= MAX_PARENT_SIBLING_DEPTH; depth++) {
|
|
480
|
+
if (depth > 0 && isBoundaryDir(cur)) break;
|
|
481
|
+
let enc: string | null = null;
|
|
482
|
+
let eol: NewFileLineEnding | null = null;
|
|
483
|
+
for (const h of detectProjectHints(cur)) {
|
|
484
|
+
if (!enc && h.encoding && !isSingleByteEncoding(h.encoding) && !isStatefulEncoding(h.encoding)) enc = h.encoding;
|
|
485
|
+
if (!eol && h.lineEnding) eol = h.lineEnding;
|
|
285
486
|
}
|
|
286
|
-
if (
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
487
|
+
if (enc || eol) return { encoding: enc ?? "UTF-8", eol };
|
|
488
|
+
if (hasGitRoot(cur)) break;
|
|
489
|
+
const parent = path.dirname(cur);
|
|
490
|
+
if (parent === cur) break;
|
|
491
|
+
cur = parent;
|
|
492
|
+
}
|
|
493
|
+
return null;
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
function finalizeSiblingBuffers(
|
|
497
|
+
cacheKey: string,
|
|
498
|
+
signature: string,
|
|
499
|
+
buffers: readonly Buffer[],
|
|
500
|
+
origDir: string,
|
|
501
|
+
): { encoding: string; eol: NewFileLineEnding | null } {
|
|
502
|
+
const result = scoreSiblingBuffers(buffers);
|
|
503
|
+
const resolved = result.hasSignal
|
|
504
|
+
? { encoding: result.encoding, eol: result.eol }
|
|
505
|
+
: (inferFromProjectFiles(origDir) ?? { encoding: "UTF-8", eol: null });
|
|
506
|
+
storeSiblingInference(cacheKey, signature, resolved);
|
|
507
|
+
return resolved;
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
function siblingCacheLookup(cur: string, targetExt: string, excludeBase: string, selected: readonly SiblingCandidate[]) {
|
|
511
|
+
const signature = siblingSignature(selected);
|
|
512
|
+
const cacheKey = `${normalizePathKey(cur)}\u0000${targetExt}\u0000${excludeBase}`;
|
|
513
|
+
const cached = siblingInference.get(cacheKey);
|
|
514
|
+
return {
|
|
515
|
+
cacheKey,
|
|
516
|
+
signature,
|
|
517
|
+
hit: cached && cached.signature === signature ? { encoding: cached.encoding, eol: cached.eol } : null,
|
|
518
|
+
};
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
function nextParentDir(cur: string): string | null {
|
|
522
|
+
if (hasGitRoot(cur)) return null;
|
|
523
|
+
const parent = path.dirname(cur);
|
|
524
|
+
return parent === cur ? null : parent;
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
/**
|
|
528
|
+
* Scan up to 16 sibling text files in `dir` (falling back up to 3 parent dirs for newly created/empty subdirectories)
|
|
529
|
+
* to infer the dominant encoding and line-ending style when creating a new file or adding non-ASCII text to a pure-ASCII file.
|
|
530
|
+
*/
|
|
531
|
+
function inferFromSiblings(dir: string, targetExt: string, excludeBase: string): { encoding: string; eol: NewFileLineEnding | null } {
|
|
532
|
+
let cur: string | null = path.resolve(dir);
|
|
533
|
+
for (let depth = 0; cur && depth <= MAX_PARENT_SIBLING_DEPTH; depth++) {
|
|
534
|
+
if (depth > 0 && isBoundaryDir(cur)) break;
|
|
535
|
+
let entries: import("node:fs").Dirent[] | null = null;
|
|
536
|
+
try { entries = readdirSync(cur, { withFileTypes: true }); } catch { entries = null; }
|
|
537
|
+
if (entries) {
|
|
538
|
+
const excl = depth === 0 ? excludeBase : "";
|
|
539
|
+
const selected: SiblingCandidate[] = [];
|
|
540
|
+
for (const f of selectSiblingEntries(entries, targetExt, excl)) {
|
|
541
|
+
const abs = path.join(cur, f.name);
|
|
542
|
+
try {
|
|
543
|
+
const st = statSync(abs);
|
|
544
|
+
if (st.size > 0 && st.size <= 256 * 1024) selected.push({ name: f.name, abs, stamp: stampFromStat(st) });
|
|
545
|
+
} catch { /* unreadable sibling */ }
|
|
546
|
+
}
|
|
547
|
+
if (selected.length > 0) {
|
|
548
|
+
const { cacheKey, signature, hit } = siblingCacheLookup(cur, targetExt, excl, selected);
|
|
549
|
+
if (hit) return hit;
|
|
550
|
+
const buffers: Buffer[] = [];
|
|
551
|
+
for (const s of selected) {
|
|
552
|
+
try { buffers.push(readFileSync(s.abs)); } catch { /* unreadable sibling */ }
|
|
553
|
+
}
|
|
554
|
+
return finalizeSiblingBuffers(cacheKey, signature, buffers, dir);
|
|
555
|
+
}
|
|
303
556
|
}
|
|
557
|
+
cur = nextParentDir(cur);
|
|
304
558
|
}
|
|
559
|
+
return inferFromProjectFiles(dir) ?? { encoding: "UTF-8", eol: null };
|
|
560
|
+
}
|
|
305
561
|
|
|
306
|
-
|
|
307
|
-
|
|
562
|
+
/** Non-blocking sibling inference (with parent & project-file fallback for empty/new subdirectories) used on async hot paths. */
|
|
563
|
+
async function inferFromSiblingsAsync(dir: string, targetExt: string, excludeBase: string): Promise<{ encoding: string; eol: NewFileLineEnding | null }> {
|
|
564
|
+
let cur: string | null = path.resolve(dir);
|
|
565
|
+
for (let depth = 0; cur && depth <= MAX_PARENT_SIBLING_DEPTH; depth++) {
|
|
566
|
+
if (depth > 0 && isBoundaryDir(cur)) break;
|
|
567
|
+
const entries = await readdir(cur, { withFileTypes: true }).catch(() => null);
|
|
568
|
+
if (entries) {
|
|
569
|
+
const excl = depth === 0 ? excludeBase : "";
|
|
570
|
+
const statResults = await Promise.all(
|
|
571
|
+
selectSiblingEntries(entries, targetExt, excl).map(async (f): Promise<SiblingCandidate | null> => {
|
|
572
|
+
const abs = path.join(cur!, f.name);
|
|
573
|
+
const st = await stat(abs).catch(() => null);
|
|
574
|
+
return st && st.size > 0 && st.size <= 256 * 1024 ? { name: f.name, abs, stamp: stampFromStat(st) } : null;
|
|
575
|
+
}),
|
|
576
|
+
);
|
|
577
|
+
const selected = statResults.filter((s): s is SiblingCandidate => s !== null);
|
|
578
|
+
if (selected.length > 0) {
|
|
579
|
+
const { cacheKey, signature, hit } = siblingCacheLookup(cur, targetExt, excl, selected);
|
|
580
|
+
if (hit) return hit;
|
|
581
|
+
const buffers = (await Promise.all(selected.map((s) => readFile(s.abs).catch(() => null)))).filter((b) => b !== null);
|
|
582
|
+
return finalizeSiblingBuffers(cacheKey, signature, buffers, dir);
|
|
583
|
+
}
|
|
584
|
+
}
|
|
585
|
+
cur = nextParentDir(cur);
|
|
586
|
+
}
|
|
587
|
+
return inferFromProjectFiles(dir) ?? { encoding: "UTF-8", eol: null };
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
// The verdict behind an adaptive rule, keyed by the very buffer it classified, so the read plan that
|
|
591
|
+
// immediately follows can reuse it instead of classifying the same bytes again under the inferred rule.
|
|
592
|
+
const adaptiveVerdicts = new WeakMap<Buffer, Verdict>();
|
|
593
|
+
export function adaptiveVerdictFor(raw: Buffer): Verdict | undefined {
|
|
594
|
+
return adaptiveVerdicts.get(raw);
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
function makeAdaptiveRule(dir: string, encoding: string, newFileLineEnding: NewFileLineEnding | null = null): ResolvedConfig {
|
|
598
|
+
const rd = runtimeDefaults;
|
|
308
599
|
return {
|
|
309
600
|
configDir: dir,
|
|
310
|
-
sourceEncoding:
|
|
311
|
-
writeEncoding:
|
|
601
|
+
sourceEncoding: encoding,
|
|
602
|
+
writeEncoding: encoding,
|
|
312
603
|
writeIntent: null,
|
|
313
604
|
readStrategy: "auto",
|
|
314
|
-
unmappable: "error",
|
|
605
|
+
unmappable: rd?.unmappable ?? "error",
|
|
315
606
|
verifyWrite: true,
|
|
316
|
-
protectUtf8: true,
|
|
607
|
+
protectUtf8: rd?.protectUtf8 ?? true,
|
|
608
|
+
preferSourceOverUtf8: rd?.preferSourceOverUtf8 ?? false,
|
|
317
609
|
autoCandidates: [...DEFAULT_AUTO_CANDIDATES],
|
|
318
610
|
force: false,
|
|
319
|
-
|
|
611
|
+
autoCommit: rd?.autoCommit ?? false,
|
|
612
|
+
hashlines: rd?.hashlines ?? false,
|
|
613
|
+
locale: rd?.locale,
|
|
614
|
+
newFileLineEnding: newFileLineEnding ?? rd?.newFileLineEnding ?? null,
|
|
320
615
|
matchedPattern: null,
|
|
321
616
|
warnings: [],
|
|
322
617
|
adaptive: true,
|
|
323
618
|
};
|
|
324
619
|
}
|
|
325
620
|
|
|
326
|
-
function
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
621
|
+
function adaptiveRuleFromBytes(dir: string, raw: Buffer | null | undefined): ResolvedConfig | null {
|
|
622
|
+
if (!raw || raw.length === 0) return null;
|
|
623
|
+
// Narrowest-first with an early stop: the verdict's encoding is the narrowest candidate that
|
|
624
|
+
// round-trips, which is what pickNarrowestCandidate would select from the exhaustive list.
|
|
625
|
+
const v = classifyBuffer(raw, null, { exhaustive: false, candidateOrder: NARROW_CJK_ORDER });
|
|
626
|
+
adaptiveVerdicts.set(raw, v);
|
|
627
|
+
if (v.kind === "cjk" || v.kind === "utf16le" || v.kind === "utf16be") return makeAdaptiveRule(dir, v.encoding);
|
|
628
|
+
if (v.kind === "utf8" || v.kind === "utf8-bom" || v.kind === "binary" || v.kind === "unknown") return makeAdaptiveRule(dir, "UTF-8");
|
|
629
|
+
return null;
|
|
630
|
+
}
|
|
631
|
+
|
|
632
|
+
/**
|
|
633
|
+
* Synthesize a self-adaptive ResolvedConfig when no .pi-charset.json file is present:
|
|
634
|
+
* - Existing non-ASCII files use their own byte-classified encoding.
|
|
635
|
+
* - New files and pure-ASCII files inherit the dominant encoding and line ending of sibling files in the same directory (defaulting to UTF-8).
|
|
636
|
+
*/
|
|
637
|
+
export function inferAdaptiveRule(absFilePath: string, rawBytes?: Buffer | null): ResolvedConfig {
|
|
638
|
+
const dir = path.dirname(absFilePath);
|
|
639
|
+
let raw = rawBytes;
|
|
640
|
+
if (raw === undefined) {
|
|
641
|
+
try {
|
|
642
|
+
raw = readFileSync(absFilePath);
|
|
643
|
+
} catch {
|
|
644
|
+
raw = null;
|
|
645
|
+
}
|
|
342
646
|
}
|
|
647
|
+
const direct = adaptiveRuleFromBytes(dir, raw);
|
|
648
|
+
if (direct) return direct;
|
|
649
|
+
|
|
650
|
+
// Target file is either new or pure ASCII: infer from sibling files in the same directory.
|
|
651
|
+
const sib = inferFromSiblings(dir, path.extname(absFilePath).toLowerCase(), path.basename(absFilePath));
|
|
652
|
+
return makeAdaptiveRule(dir, sib.encoding, sib.eol);
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
/** Non-blocking counterpart to inferAdaptiveRule used on async read/write/edit paths. */
|
|
656
|
+
export async function inferAdaptiveRuleAsync(absFilePath: string, rawBytes?: Buffer | null): Promise<ResolvedConfig> {
|
|
657
|
+
const dir = path.dirname(absFilePath);
|
|
658
|
+
const raw = rawBytes !== undefined ? rawBytes : await readFile(absFilePath).catch(() => null);
|
|
659
|
+
const direct = adaptiveRuleFromBytes(dir, raw);
|
|
660
|
+
if (direct) return direct;
|
|
661
|
+
|
|
662
|
+
const sib = await inferFromSiblingsAsync(dir, path.extname(absFilePath).toLowerCase(), path.basename(absFilePath));
|
|
663
|
+
return makeAdaptiveRule(dir, sib.encoding, sib.eol);
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
function parseAndCacheConfig(cKey: string, p: string, stamp: FileStamp, text: string): CacheEntry {
|
|
343
667
|
let parsed: unknown;
|
|
344
668
|
try {
|
|
345
669
|
parsed = JSON.parse(stripJsonComments(text));
|
|
346
670
|
} catch (e) {
|
|
671
|
+
// Fall back to default configuration with a warning if the JSON file is malformed, avoiding raw UTF-8 passthrough.
|
|
347
672
|
const entry: CacheEntry = {
|
|
348
673
|
config: { ...DEFAULTS },
|
|
349
674
|
configPath: p,
|
|
350
675
|
warnings: [`${p} 不是合法 JSON(${(e as Error).message});本次按默认值处理,请修正该文件`],
|
|
351
|
-
|
|
352
|
-
size: st.size,
|
|
676
|
+
stamp,
|
|
353
677
|
};
|
|
354
|
-
|
|
678
|
+
setDirCache(cKey, entry);
|
|
355
679
|
return entry;
|
|
356
680
|
}
|
|
357
681
|
const { config, warnings } = validateConfig((parsed ?? {}) as Record<string, unknown>, p);
|
|
358
|
-
const entry: CacheEntry = { config, configPath: p, warnings,
|
|
359
|
-
|
|
682
|
+
const entry: CacheEntry = { config, configPath: p, warnings, stamp };
|
|
683
|
+
setDirCache(cKey, entry);
|
|
360
684
|
return entry;
|
|
361
685
|
}
|
|
362
686
|
|
|
687
|
+
function loadConfigInDirSync(dir: string): CacheEntry | null {
|
|
688
|
+
const cKey = normalizePathKey(dir);
|
|
689
|
+
const cached = dirCache.get(cKey);
|
|
690
|
+
const found = resolveConfigPathSync(dir);
|
|
691
|
+
if (!found) {
|
|
692
|
+
setDirCache(cKey, null);
|
|
693
|
+
return null;
|
|
694
|
+
}
|
|
695
|
+
const { path: p, stamp } = found;
|
|
696
|
+
if (cached && cached.configPath === p && sameFileStamp(cached.stamp, stamp)) return cached;
|
|
697
|
+
try {
|
|
698
|
+
return parseAndCacheConfig(cKey, p, stamp, readFileSync(p, "utf-8"));
|
|
699
|
+
} catch {
|
|
700
|
+
setDirCache(cKey, null);
|
|
701
|
+
return null;
|
|
702
|
+
}
|
|
703
|
+
}
|
|
704
|
+
|
|
363
705
|
export function findNearestConfigSync(startDir: string): FoundConfig | null {
|
|
364
706
|
let cur = path.resolve(startDir);
|
|
365
707
|
const warnings: string[] = [];
|
|
@@ -370,7 +712,7 @@ export function findNearestConfigSync(startDir: string): FoundConfig | null {
|
|
|
370
712
|
return { config: entry.config, configDir: cur, configPath: entry.configPath, warnings };
|
|
371
713
|
}
|
|
372
714
|
const parent = path.dirname(cur);
|
|
373
|
-
if (parent === cur) return
|
|
715
|
+
if (parent === cur) return runtimeFoundConfig(startDir);
|
|
374
716
|
cur = parent;
|
|
375
717
|
}
|
|
376
718
|
}
|
|
@@ -491,13 +833,26 @@ function validateConfig(parsed: Record<string, unknown>, where: string): { confi
|
|
|
491
833
|
merged.autoCandidates = [...DEFAULT_AUTO_CANDIDATES];
|
|
492
834
|
} else merged.autoCandidates = kept;
|
|
493
835
|
}
|
|
836
|
+
const checkBool = (field: string, val: unknown, def: boolean): boolean => {
|
|
837
|
+
if (val === undefined) return def;
|
|
838
|
+
if (typeof val === "boolean") return val;
|
|
839
|
+
warnings.push(`${where}: ${field} 只接受 true/false,收到 ${JSON.stringify(val)},按 ${def} 处理`);
|
|
840
|
+
return def;
|
|
841
|
+
};
|
|
842
|
+
const checkEnum = <T extends string>(field: string, val: unknown, allowed: readonly T[], def: T): T => {
|
|
843
|
+
if (val === undefined) return def;
|
|
844
|
+
if (typeof val === "string" && (allowed as readonly string[]).includes(val)) return val as T;
|
|
845
|
+
warnings.push(`${where}: ${field} 只接受 ${allowed.map((x) => `"${x}"`).join("/")},收到 ${JSON.stringify(val)},已回退为 "${def}"`);
|
|
846
|
+
return def;
|
|
847
|
+
};
|
|
494
848
|
merged.transcodeBash = normalizeBashMode(parsed.transcodeBash, where, warnings);
|
|
849
|
+
merged.autoCommit = checkBool("autoCommit", parsed.autoCommit, false);
|
|
850
|
+
merged.hashlines = checkBool("hashlines", parsed.hashlines, false);
|
|
851
|
+
merged.preferSourceOverUtf8 = checkBool("preferSourceOverUtf8", parsed.preferSourceOverUtf8, false);
|
|
852
|
+
merged.shellGuard = checkEnum("shellGuard", parsed.shellGuard, ["block", "warn", "off"] as const, DEFAULTS.shellGuard);
|
|
853
|
+
merged.locale = parsed.locale === undefined ? undefined : checkEnum("locale", parsed.locale, ["auto", "en", "zh-CN"] as const, "auto");
|
|
495
854
|
merged.newFileLineEnding = normalizeNewFileLineEnding(parsed.newFileLineEnding, where, warnings);
|
|
496
|
-
|
|
497
|
-
else if (typeof parsed.bashFileDump !== "boolean") {
|
|
498
|
-
warnings.push(`${where}: bashFileDump 必须是布尔值,已回退为 true`);
|
|
499
|
-
merged.bashFileDump = true;
|
|
500
|
-
} else merged.bashFileDump = parsed.bashFileDump;
|
|
855
|
+
merged.bashFileDump = checkBool("bashFileDump", parsed.bashFileDump, DEFAULTS.bashFileDump);
|
|
501
856
|
if (merged.overrides) {
|
|
502
857
|
merged.overrides = merged.overrides.map((r) => {
|
|
503
858
|
const rule: OverrideRule = { ...r };
|
|
@@ -532,55 +887,35 @@ function validateConfig(parsed: Record<string, unknown>, where: string): { confi
|
|
|
532
887
|
return { config: merged, warnings };
|
|
533
888
|
}
|
|
534
889
|
|
|
535
|
-
async function loadConfigInDir(dir: string): Promise<CacheEntry | null> {
|
|
890
|
+
async function loadConfigInDir(dir: string, fresh = false): Promise<CacheEntry | null> {
|
|
536
891
|
const cKey = normalizePathKey(dir);
|
|
537
892
|
const cached = dirCache.get(cKey);
|
|
538
893
|
const found = await resolveConfigPath(dir);
|
|
539
894
|
if (!found) {
|
|
540
|
-
|
|
895
|
+
setDirCache(cKey, null);
|
|
541
896
|
return null;
|
|
542
897
|
}
|
|
543
|
-
const { path: p,
|
|
544
|
-
if (
|
|
545
|
-
let text: string;
|
|
898
|
+
const { path: p, stamp } = found;
|
|
899
|
+
if (!fresh && cached && cached.configPath === p && sameFileStamp(cached.stamp, stamp)) return cached;
|
|
546
900
|
try {
|
|
547
|
-
|
|
901
|
+
return parseAndCacheConfig(cKey, p, stamp, await readFile(p, "utf-8"));
|
|
548
902
|
} catch {
|
|
549
|
-
|
|
903
|
+
setDirCache(cKey, null);
|
|
550
904
|
return null;
|
|
551
905
|
}
|
|
552
|
-
let parsed: unknown;
|
|
553
|
-
try {
|
|
554
|
-
parsed = JSON.parse(stripJsonComments(text));
|
|
555
|
-
} catch (e) {
|
|
556
|
-
// Fall back to default configuration with a warning if the JSON file is malformed, avoiding raw UTF-8 passthrough.
|
|
557
|
-
const entry: CacheEntry = {
|
|
558
|
-
config: { ...DEFAULTS },
|
|
559
|
-
configPath: p,
|
|
560
|
-
warnings: [`${p} 不是合法 JSON(${(e as Error).message});本次按默认值处理,请修正该文件`],
|
|
561
|
-
mtimeMs: st.mtimeMs,
|
|
562
|
-
size: st.size,
|
|
563
|
-
};
|
|
564
|
-
dirCache.set(cKey, entry);
|
|
565
|
-
return entry;
|
|
566
|
-
}
|
|
567
|
-
const { config, warnings } = validateConfig((parsed ?? {}) as Record<string, unknown>, p);
|
|
568
|
-
const entry: CacheEntry = { config, configPath: p, warnings, mtimeMs: st.mtimeMs, size: st.size };
|
|
569
|
-
dirCache.set(cKey, entry);
|
|
570
|
-
return entry;
|
|
571
906
|
}
|
|
572
907
|
|
|
573
|
-
export async function findNearestConfig(startDir: string): Promise<FoundConfig | null> {
|
|
908
|
+
export async function findNearestConfig(startDir: string, fresh = false): Promise<FoundConfig | null> {
|
|
574
909
|
let cur = path.resolve(startDir);
|
|
575
910
|
const warnings: string[] = [];
|
|
576
911
|
while (true) {
|
|
577
|
-
const entry = await loadConfigInDir(cur);
|
|
912
|
+
const entry = await loadConfigInDir(cur, fresh);
|
|
578
913
|
if (entry) {
|
|
579
914
|
if (entry.warnings.length) warnings.push(...entry.warnings);
|
|
580
915
|
return { config: entry.config, configDir: cur, configPath: entry.configPath, warnings };
|
|
581
916
|
}
|
|
582
917
|
const parent = path.dirname(cur);
|
|
583
|
-
if (parent === cur) return
|
|
918
|
+
if (parent === cur) return runtimeFoundConfig(startDir);
|
|
584
919
|
cur = parent;
|
|
585
920
|
}
|
|
586
921
|
}
|
|
@@ -656,12 +991,16 @@ export function resolveFileRule(absFilePath: string, found: FoundConfig): Resolv
|
|
|
656
991
|
unmappable: rule?.unmappable ?? config.unmappable ?? DEFAULTS.unmappable,
|
|
657
992
|
verifyWrite: rule?.verifyWrite ?? config.verifyWrite ?? DEFAULTS.verifyWrite,
|
|
658
993
|
protectUtf8: rule?.protectUtf8 ?? config.protectUtf8 ?? DEFAULTS.protectUtf8,
|
|
994
|
+
preferSourceOverUtf8: rule?.preferSourceOverUtf8 ?? config.preferSourceOverUtf8 ?? false,
|
|
659
995
|
autoCandidates: rule?.autoCandidates?.length
|
|
660
996
|
? (rule.autoCandidates.map((c) => safeNormalize(String(c))).filter(Boolean) as string[])
|
|
661
997
|
: config.autoCandidates ?? DEFAULTS.autoCandidates,
|
|
662
998
|
force,
|
|
663
999
|
matchedPattern: rule?.pattern ?? null,
|
|
664
1000
|
newFileLineEnding: rule?.newFileLineEnding ?? config.newFileLineEnding ?? null,
|
|
1001
|
+
autoCommit: config.autoCommit === true,
|
|
1002
|
+
hashlines: config.hashlines === true,
|
|
1003
|
+
locale: config.locale,
|
|
665
1004
|
warnings,
|
|
666
1005
|
};
|
|
667
1006
|
}
|