-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathCode-encoding-fix.py
More file actions
3039 lines (2764 loc) · 134 KB
/
Code-encoding-fix.py
File metadata and controls
3039 lines (2764 loc) · 134 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
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# GUI 工具:为 Code-encoding-fix 提供 Windows UTF-8 与 Git Bash 配置的 tkinter 界面
# 设计为尽量在无管理员权限下运行,提供路径检测、日志与进度反馈
# 兼容 Python 3.10,使用原生 tkinter 组件
import ctypes
import locale
import os
import re
import shutil
import subprocess
import sys
import threading
import tkinter as tk
import tkinter.font as tkfont
from pathlib import Path
from tkinter import filedialog, scrolledtext, ttk
import json
from typing import Callable
from itertools import chain
import time
try:
import winreg # type: ignore
except ImportError:
winreg = None # 在非 Windows 环境下避免崩溃
PROFILE_MARKER_START = "# === Code-encoding-fix 配置(自动生成)开始 ==="
PROFILE_MARKER_END = "# === Code-encoding-fix 配置(自动生成)结束 ==="
BASH_MARKER_START = "# === Code-encoding-fix 配置(自动生成)开始 ==="
BASH_MARKER_END = "# === Code-encoding-fix 配置(自动生成)结束 ==="
# VS Code settings.json 注释使用 //,保持与其他工具一致的中文标记;同时兼容旧版英文标记
VSCODE_MARKER_START = "// === Code-encoding-fix 配置(自动生成)开始 ==="
VSCODE_MARKER_END = "// === Code-encoding-fix 配置(自动生成)结束 ==="
VSCODE_MARKER_START_LEGACY = "// Code-encoding-fix block (do not remove)"
VSCODE_MARKER_END_LEGACY = "// Code-encoding-fix block end"
class SetupApp:
def __init__(self, root: tk.Tk) -> None:
self.root = root
self.root.title("Code-encoding-fix 编码配置助手 v1.0.2 - 阿華(github:hellowind777)")
self._apply_app_icon()
# 默认窗口尺寸与最小尺寸同步下调,保持宽度不变、降低高度以更贴合 1080p 显示
self.root.geometry("820x750")
self.root.minsize(820, 750)
self.root.withdraw()
appdata_root = Path(os.environ.get("APPDATA", Path.home()))
self._config_dir = appdata_root / "Code-encoding-fix"
self._config_path = self._config_dir / "config.json"
self._backup_root = self._config_path.parent / "backup"
self._console_reg_backup_path = self._backup_root / "shell_reg.orig"
self._console_log_buffer: list[tuple[str, str]] = []
self._ps5_profile_path = Path.home() / "Documents" / "WindowsPowerShell" / "Microsoft.PowerShell_profile.ps1"
self._ps7_profile_path = Path.home() / "Documents" / "PowerShell" / "Microsoft.PowerShell_profile.ps1"
self._git_bashrc_path: Path | None = None
self.style = ttk.Style()
try:
self.style.theme_use("vista")
except tk.TclError:
self.style.theme_use("clam")
self._init_fonts()
self.ps5_path_var = tk.StringVar()
self.ps7_path_var = tk.StringVar()
self.git_path_var = tk.StringVar()
self.vscode_path_var = tk.StringVar()
self.status_var = tk.StringVar(value="待检测 Git Bash / Visual Studio Code")
self.console_info_var = tk.StringVar(value="控制台编码:待检测")
self.tool_info_var = tk.StringVar(value="工具配置:待检测")
self.progress_var = tk.IntVar(value=0)
self.is_running = False
self._is_admin_cached = self._is_admin()
self._ps5_available = False
self._ps7_available = False
self._ps5_exe: Path | None = None
self._ps7_exe: Path | None = None
self._git_exe: Path | None = None
self._row_widgets: dict[str, dict[str, ttk.Widget]] = {}
self._detect_cache = {}
self._detect_cache_max = 64
self._shell_marker_detail = {}
self._tool_config_detail = {}
self._registry_cache: dict[tuple[str, ...], list[Path]] = {}
self._shortcut_cache: dict[tuple[str, ...], list[Path]] = {}
self._detecting = False
self._build_layout()
self._apply_window_position()
# 先记录应用启动,再进行 Shell 路径检测,保证日志顺序符合直觉
self._log("应用已启动,准备检测 Shell 路径", "info")
self._detect_all_paths_in_thread(log=True)
self._refresh_env_tool_labels()
self._update_restore_button_state()
self._refresh_start_button_state()
self.root.protocol("WM_DELETE_WINDOW", self._on_close)
self.root.deiconify()
def _apply_app_icon(self) -> None:
"""为窗口/任务栏设置应用图标(优先使用同目录的 .ico)。"""
if not sys.platform.startswith("win"):
return
base_dir = Path(getattr(sys, "_MEIPASS", Path(__file__).resolve().parent))
icon_path = base_dir / "Code-encoding-fix.ico"
if not icon_path.exists():
return
try:
self.root.iconbitmap(default=str(icon_path))
except tk.TclError:
return
def _reset_to_system_default(self) -> None:
"""恢复控制台 CodePage 到系统默认(不依赖备份),不再改写环境变量。"""
if self.is_running:
return
confirm = self._show_modal(
"恢复系统默认编码(控制台配置)",
"将删除控制台编码恢复到当前系统语言默认编码(936),不再改写环境变量。\n\n是否继续?",
kind="confirm",
confirm_text="继续",
cancel_text="取消",
)
if not confirm:
return
self.is_running = True
self._set_buttons_state(False)
threading.Thread(target=self._run_reset_default, daemon=True).start()
def _run_reset_default(self) -> None:
actions: list[tuple[str, str]] = []
try:
default_lang, default_lc_all, default_cp = self._system_default_locale()
self._log_separator("恢复系统默认(不含工具)开始")
self._log("控制台编码:", "info")
console_logs = self._set_console_codepage_all(default_cp)
for level, message in console_logs:
self._log(message, level)
self._log_separator("恢复系统默认(不含工具)结束")
# 刷新检测与状态
self._ui_call(self._detect_all_paths, False)
self._ui_call(self._refresh_env_tool_labels)
self._ui_call(self._refresh_config_status_label)
self._ui_call(self._refresh_start_button_state)
except Exception as exc: # noqa: BLE001
self._log(f"恢复系统默认失败(不含工具): {exc}", "error")
finally:
self.is_running = False
self._ui_call(self._set_buttons_state, True)
rs = self._runtime_status()
console_lines = rs.get("console", [])
summary_parts = [
"恢复系统默认完成(不含工具)。",
"",
"当前控制台编码:",
]
summary_parts.extend([f"• {line}" for line in console_lines] or ["• 未检测到控制台状态"])
summary = "\n".join(summary_parts)
self._ui_call(self._show_modal, "完成", summary, "info")
def _pick_ui_font_family(self) -> str:
# 避免指定西文字体导致中文回退(出现“字体不一致/中文发虚”)
candidates = [
"Microsoft YaHei UI",
"Microsoft YaHei",
"微软雅黑",
"Segoe UI",
]
try:
families = set(tkfont.families(self.root))
except Exception:
families = set()
for family in candidates:
if family in families:
return family
try:
return tkfont.nametofont("TkDefaultFont").cget("family")
except Exception:
return "TkDefaultFont"
def _init_fonts(self) -> None:
self.ui_font_family = self._pick_ui_font_family()
try:
default_font = tkfont.nametofont("TkDefaultFont")
self.ui_font_size = int(default_font.cget("size"))
default_font.configure(family=self.ui_font_family)
except Exception:
self.ui_font_size = 10
try:
self.style.configure(".", font=(self.ui_font_family, self.ui_font_size))
except Exception:
pass
# 显式字体(保持原字号,仅替换 family)
self.font_title = (self.ui_font_family, 16, "bold")
self.font_subtitle = (self.ui_font_family, 10)
self.font_log = (self.ui_font_family, 10)
def _build_layout(self) -> None:
header = ttk.Frame(self.root, padding="12 8")
header.pack(fill="x")
ttk.Label(
header,
text="Code-encoding-fix 编码配置助手",
font=self.font_title,
).pack(anchor="center")
ttk.Label(
header,
text="一键修复Codex for Windows 运行乱码问题,完成 工具/shell UTF-8 编码配置",
font=self.font_subtitle,
foreground="#555",
).pack(anchor="center", pady=(1, 0))
path_frame = ttk.LabelFrame(self.root, text="工具配置", padding="8")
path_frame.pack(fill="x", padx=12, pady=4)
path_frame.columnconfigure(1, weight=1)
row_idx = 0
row_idx = self._build_shell_row(
parent=path_frame,
key="ps5",
label_text="Windows PowerShell 5.1",
var=self.ps5_path_var,
open_cmd=lambda: self._open_path("ps5"),
start_row=row_idx,
)
row_idx = self._build_shell_row(
parent=path_frame,
key="ps7",
label_text="PowerShell 7+",
var=self.ps7_path_var,
open_cmd=lambda: self._open_path("ps7"),
start_row=row_idx,
)
row_idx = self._build_shell_row(
parent=path_frame,
key="git",
label_text="Git Bash",
var=self.git_path_var,
open_cmd=lambda: self._open_path("git"),
start_row=row_idx,
)
row_idx = self._build_shell_row(
parent=path_frame,
key="vscode",
label_text="Visual Studio Code",
var=self.vscode_path_var,
open_cmd=lambda: self._open_path("vscode"),
start_row=row_idx,
readonly=True,
)
console_frame = ttk.LabelFrame(self.root, text="控制台配置", padding="8")
console_frame.pack(fill="x", padx=12, pady=(2, 4))
ttk.Label(console_frame, textvariable=self.console_info_var, foreground="#444").pack(anchor="w")
# 状态摘要条(独立放置在语言环境分区下方)
status_frame = ttk.Frame(self.root, padding="10 2")
status_frame.pack(fill="x", padx=0, pady=(0, 4))
self.admin_label = ttk.Label(status_frame, textvariable=self.status_var, foreground="#0063b1")
self.admin_label.pack(side="left", anchor="w")
ttk.Button(status_frame, text="重新检测", command=lambda: self._detect_all_paths_in_thread(log=True)).pack(side="right")
progress_frame = ttk.Frame(self.root, padding="12 2 12 0")
progress_frame.pack(fill="x")
ttk.Label(progress_frame, text="执行进度").pack(anchor="w")
self.progress = ttk.Progressbar(progress_frame, variable=self.progress_var, maximum=100)
self.progress.pack(fill="x", pady=4)
control_row = ttk.Frame(progress_frame)
control_row.pack(fill="x", pady=(1, 0))
self.start_btn = ttk.Button(control_row, text="开始执行配置", command=self._start_setup)
self.start_btn.pack(side="left")
self.reset_default_btn = ttk.Button(
control_row,
text="恢复系统默认编码(控制台配置)",
width=24,
command=self._reset_to_system_default,
)
self.reset_default_btn.pack(side="left", padx=(8, 0))
self.restore_btn = ttk.Button(
control_row,
text="恢复已备份配置",
width=20,
command=self._restore_configs,
)
self.restore_btn.pack(side="left", padx=(8, 0))
ttk.Button(control_row, text="退出", command=self.root.destroy).pack(side="right")
self.backup_btn = ttk.Button(
control_row,
text="备份目录",
command=self._open_backup_dir,
)
self.backup_btn.pack(side="right", padx=(0, 8))
log_frame = ttk.LabelFrame(self.root, text="日志输出", padding="12")
log_frame.pack(fill="both", expand=True, padx=12, pady=4)
self.log_text = scrolledtext.ScrolledText(
log_frame, height=10, state="disabled", font=self.font_log
)
self.log_text.pack(fill="both", expand=True)
self.log_text.tag_config("info", foreground="#222")
self.log_text.tag_config("success", foreground="#0b6e35")
self.log_text.tag_config("warning", foreground="#b8860b")
self.log_text.tag_config("error", foreground="#b00020")
# 右键菜单:清空日志
self.log_menu = tk.Menu(self.root, tearoff=0)
self.log_menu.add_command(label="清空日志", command=self._clear_log)
self.log_text.bind("<Button-3>", self._show_log_menu)
# 底部留白以保证布局呼吸感
ttk.Frame(self.root, height=2).pack(fill="x")
def _build_shell_row(
self,
parent: ttk.Frame,
key: str,
label_text: str,
var: tk.StringVar,
open_cmd,
start_row: int,
readonly: bool = False,
) -> None:
ttk.Label(parent, text=label_text + ":", width=22).grid(
row=start_row, column=0, sticky="e", padx=(0, 6), pady=(2, 0)
)
entry = ttk.Entry(parent, textvariable=var, state="readonly" if readonly else "normal")
entry.grid(row=start_row, column=1, sticky="we", padx=(0, 6), pady=(2, 0))
btn = ttk.Button(parent, text="打开", command=open_cmd, width=8)
btn.grid(row=start_row, column=2, sticky="e", padx=(0, 0), pady=(2, 0))
status_full = ttk.Label(parent, text="", foreground="#444", anchor="w", justify="left", wraplength=620)
status_full.grid(row=start_row + 1, column=1, columnspan=2, sticky="w", pady=(0, 4))
self._row_widgets[key] = {"entry": entry, "btn": btn, "status_full": status_full}
return start_row + 2
def _update_console_state_label(self) -> None:
status_label = self._console_config_state()
summary_full = self._console_status_summary()
summary_short = self._console_status_summary(short=True)
self._console_summary_short = summary_short
self._console_summary_list = summary_short.split(" ") if summary_short else []
self._console_config_status = status_label
self.console_info_var.set(f"控制台编码:{summary_full}")
def _refresh_env_tool_labels(self) -> None:
# 语言环境改由注册表 CodePage 控制,实时显示当前检测结果
# 语言环境提示已合并到控制台状态,不再单独显示
self._env_summary_short = ""
self._env_status_short = ""
appdata = os.environ.get("APPDATA")
settings_path = Path(appdata) / "Code" / "User" / "settings.json" if appdata else None
# 尝试定位 Visual Studio Code 可执行文件
vscode_exe = shutil.which("code") or shutil.which("code.cmd")
vscode_path_display = None
if vscode_exe:
resolved = Path(vscode_exe).resolve()
if resolved.name.lower() == "code.cmd":
candidate = resolved.parent.parent / "Code.exe"
vscode_path_display = candidate if candidate.exists() else resolved
elif resolved.name.lower() == "code":
candidate = resolved.parent / "Code.exe"
vscode_path_display = candidate if candidate.exists() else resolved
else:
vscode_path_display = resolved
if settings_path and settings_path.exists():
exe_part = f"{vscode_path_display}" if vscode_path_display else None
if exe_part:
self.tool_info_var.set(f"已检测到 Visual Studio Code: {exe_part}")
else:
self.tool_info_var.set("已检测到 Visual Studio Code")
self.vscode_path_var.set(str(settings_path))
else:
self.tool_info_var.set("未检测到 Visual Studio Code,请在安装后再次执行配置")
self.vscode_path_var.set("未检测到 Visual Studio Code,请在安装后再次执行配置")
def _append_console_logs(self, messages: list[tuple[str, str]]) -> None:
if not messages:
return
self._console_log_buffer.extend(messages)
def _file_marker_status(self, path: Path | None, start: str, end: str) -> str:
"""
返回标记状态:
- "full": 同时存在 start/end
- "partial": 仅存在 start 或 end
- "none": 未检测到
- "error": 读取失败
"""
if not path:
return "none"
try:
if not path.exists():
return "none"
text = path.read_text(encoding="utf-8", errors="ignore")
except OSError as exc:
try:
self._log(f"读取 {path} 失败: {exc}", "warning")
except Exception:
pass
return "error"
has_start = start in text
has_end = end in text
if has_start and has_end:
return "full"
if has_start or has_end:
return "partial"
return "none"
@staticmethod
def _normalize_block_text(text: str) -> str:
"""归一化配置块文本,用于比较差异(忽略换行差异与行尾空格)。"""
normalized = text.replace("\r\n", "\n").replace("\r", "\n")
lines = [line.rstrip() for line in normalized.split("\n")]
# 去掉首尾空行,避免误报
while lines and lines[0] == "":
lines.pop(0)
while lines and lines[-1] == "":
lines.pop()
return "\n".join(lines)
@staticmethod
def _extract_marker_blocks(text: str, start: str, end: str) -> list[str]:
"""提取由 start/end 包裹的所有配置块(包含 start/end 行本身)。"""
pattern = re.compile(re.escape(start) + r".*?" + re.escape(end), re.DOTALL)
return pattern.findall(text)
@staticmethod
def _expected_powershell_block() -> str:
"""当前工具写入 PowerShell Profile 的标准配置块(含标记)。"""
return "\n".join(
[
PROFILE_MARKER_START,
"chcp 65001 | Out-Null",
"[Console]::InputEncoding = [System.Text.UTF8Encoding]::new()",
"[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new()",
"$OutputEncoding = [System.Text.UTF8Encoding]::new()",
"$PSDefaultParameterValues['Get-Content:Encoding'] = 'utf8'",
"$PSDefaultParameterValues['Set-Content:Encoding'] = 'utf8'",
"$PSDefaultParameterValues['Add-Content:Encoding'] = 'utf8'",
"$PSDefaultParameterValues['Out-File:Encoding'] = 'utf8'",
"$PSDefaultParameterValues['Select-String:Encoding'] = 'utf8'",
"$PSDefaultParameterValues['Import-Csv:Encoding'] = 'utf8'",
"$PSDefaultParameterValues['Export-Csv:Encoding'] = 'utf8'",
"$PSDefaultParameterValues['*:Encoding'] = 'utf8'",
'$env:LANG = "zh_CN.UTF-8"',
PROFILE_MARKER_END,
]
)
@staticmethod
def _expected_bash_block() -> str:
"""当前工具写入 Git Bash ~/.bashrc 的标准配置块(含标记)。"""
return "\n".join(
[
BASH_MARKER_START,
'export LANG="zh_CN.UTF-8"',
'export LC_ALL="zh_CN.UTF-8"',
'export LC_CTYPE="zh_CN.UTF-8"',
'export LC_MESSAGES="zh_CN.UTF-8"',
'if command -v chcp >/dev/null 2>&1; then chcp 65001 >/dev/null 2>&1; fi',
"git config --global core.quotepath false",
"git config --global i18n.commitencoding utf-8",
"git config --global i18n.logoutputencoding utf-8",
BASH_MARKER_END,
]
)
@staticmethod
def _is_utf8_locale_value(value: object) -> bool:
if not isinstance(value, str):
return False
return bool(re.search(r"utf-?8", value, flags=re.IGNORECASE))
@staticmethod
def _equivalent_powershell_profile(text: str) -> tuple[bool, str]:
"""在无工具标记块时,保守判断 PowerShell profile 是否已做 UTF-8 等效配置。"""
has_input = bool(re.search(r"\[console\]::\s*inputencoding\s*=\s*.*utf8", text, flags=re.IGNORECASE))
has_output = bool(re.search(r"\[console\]::\s*outputencoding\s*=\s*.*utf8", text, flags=re.IGNORECASE))
has_outputencoding = bool(re.search(r"\$outputencoding\s*=\s*.*utf8", text, flags=re.IGNORECASE))
has_psdefaults = ("$psdefaultparametervalues" in text.lower()) and (":encoding" in text.lower()) and ("utf8" in text.lower())
has_chcp = bool(re.search(r"(?:^|\s)chcp\s+65001\b", text, flags=re.IGNORECASE))
ok = has_input and has_output and (has_psdefaults or has_outputencoding or has_chcp)
if not ok:
return False, ""
reasons: list[str] = []
if has_chcp:
reasons.append("检测到 chcp 65001")
if has_outputencoding:
reasons.append("检测到 $OutputEncoding=UTF-8")
if has_psdefaults:
reasons.append("检测到 PSDefaultParameterValues(Encoding)")
return True, ";".join(reasons) if reasons else "检测到关键 UTF-8 设置"
@staticmethod
def _equivalent_bashrc(text: str) -> tuple[bool, str]:
"""在无工具标记块时,保守判断 bashrc 是否已做 UTF-8 等效配置。"""
has_lang = bool(re.search(r"^\s*export\s+LANG\s*=\s*['\"]?.*utf-?8", text, flags=re.IGNORECASE | re.MULTILINE))
has_lc_all = bool(re.search(r"^\s*export\s+LC_ALL\s*=\s*['\"]?.*utf-?8", text, flags=re.IGNORECASE | re.MULTILINE))
lower = text.lower()
has_git = ("core.quotepath" in lower) or ("i18n.commitencoding" in lower) or ("i18n.logoutputencoding" in lower)
ok = has_lang and has_lc_all and has_git
if not ok:
return False, ""
return True, "检测到 LANG/LC_ALL 为 UTF-8 且包含 git 编码配置"
def _analyze_marker_block(
self,
path: Path | None,
start: str,
end: str,
expected_block: str,
equivalent_check: Callable[[str], tuple[bool, str]] | None = None,
) -> dict[str, object]:
"""分析配置文件中工具生成的配置块是否存在漂移(被手动改动/重复/截断)。"""
if not path:
return {"state": "missing", "summary": "未定位到配置文件路径"}
try:
if not path.exists():
return {"state": "missing", "summary": "配置文件不存在"}
text = path.read_text(encoding="utf-8", errors="ignore")
except OSError as exc:
self._log(f"读取 {path} 失败: {exc}", "warning")
return {"state": "unreadable", "summary": "读取失败"}
has_start = start in text
has_end = end in text
if not has_start and not has_end:
if equivalent_check:
ok, reason = equivalent_check(text)
if ok:
suffix = f":{reason}" if reason else ""
return {"state": "ok", "summary": f"等效配置已存在(无工具标记块){suffix}"}
# 无标记且未命中等效 UTF-8 配置:对用户更友好的摘要,避免误导为“仅缺少标记”
return {"state": "missing", "summary": "未发现 UTF-8 配置"}
return {"state": "missing", "summary": "未检测到配置块标记"}
if has_start ^ has_end:
return {"state": "partial", "summary": "检测到部分标记(可能被截断)"}
blocks = self._extract_marker_blocks(text, start, end)
if not blocks:
# 理论上 has_start/has_end 成立时不应为空,这里兜底处理为“部分标记”
return {"state": "partial", "summary": "检测到标记但无法提取完整配置块"}
if len(blocks) > 1:
return {"state": "duplicate", "summary": f"检测到重复配置块({len(blocks)}个)"}
actual = self._normalize_block_text(blocks[0])
expected = self._normalize_block_text(expected_block)
if actual == expected:
return {"state": "ok", "summary": "与标准模板一致"}
# 生成简短差异摘要:定位首个不一致行
actual_lines = actual.split("\n")
expected_lines = expected.split("\n")
first_idx: int | None = None
for idx in range(max(len(actual_lines), len(expected_lines))):
a = actual_lines[idx] if idx < len(actual_lines) else "<缺失>"
e = expected_lines[idx] if idx < len(expected_lines) else "<多余>"
if a != e:
first_idx = idx
break
if first_idx is None:
summary = "与标准模板不一致"
else:
a = actual_lines[first_idx] if first_idx < len(actual_lines) else "<缺失>"
e = expected_lines[first_idx] if first_idx < len(expected_lines) else "<多余>"
summary = f"第{first_idx + 1}行不一致:期望 `{e}`,实际 `{a}`"
return {"state": "modified", "summary": summary}
def _detect_vscode_settings_drift(self) -> dict[str, object]:
"""检测 Visual Studio Code settings.json 是否满足工具期望的 UTF-8 配置。"""
appdata = os.environ.get("APPDATA")
if not appdata:
return {"state": "missing", "summary": "无法定位 APPDATA"}
settings_path = Path(appdata) / "Code" / "User" / "settings.json"
cache_key = None
try:
st = settings_path.stat()
cache_key = ('vscode_drift', str(settings_path), getattr(st, 'st_mtime_ns', st.st_mtime), st.st_size)
except FileNotFoundError:
cache_key = ('vscode_drift', str(settings_path), 'missing')
except OSError:
cache_key = ('vscode_drift', str(settings_path), 'unreadable')
if cache_key and hasattr(self, '_detect_cache') and isinstance(self._detect_cache, dict):
cached = self._detect_cache.get(cache_key)
if cached is not None:
return cached
def _ret(d):
if cache_key and hasattr(self, '_detect_cache') and isinstance(self._detect_cache, dict):
if len(self._detect_cache) >= getattr(self, '_detect_cache_max', 64):
self._detect_cache.clear()
self._detect_cache[cache_key] = d
return d
if not settings_path.exists():
return {"state": "missing", "summary": "未找到 settings.json"}
try:
raw_text = settings_path.read_text(encoding="utf-8")
except Exception as exc: # noqa: BLE001
return {"state": "unreadable", "summary": f"读取失败: {exc}"}
# 如果未写入过工具标记块,判定为“缺失”而非“漂移”(兼容旧版英文标记)
start_hits = any(m in raw_text for m in (VSCODE_MARKER_START, VSCODE_MARKER_START_LEGACY))
end_hits = any(m in raw_text for m in (VSCODE_MARKER_END, VSCODE_MARKER_END_LEGACY))
if not (start_hits and end_hits):
return {"state": "missing", "summary": "未检测到工具标记块"}
data, err = self._load_json_relaxed(settings_path)
if err or not isinstance(data, dict):
return {"state": "unreadable", "summary": err or "解析失败"}
issues: list[str] = []
# 1) files.encoding:允许大小写差异,但仍坚持 utf8(无 BOM)
if "files.encoding" not in data:
issues.append("缺少 `files.encoding`")
else:
enc = data.get("files.encoding")
if not isinstance(enc, str):
issues.append(f"`files.encoding` 当前={enc!r},期望='utf8'")
elif enc.lower() != "utf8":
issues.append(f"`files.encoding` 当前={enc!r},期望='utf8'")
# 2) autoGuessEncoding:必须为 true
if "files.autoGuessEncoding" not in data:
issues.append("缺少 `files.autoGuessEncoding`")
elif data.get("files.autoGuessEncoding") is not True:
issues.append(f"`files.autoGuessEncoding` 当前={data.get('files.autoGuessEncoding')!r},期望=true")
# 3) 默认终端:允许等效 PowerShell(不同版本/命名)
if "terminal.integrated.defaultProfile.windows" not in data:
issues.append("缺少 `terminal.integrated.defaultProfile.windows`")
else:
prof = data.get("terminal.integrated.defaultProfile.windows")
if not isinstance(prof, str):
issues.append(f"`terminal.integrated.defaultProfile.windows` 当前={prof!r},期望为 PowerShell")
elif "powershell" not in prof.lower():
issues.append(f"`terminal.integrated.defaultProfile.windows` 当前={prof!r},期望为 PowerShell")
env = data.get("terminal.integrated.env.windows")
if not isinstance(env, dict):
issues.append("缺少 `terminal.integrated.env.windows`")
else:
for ek, ev in (("LANG", "zh_CN.UTF-8"), ("LC_ALL", "zh_CN.UTF-8")):
v = env.get(ek)
if not self._is_utf8_locale_value(v):
issues.append(f"`terminal.integrated.env.windows.{ek}` 当前={v!r},期望为 UTF-8 locale(如 {ev!r})")
if not issues:
return {"state": "ok", "summary": "关键键值与期望一致"}
return _ret({"state": "modified", "summary": ";".join(issues[:3]) + (";..." if len(issues) > 3 else "")})
def _detect_console_codepage_drift(self, expected_cp: int = 65001) -> list[str]:
"""检测 HKCU\\Console 目标键的 CodePage 是否与期望一致,返回差异摘要列表。"""
diffs: list[str] = []
for label, path in self._console_targets():
key_name = self._console_key_from_path(path)
values = self._read_console_values(key_name)
current = None if not values else values.get("CodePage")
try:
current_int = int(current) if current is not None else None
except Exception:
current_int = None
if current_int is None:
diffs.append(f"{label}: 未检测到 CodePage(期望 {expected_cp})")
elif current_int != expected_cp:
diffs.append(f"{label}: CodePage={current_int}(期望 {expected_cp})")
return diffs
def _log_config_drift_report(self) -> None:
"""输出“哪些内容被手动更改”的差异提示(用于启动自动检测与手动重新检测)。"""
labels = {
"ps5": "Windows PowerShell 5.1",
"ps7": "PowerShell 7+",
"git": "Git Bash",
"vscode": "Visual Studio Code",
}
availability = {
"ps5": getattr(self, "_ps5_available", False),
"ps7": getattr(self, "_ps7_available", False),
"git": self._git_exe is not None,
"vscode": bool(getattr(self, "_vscode_available", False)),
}
# 先触发一次检测,确保 detail 缓存可用
self._detect_shell_config_status()
details: dict[str, dict[str, object]] = getattr(self, "_tool_config_detail", {})
console_lines: list[tuple[str, str]] = []
# 控制台编码漂移:仅在“看起来曾执行过配置”时强调期望为 UTF-8
should_expect_utf8 = bool(self._console_reg_backup_path.exists()) or self._has_any_original_backup()
if should_expect_utf8:
console_diffs = self._detect_console_codepage_drift(expected_cp=65001)
for diff in console_diffs:
console_lines.append(("warning", f"控制台编码: {diff}"))
# 输出顺序:工具摘要(缺失/漂移)→ 控制台编码(漂移/缺失)
# ===== 工具配置与控制台编码 =====
# 漂移日志分级:missing 不视为手动改动,partial 可自动清理
def _level_for_state(s):
if s in ('ok',):
return 'success'
if s in ('missing',):
return 'warning'
if s in ('partial', 'duplicate', 'modified'):
return 'warning'
if s in ('unreadable', 'error'):
return 'error'
return 'info'
def _brief_state(item):
if not isinstance(item, dict):
return '未检测'
s = str(item.get('state') or 'unknown')
summary = str(item.get('summary') or '').strip()
if s == 'ok':
return 'utf-8编码已正确配置'
if s == 'missing':
return '未检测到 UTF-8 配置(可能被删除或尚未配置)'
if s == 'partial':
return '残缺标记(可自动清理)'
if s == 'duplicate':
return '重复块(将自动去重)'
if s == 'modified':
return '已偏离(执行时将覆盖修复)'
if s == 'unreadable':
return '不可读取'
return s
for key, label in (
("ps5", "Windows PowerShell 5.1"),
("ps7", "PowerShell 7+"),
("git", "Git Bash"),
("vscode", "Visual Studio Code"),
):
if not availability.get(key):
continue
item = details.get(key) if isinstance(details, dict) else None
state = str((item or {}).get('state') or 'unknown')
self._log(f"{label}: { _brief_state(item) }", _level_for_state(state))
if console_lines:
for level, message in console_lines:
self._log(f"• {message}", level)
def _vscode_backup_path(self) -> Path:
# 采用与其他备份一致的固定命名
return self._backup_root / "vscode.orig"
def _system_default_locale(self) -> tuple[str, str, int]:
"""获取系统默认的 LANG/LC_ALL/CodePage,失败时回退到 936。"""
try:
# Python 3.15 将移除 getdefaultlocale(),改用 setlocale/getlocale/getencoding 系列 API
try:
locale.setlocale(locale.LC_ALL, "")
except Exception:
pass
lang, enc = locale.getlocale() or (None, None)
except Exception:
lang, enc = (None, None)
if not lang:
fallback_lang = os.environ.get("LANG", "")
lang = fallback_lang.split(".", 1)[0] if fallback_lang else "zh_CN"
cp: int | None = None
try:
cp = int(ctypes.windll.kernel32.GetACP())
except Exception:
cp = None
if cp is None:
try:
enc_pref = locale.getpreferredencoding(False)
m = re.search(r"(\\d{3,5})", enc_pref or "")
if m:
cp = int(m.group(1))
except Exception:
cp = None
if cp is None:
cp = 936
encoding = enc or f"cp{cp}"
lang_val = f"{lang}.{encoding}"
lc_all_val = lang_val
return lang_val, lc_all_val, cp
def _is_system_default_env(self) -> bool:
"""判断当前 LANG/LC_ALL/CHCP 与控制台 CodePage 是否均为系统默认。"""
_, _, default_cp = self._system_default_locale()
env_ok = True # 语言环境不再依赖环境变量
def _console_ok(cp_expected: int) -> bool:
for _label, path in self._console_targets():
values = self._read_console_values(self._console_key_from_path(path))
if values is None:
continue # 视为默认
code = values.get("CodePage")
if code is None:
continue
if code != cp_expected:
return False
return True
return env_ok and _console_ok(default_cp)
@staticmethod
def _strip_json_comments_and_trailing_commas(text: str) -> str:
"""去除注释/尾逗号并清理非法控制字符,避免误删字符串内的 //。"""
out: list[str] = []
i = 0
in_str = False
esc = False
while i < len(text):
ch = text[i]
nxt = text[i + 1] if i + 1 < len(text) else ""
if not in_str and ch == "/" and nxt == "/":
# 行注释,跳到行末
i = text.find("\n", i)
if i == -1:
break
out.append("\n")
i += 1
continue
if not in_str and ch == "/" and nxt == "*":
# 块注释
end = text.find("*/", i + 2)
i = end + 2 if end != -1 else len(text)
continue
out.append(ch)
if ch == "\"" and not esc:
in_str = not in_str
esc = (ch == "\\" and not esc and in_str)
i += 1
cleaned = "".join(out)
cleaned = re.sub(r",\s*([}\]])", r"\1", cleaned) # 尾随逗号
cleaned = re.sub(r"[\x00-\x08\x0B\x0C\x0E-\x1F]", "", cleaned) # 清理控制字符(保留 \t\r\n)
return cleaned
def _append_vscode_block(self, raw_text: str, preserved_custom_lines: list[str] | None = None) -> tuple[str, bool, str | None]:
"""删除冲突键后在末尾追加统一块;保留原注释和行序,并尽量保留用户在标记块中的自定义键。
返回 (新文本, 是否写入, 错误消息);错误时不改动原文本。
"""
marker_start = VSCODE_MARKER_START
marker_end = VSCODE_MARKER_END
marker_start_candidates = (VSCODE_MARKER_START, VSCODE_MARKER_START_LEGACY)
marker_end_candidates = (VSCODE_MARKER_END, VSCODE_MARKER_END_LEGACY)
# 历史版本可能存在文案差异;重复执行时需一并清理,避免残留“仅注释块”
orphan_comment_lines = {
VSCODE_MARKER_START,
VSCODE_MARKER_END,
VSCODE_MARKER_START_LEGACY,
VSCODE_MARKER_END_LEGACY,
"// 自动猜测编码以兼容混合文件",
"// 终端默认使用 PowerShell",
"// VS Code 终端环境:统一 UTF-8",
"// Visual Studio Code 终端环境:统一 UTF-8",
}
expected_lines_set = {
f' "files.encoding": "utf8",',
f" // 自动猜测编码以兼容混合文件",
f' "files.autoGuessEncoding": true,',
f" // 终端默认使用 PowerShell",
f' "terminal.integrated.defaultProfile.windows": "PowerShell",',
f" // Visual Studio Code 终端环境:统一 UTF-8",
f' "terminal.integrated.env.windows": {{',
f' "LANG": "zh_CN.UTF-8",',
f' "LC_ALL": "zh_CN.UTF-8"',
f" }}",
}
preserved_custom_lines = preserved_custom_lines or []
newline = "\r\n" if "\r\n" in raw_text else "\n"
target_keys = [
'"files.encoding"',
'"files.autoGuessEncoding"',
'"terminal.integrated.defaultProfile.windows"',
]
target_env_key = '"terminal.integrated.env.windows"'
# 1) 优先移除完整标记块(包含 start/end 行),解决重复块/旧块残留问题,
# 同时保留用户在标记块内额外添加的键/注释,稍后再插回去。
lines = raw_text.splitlines(keepends=True)
cleaned_lines: list[str] = []
i = 0
while i < len(lines):
line = lines[i]
if any(m in line for m in marker_start_candidates):
j = i + 1
while j < len(lines) and not any(m in lines[j] for m in marker_end_candidates):
j += 1
if j < len(lines) and any(m in lines[j] for m in marker_end_candidates):
# 收集自定义行(非预期行)以便后续保留(保留原始换行与缩进)
for ln in lines[i + 1 : j]:
stripped = ln.strip()
if stripped and stripped not in expected_lines_set and stripped not in orphan_comment_lines:
preserved_custom_lines.append(ln)
# 跳过整个块
i = j + 1
continue
cleaned_lines.append(line)
i += 1
# 2) 清理残缺块的可识别片段(仅删除工具可识别的标记/注释行,避免误伤用户配置)
lines = [ln for ln in cleaned_lines if ln.strip() not in orphan_comment_lines]
new_lines: list[str] = []
in_env = False
brace_depth = 0
for line in lines:
stripped = line.strip()
if in_env:
brace_depth += line.count("{") - line.count("}")
if brace_depth <= 0:
in_env = False
continue
if any(k in stripped for k in target_keys):
continue
if target_env_key in stripped:
in_env = True
brace_depth = line.count("{") - line.count("}")
if brace_depth <= 0:
in_env = False
continue
new_lines.append(line)
closing_idx = None
for i in range(len(new_lines) - 1, -1, -1):
if "}" in new_lines[i]:
closing_idx = i
break
if closing_idx is None:
return raw_text, False, "settings.json 缺少结束大括号"
insert_pos = closing_idx
j = closing_idx - 1
while j >= 0:
t = new_lines[j].strip()
if t == "" or t.startswith("//"):
j -= 1
continue
if not t.endswith(",") and t not in ("{", "["):
new_lines[j] = new_lines[j].rstrip("\n").rstrip() + ",\n"
break
env_lines = [
f' "LANG": "zh_CN.UTF-8",{newline}',
f' "LC_ALL": "zh_CN.UTF-8"{newline}',
]
block = [
f" {marker_start}{newline}",
f' "files.encoding": "utf8",{newline}',
f" // 自动猜测编码以兼容混合文件{newline}",
f' "files.autoGuessEncoding": true,{newline}',
f" // 终端默认使用 PowerShell{newline}",
f' "terminal.integrated.defaultProfile.windows": "PowerShell",{newline}',
f" // Visual Studio Code 终端环境:统一 UTF-8{newline}",
f' "terminal.integrated.env.windows": {{{newline}',
*env_lines,
f" }}{newline}",
f" {marker_end}{newline}",
*preserved_custom_lines,
]
new_lines = new_lines[:insert_pos] + block + new_lines[insert_pos:]
new_text = "".join(new_lines)
changed = new_text != raw_text
return new_text, changed, None
def _remove_vscode_block(self, raw_text: str) -> tuple[str, bool, str | None]:
"""移除 VS Code 工具标记块及关联键,确保恢复后文件无残留。"""
marker_start_candidates = (VSCODE_MARKER_START, VSCODE_MARKER_START_LEGACY)
marker_end_candidates = (VSCODE_MARKER_END, VSCODE_MARKER_END_LEGACY)
orphan_comment_lines = {
VSCODE_MARKER_START,
VSCODE_MARKER_END,
VSCODE_MARKER_START_LEGACY,
VSCODE_MARKER_END_LEGACY,
"// 自动猜测编码以兼容混合文件",
"// 终端默认使用 PowerShell",
"// VS Code 终端环境:统一 UTF-8",
"// Visual Studio Code 终端环境:统一 UTF-8",
}
lines = raw_text.splitlines(keepends=True)
cleaned_lines: list[str] = []
i = 0
while i < len(lines):
line = lines[i]