forked from taekchef/claude-code-zh-cn
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpatch-cli.js
More file actions
executable file
·731 lines (649 loc) · 24.1 KB
/
patch-cli.js
File metadata and controls
executable file
·731 lines (649 loc) · 24.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
#!/usr/bin/env node
// patch-cli.js - cli.js 硬编码文字中文 patch(安全版)
// 逐条翻译:对每条翻译用正则匹配 "..." 内的目标文本,安全替换
// 被 patch-cli.sh 调用
const fs = require("fs");
const cliFile = process.argv[2];
const translationsFile = process.argv[3];
if (!cliFile || !fs.existsSync(cliFile)) {
console.log("0");
process.exit(0);
}
const original = fs.readFileSync(cliFile, "utf8");
let s = original;
let count = 0;
// === Helper:直接全量替换(仅用于特殊 patch,匹配特定代码模式)===
function tryReplace(from, to) {
if (s.includes(from)) {
s = s.split(from).join(to);
count++;
return true;
}
return false;
}
function tryRegexReplace(pattern, replacer) {
let hit = false;
s = s.replace(pattern, (...args) => {
const match = args[0];
const replaced = replacer(...args);
if (replaced !== match) hit = true;
return replaced;
});
if (hit) count++;
return hit;
}
function escapeRegExp(text) {
return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function asDoubleQuotedLiteral(text) {
return JSON.stringify(text);
}
function splitApostropheLiteral(text) {
if (!text.includes("'")) {
return [text];
}
const parts = [];
const segments = text.split("'");
segments.forEach((segment, index) => {
parts.push(segment);
if (index !== segments.length - 1) {
parts.push("'");
}
});
return parts;
}
function trySplitDoubleQuotedLiteralReplace(en, zh) {
const parts = splitApostropheLiteral(en);
if (parts.length === 1) {
return false;
}
const pattern = new RegExp(
parts.map((part) => escapeRegExp(asDoubleQuotedLiteral(part))).join(String.raw`\s*,\s*`),
"g"
);
return tryRegexReplace(pattern, () => asDoubleQuotedLiteral(zh));
}
function escapeSingleQuotedLiteralContent(text) {
return text
.replace(/\\/g, "\\\\")
.replace(/\r/g, "\\r")
.replace(/\n/g, "\\n")
.replace(/\t/g, "\\t")
.replace(/\u2028/g, "\\u2028")
.replace(/\u2029/g, "\\u2029")
.replace(/'/g, "\\'");
}
function replaceTemplateLiteralTextParts(parts, en, zh) {
let hit = false;
for (const part of parts) {
if (part.type !== "text" || !part.value.includes(en)) {
continue;
}
const replaced = replaceLiteralText(part.value, en, zh);
if (replaced === part.value) {
continue;
}
part.value = replaced;
hit = true;
}
return hit;
}
function splitTemplateSegments(text) {
return text.split(/\$\{[^}]+\}/g);
}
function replaceWholeTemplateLiteral(literal, en, zh) {
const exprParts = literal.parts.filter((part) => part.type === "expr");
if (exprParts.length === 0) {
return false;
}
const enSegments = splitTemplateSegments(en);
const zhSegments = splitTemplateSegments(zh);
if (enSegments.length !== exprParts.length + 1 || zhSegments.length !== exprParts.length + 1) {
return false;
}
let segmentIndex = 0;
for (const part of literal.parts) {
if (part.type !== "text") {
continue;
}
if (part.value !== enSegments[segmentIndex++]) {
return false;
}
}
if (segmentIndex !== enSegments.length) {
return false;
}
segmentIndex = 0;
let textIndex = 0;
for (const part of literal.parts) {
if (part.type !== "text") {
continue;
}
part.value = zhSegments[textIndex++] ?? "";
}
literal.text = literal.parts.map((part) => part.value).join("");
return true;
}
function scanStringLiterals(source) {
const literals = [];
const regexAllowedKeywords = new Set([
"case",
"delete",
"do",
"else",
"in",
"instanceof",
"new",
"of",
"return",
"throw",
"typeof",
"void",
"yield",
"await",
]);
let state = "code";
let i = 0;
let start = -1;
let prevToken = { type: "start", value: "" };
const templateStack = [];
let recordStringLiteral = true;
function setPrevToken(type, value = "") {
prevToken = { type, value };
}
function currentTemplate() {
return templateStack[templateStack.length - 1] ?? null;
}
function isIdentifierStart(ch) {
return /[A-Za-z_$]/.test(ch);
}
function isIdentifierPart(ch) {
return /[A-Za-z0-9_$]/.test(ch);
}
function isDigit(ch) {
return ch >= "0" && ch <= "9";
}
function canStartRegex() {
if (prevToken.type === "start") return true;
if (prevToken.type === "operator") return true;
if (prevToken.type === "open") return true;
if (prevToken.type === "comma") return true;
if (prevToken.type === "colon") return true;
if (prevToken.type === "question") return true;
if (prevToken.type === "templateExprStart") return true;
if (prevToken.type === "keyword" && regexAllowedKeywords.has(prevToken.value)) return true;
return false;
}
while (i < source.length) {
const ch = source[i];
const next = source[i + 1];
switch (state) {
case "code":
if (/\s/.test(ch)) {
i++;
continue;
}
if (ch === '"') {
start = i;
recordStringLiteral = !(currentTemplate() && currentTemplate().exprDepth > 0);
state = "double";
i++;
continue;
}
if (ch === "'") {
start = i;
recordStringLiteral = !(currentTemplate() && currentTemplate().exprDepth > 0);
state = "single";
i++;
continue;
}
if (ch === "`") {
start = i;
templateStack.push({
start,
parts: [],
textStart: i + 1,
exprStart: -1,
exprDepth: 0,
recordLiteral: !(currentTemplate() && currentTemplate().exprDepth > 0),
});
state = "template";
i++;
continue;
}
if (ch === "/" && next === "/") {
state = "lineComment";
i += 2;
continue;
}
if (ch === "/" && next === "*") {
state = "blockComment";
i += 2;
continue;
}
if (ch === "/") {
if (canStartRegex()) {
state = "regex";
i++;
continue;
}
setPrevToken("operator", "/");
i++;
continue;
}
if (isIdentifierStart(ch)) {
let j = i + 1;
while (j < source.length && isIdentifierPart(source[j])) j++;
const word = source.slice(i, j);
setPrevToken(regexAllowedKeywords.has(word) ? "keyword" : "identifier", word);
i = j;
continue;
}
if (isDigit(ch)) {
let j = i + 1;
while (j < source.length && /[0-9A-Fa-f_xXobBeE.+-]/.test(source[j])) j++;
setPrevToken("number", source.slice(i, j));
i = j;
continue;
}
if (ch === "{") {
const template = currentTemplate();
if (template && template.exprDepth > 0) {
template.exprDepth++;
}
setPrevToken("open", ch);
i++;
continue;
}
if (ch === "}") {
const template = currentTemplate();
if (template && template.exprDepth > 0) {
template.exprDepth--;
if (template.exprDepth === 0) {
template.parts.push({
type: "expr",
value: source.slice(template.exprStart, i + 1),
});
template.exprStart = -1;
template.textStart = i + 1;
setPrevToken("templateExprEnd", ch);
state = "template";
i++;
continue;
}
}
setPrevToken("close", ch);
i++;
continue;
}
if (ch === "(" || ch === "[") {
setPrevToken("open", ch);
i++;
continue;
}
if (ch === ")" || ch === "]") {
setPrevToken("close", ch);
i++;
continue;
}
if (ch === ",") {
setPrevToken("comma", ch);
i++;
continue;
}
if (ch === ":") {
setPrevToken("colon", ch);
i++;
continue;
}
if (ch === "?") {
setPrevToken("question", ch);
i++;
continue;
}
if (ch === "=" && next === ">") {
setPrevToken("operator", "=>");
i += 2;
continue;
}
setPrevToken("operator", ch);
i++;
continue;
case "double":
if (ch === "\\") {
i += 2;
continue;
}
if (ch === '"') {
if (recordStringLiteral) {
literals.push({
start,
end: i + 1,
text: source.slice(start + 1, i),
quote: '"',
});
}
setPrevToken("string");
state = "code";
i++;
continue;
}
i++;
continue;
case "single":
if (ch === "\\") {
i += 2;
continue;
}
if (ch === "'") {
if (recordStringLiteral) {
literals.push({
start,
end: i + 1,
text: source.slice(start + 1, i),
quote: "'",
});
}
setPrevToken("string");
state = "code";
i++;
continue;
}
i++;
continue;
case "template":
if (ch === "\\") {
i += 2;
continue;
}
if (ch === "`") {
const template = templateStack.pop();
template.parts.push({
type: "text",
value: source.slice(template.textStart, i),
});
if (template.recordLiteral) {
literals.push({
start: template.start,
end: i + 1,
text: template.parts.map((part) => part.value).join(""),
quote: "`",
parts: template.parts,
});
}
setPrevToken("template");
state = "code";
i++;
continue;
}
if (ch === "$" && next === "{") {
const template = currentTemplate();
template.parts.push({
type: "text",
value: source.slice(template.textStart, i),
});
template.exprStart = i;
template.exprDepth = 1;
setPrevToken("templateExprStart", "${");
state = "code";
i += 2;
continue;
}
i++;
continue;
case "lineComment":
if (ch === "\n" || ch === "\r") {
state = "code";
}
i++;
continue;
case "blockComment":
if (ch === "*" && next === "/") {
state = "code";
i += 2;
continue;
}
i++;
continue;
case "regex":
if (ch === "\\") {
i += 2;
continue;
}
if (ch === "[") {
state = "regexClass";
i++;
continue;
}
if (ch === "/") {
i++;
while (i < source.length && /[A-Za-z]/.test(source[i])) i++;
setPrevToken("regex");
state = "code";
continue;
}
i++;
continue;
case "regexClass":
if (ch === "\\") {
i += 2;
continue;
}
if (ch === "]") {
state = "regex";
i++;
continue;
}
i++;
continue;
}
}
return literals;
}
function replaceLiteralText(text, en, zh) {
const wordLike = en.match(/^([^A-Za-z0-9_$]*)([A-Za-z][A-Za-z0-9_$]*)([^A-Za-z0-9_$]*)$/);
if (!wordLike) {
return text.split(en).join(zh);
}
const [, , word] = wordLike;
const enEscaped = en.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const pattern = new RegExp(`(^|[^A-Za-z0-9_$])(${enEscaped})(?=$|[^A-Za-z0-9_$])`, "g");
return text.replace(pattern, (match, boundary) => boundary + zh);
}
const specialSplitLiteralTranslations = [
{
en: "Quick safety check: Is this a project you created or one you trust? (Like your own code, a well-known open source project, or work from your team). If not, take a moment to review what's in this folder first.",
zh: "安全检查:这是你自己创建或信任的项目吗?(比如你自己的代码、知名开源项目、或团队的工作)。如果不是,请先查看此文件夹中的内容。",
},
{
en: "Claude Code'll be able to read, edit, and execute files here.",
zh: "Claude Code 将能在此目录中读取、编辑和执行文件。",
},
];
const specialLiteralTranslations = [
{ en: "Tab to amend", zh: "按 Tab 修改" },
{ en: "ctrl+e to explain", zh: "按 ctrl+e 说明" },
{ en: " ready · shift+↓ to view", zh: " 已就绪 · 按 shift+↓ 查看" },
{ en: "Failed to save ", zh: "保存失败:" },
];
// === 特殊 patch(基于精确代码模式匹配,安全)===
// 这些 patch 匹配非常特定的代码模式,不会误伤标识符
// 1. 过去式动词数组
tryReplace(
'["Baked","Brewed","Churned","Cogitated","Cooked","Crunched","Saut\u00e9ed","Worked"]',
'["烘焙了","沏了","翻搅了","琢磨了","烹饪了","嚼了","翻炒了","忙活了"]'
);
// 2. Tip: → 💡
const tipMatch = s.match(/`Tip: \$\{[^}]+\}`/);
if (tipMatch) {
const replaced = tipMatch[0].replace("Tip: ", "\u{1F4A1} ");
s = s.split(tipMatch[0]).join(replaced);
count++;
}
// 3. Duration formatter(时间单位中文化)
const marker = "if(q<60000)";
const markerIdx = s.indexOf(marker);
if (markerIdx !== -1) {
const fnStart = s.lastIndexOf("function", markerIdx);
if (fnStart !== -1) {
let depth = 0, fnEnd = -1;
for (let i = s.indexOf("{", fnStart); i < s.length; i++) {
if (s[i] === "{") depth++;
else if (s[i] === "}") depth--;
if (depth === 0) { fnEnd = i; break; }
}
if (fnEnd !== -1) {
let fn = s.substring(fnStart, fnEnd + 1);
const pairs = [
["}d ${z}h ${Y}m ${$}s", "}天${z}时${Y}分${$}秒"],
["}d ${z}h ${Y}m", "}天${z}时${Y}分"],
["}h ${Y}m ${$}s", "}时${Y}分${$}秒"],
["}d ${z}h", "}天${z}时"],
["}h ${Y}m", "}时${Y}分"],
["}m ${$}s", "}分${$}秒"],
["}d", "}天"],
["}h", "}时"],
["}m", "}分"],
["}s", "}秒"],
['"0s"', '"0秒"'],
];
let changed = false;
pairs.forEach(([from, to]) => {
if (fn.includes(from)) {
fn = fn.split(from).join(to);
changed = true;
}
});
if (changed) {
s = s.substring(0, fnStart) + fn + s.substring(fnEnd + 1);
count++;
}
}
}
}
// 4. 去掉 duration display 的 "for" 连接词
// 原始: createElement(T, ..., verb, " for ", duration) → "沏了 for 27分26秒"
// 修复: " for " → " "(仅匹配 createElement 文本节点模式)
tryReplace('," for ",', '," ",');
tryReplace('"Idle for "', '"空闲 "');
// 4b. 主 spinner 的 duration display(反引号模板字符串)
// 原: `${bL} Worked for ${w3(Date.now()-V.startTime)}` → "烘焙了 Worked for 27分26秒"
// 修: `${bL} ${w3(Date.now()-V.startTime)}` → "烘焙了 27分26秒"
tryReplace(' Worked for ${w3(Date.now()-V.startTime)}', ' ${w3(Date.now()-V.startTime)}');
tryReplace('${bL} Idle', '${bL} 空闲');
// 4c. 同类 duration 模板的泛化匹配
// 某些版本会改变量名或表达式,但模板结构仍是 `${verb} Worked for ${duration}`。
// 这里按模板形态处理,不再依赖固定变量名。
tryRegexReplace(/\$\{[^}]+\}\s+Worked for\s+\$\{[^}]+\}/g, (match) =>
match.replace(" Worked for ", " ")
);
tryRegexReplace(/\$\{[^}]+\}\s+Idle(?=[`"])/g, (match) =>
match.replace(" Idle", " 空闲")
);
// 4d. 消息完成后的状态行(显示 "翻搅了 for 51秒" 的地方)
// 原: let G=H&&`${O} for ${M}` (O=动词, M=时长)
// 修: let G=H&&`${O} ${M}` → "翻搅了 51秒"
tryReplace('`${O} for ${M}`', '`${O} ${M}`');
tryRegexReplace(/&&`\$\{[^}]+\} for \$\{[^}]+\}`/g, (match) =>
match.replace(" for ", " ")
);
// 4e. /clear 省上下文提示(split fragment → 稳定模板)
tryRegexReplace(
/([A-Za-z0-9_$]+(?:\.default)?)\.createElement\(([^,]+),\{color:"suggestion"\},"\/clear"\),\1\.createElement\(\2,\{dimColor:!0\}," to save "\),\1\.createElement\(\2,\{color:"suggestion"\},([A-Za-z0-9_$]+)," tokens"\)/g,
(match, factory, component, tokenCount) =>
`${factory}.createElement(${component},{color:"suggestion"},"/clear"),${factory}.createElement(${component},{dimColor:!0}," 保存 "),${factory}.createElement(${component},{color:"suggestion"},${tokenCount}," tokens")`
);
// 5. 保存并编辑快捷键提示(split fragment → 稳定模板)
tryRegexReplace(
/([A-Za-z0-9_$]+(?:\.default)?)\.createElement\(([^,]+),\{color:"success"\},"Press ",([A-Za-z0-9_$]+)," or ",([A-Za-z0-9_$]+)," to save,"," ",\1\.createElement\(\2,\{bold:!0\},"e"\)," to save and edit"\)/g,
(match, factory, component, primaryKey, secondaryKey) =>
`${factory}.createElement(${component},{color:"success"},"按 ",${primaryKey}," 或 ",${secondaryKey}," 保存,按 ",${factory}.createElement(${component},{bold:!0},"e")," 保存并编辑")`
);
// 6. Quick Launch / plan open 等单点高风险 UI 片段迁移到结构化 patch
tryRegexReplace(
/([A-Za-z0-9_$]+(?:\.default)?)\.createElement\(([^,]+),null,"• Cmd\+Esc",\1\.createElement\(\2,\{dimColor:!0\}," for Quick Launch"\)\)/g,
(match, factory, component) =>
`${factory}.createElement(${component},null,"• 快速启动",${factory}.createElement(${component},{dimColor:!0}," · Cmd+Esc"))`
);
tryRegexReplace(
/([A-Za-z0-9_$]+(?:\.default)?)\.createElement\(([^,]+),\{marginTop:1\},\1\.createElement\(([^,]+),\{dimColor:!0\},['"]"\/plan open"['"]\),\1\.createElement\(\3,\{dimColor:!0\}," to edit this plan in "\),\1\.createElement\(\3,\{bold:!0,dimColor:!0\},([A-Za-z0-9_$]+)\)\)/g,
(match, factory, containerComponent, textComponent, terminalName) =>
`${factory}.createElement(${containerComponent},{marginTop:1},${factory}.createElement(${textComponent},{dimColor:!0},"在 "),${factory}.createElement(${textComponent},{bold:!0,dimColor:!0},${terminalName}),${factory}.createElement(${textComponent},{dimColor:!0},' 中用 "/plan open" 编辑此计划'))`
);
// === 逐条翻译:只替换真实的字符串字面量 ===
//
// 先处理 minifier 把 `'` 拆成 `"foo","'","bar"` 的高风险字面量(folder trust、/btw 等),
// 再扫描源码中的真实字符串 token,只在这些 token 内做替换。
// 这样不会跨越源码结构误改对象键、标识符或注释。
if (translationsFile && fs.existsSync(translationsFile)) {
const translationRules = [
...JSON.parse(fs.readFileSync(translationsFile, "utf8")),
...specialLiteralTranslations,
...specialSplitLiteralTranslations,
];
translationRules.sort((a, b) => b.en.length - a.en.length);
for (const { en, zh } of translationRules) {
if (en === zh || !en.includes("'")) {
continue;
}
trySplitDoubleQuotedLiteralReplace(en, zh);
}
const literals = scanStringLiterals(s);
let literalsChanged = false;
for (const { en, zh } of translationRules) {
if (en === zh) continue;
let hit = false;
for (const literal of literals) {
if (literal.quote === "`") {
if (!replaceWholeTemplateLiteral(literal, en, zh)) {
if (!replaceTemplateLiteralTextParts(literal.parts, en, zh)) {
continue;
}
literal.text = literal.parts.map((part) => part.value).join("");
}
hit = true;
literalsChanged = true;
continue;
}
const needle = literal.quote === "'" ? escapeSingleQuotedLiteralContent(en) : en;
const replacementText = literal.quote === "'" ? escapeSingleQuotedLiteralContent(zh) : zh;
if (!literal.text.includes(needle)) {
continue;
}
const replaced = replaceLiteralText(literal.text, needle, replacementText);
if (replaced === literal.text) {
continue;
}
literal.text = replaced;
hit = true;
literalsChanged = true;
}
if (hit) count++;
}
if (literalsChanged) {
let rebuilt = "";
let cursor = 0;
for (const literal of literals) {
rebuilt += s.slice(cursor, literal.start + 1);
rebuilt += literal.text;
rebuilt += literal.quote;
cursor = literal.end;
}
rebuilt += s.slice(cursor);
s = rebuilt;
}
}
// === 只有实际改变文件内容才写入 ===
if (s === original) {
console.log("0");
process.exit(0);
}
const tmp = cliFile + ".zh-cn-tmp";
fs.writeFileSync(tmp, s);
const origMode = fs.statSync(cliFile).mode;
fs.chmodSync(tmp, origMode);
if (process.platform === "win32") {
try { fs.unlinkSync(cliFile); } catch (e) {}
}
fs.renameSync(tmp, cliFile);
console.log(count);