audit-e2w 0.0.0-stage → 1.11.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +147 -2
  3. package/cordis.patch.yml +3 -0
  4. package/dsh_plugins/audit-e2w/lib/engine.mjs +174 -0
  5. package/dsh_plugins/audit-e2w/lib/index.js +114 -0
  6. package/dsh_plugins/audit-e2w/lib/skill.js +41 -0
  7. package/excel_word/README.md +380 -0
  8. package/excel_word/qoder_engine.py +438 -0
  9. package/excel_word/requirements.txt +4 -0
  10. package/excel_word/wesync/__init__.py +19 -0
  11. package/excel_word/wesync/__main__.py +6 -0
  12. package/excel_word/wesync/align.py +154 -0
  13. package/excel_word/wesync/api.py +840 -0
  14. package/excel_word/wesync/backup_history.py +65 -0
  15. package/excel_word/wesync/changelog.py +58 -0
  16. package/excel_word/wesync/cli.py +173 -0
  17. package/excel_word/wesync/commands/__init__.py +8 -0
  18. package/excel_word/wesync/commands/blank_cmd.py +250 -0
  19. package/excel_word/wesync/commands/bookmark_cmd.py +115 -0
  20. package/excel_word/wesync/commands/clear_cmd.py +48 -0
  21. package/excel_word/wesync/commands/export_cmd.py +220 -0
  22. package/excel_word/wesync/commands/marks_cmd.py +152 -0
  23. package/excel_word/wesync/commands/placeholders_cmd.py +87 -0
  24. package/excel_word/wesync/commands/writeback_cmd.py +513 -0
  25. package/excel_word/wesync/config.py +96 -0
  26. package/excel_word/wesync/console.py +78 -0
  27. package/excel_word/wesync/docx_blank.py +156 -0
  28. package/excel_word/wesync/docx_bookmarks.py +287 -0
  29. package/excel_word/wesync/docx_columns.py +257 -0
  30. package/excel_word/wesync/docx_edit.py +77 -0
  31. package/excel_word/wesync/docx_grid.py +212 -0
  32. package/excel_word/wesync/docx_marks.py +291 -0
  33. package/excel_word/wesync/docx_meta.py +157 -0
  34. package/excel_word/wesync/docx_newtable.py +220 -0
  35. package/excel_word/wesync/docx_placeholders.py +161 -0
  36. package/excel_word/wesync/docx_rows.py +67 -0
  37. package/excel_word/wesync/errors.py +5 -0
  38. package/excel_word/wesync/excel_blocks.py +543 -0
  39. package/excel_word/wesync/excel_export.py +136 -0
  40. package/excel_word/wesync/excel_marks.py +193 -0
  41. package/excel_word/wesync/excel_totals.py +53 -0
  42. package/excel_word/wesync/fsops.py +214 -0
  43. package/excel_word/wesync/gui/__init__.py +34 -0
  44. package/excel_word/wesync/gui/__main__.py +6 -0
  45. package/excel_word/wesync/gui/app.py +399 -0
  46. package/excel_word/wesync/gui/manual.py +68 -0
  47. package/excel_word/wesync/gui/pages/__init__.py +31 -0
  48. package/excel_word/wesync/gui/pages/_page.py +89 -0
  49. package/excel_word/wesync/gui/pages/batch_page.py +423 -0
  50. package/excel_word/wesync/gui/pages/blank_page.py +465 -0
  51. package/excel_word/wesync/gui/pages/bookmark_page.py +37 -0
  52. package/excel_word/wesync/gui/pages/export_page.py +88 -0
  53. package/excel_word/wesync/gui/pages/format_page.py +429 -0
  54. package/excel_word/wesync/gui/pages/help_page.py +92 -0
  55. package/excel_word/wesync/gui/pages/history_page.py +145 -0
  56. package/excel_word/wesync/gui/pages/marks_page.py +178 -0
  57. package/excel_word/wesync/gui/pages/writeback_page.py +452 -0
  58. package/excel_word/wesync/gui/resources.py +22 -0
  59. package/excel_word/wesync/gui/runner.py +74 -0
  60. package/excel_word/wesync/gui/store.py +34 -0
  61. package/excel_word/wesync/gui/theme.py +100 -0
  62. package/excel_word/wesync/gui/widgets/__init__.py +8 -0
  63. package/excel_word/wesync/gui/widgets/cards.py +20 -0
  64. package/excel_word/wesync/gui/widgets/filebar.py +58 -0
  65. package/excel_word/wesync/gui/widgets/logpane.py +110 -0
  66. package/excel_word/wesync/gui/widgets/nav.py +39 -0
  67. package/excel_word/wesync/report_format.py +1577 -0
  68. package/excel_word/wesync/sort_rules.py +244 -0
  69. package/excel_word/wesync/valuefmt.py +462 -0
  70. package/package.json +49 -4
  71. package/qoder_plugins/audit-toolbox/README.md +156 -0
  72. package/qoder_plugins/audit-toolbox/catalog.mjs +265 -0
@@ -0,0 +1,193 @@
1
+ """工作簿里的「链接标注」工作表:高亮标记的导出与回读。
2
+
3
+ 列:标记 | 书签 | 位置 | 原文 | 新内容 | 链接地址 | →定位Word
4
+ * 导出/刷新时按书签名保留已填的「新内容」「链接地址」;
5
+ * Word 中已删除的标记保留成行并在位置列标注「(Word 中已删除)」。
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from pathlib import Path
11
+
12
+ from openpyxl import load_workbook
13
+ from openpyxl.styles import Alignment, Border, Font, PatternFill, Side
14
+ from openpyxl.utils import get_column_letter
15
+ from openpyxl.worksheet.hyperlink import Hyperlink
16
+
17
+ from .config import FONT_NAME
18
+ from .console import log
19
+
20
+ SHEET_MARKS = "链接标注"
21
+ HEADERS = ["标记", "书签", "位置", "原文", "新内容", "链接地址", "→定位Word"]
22
+ HEADER_FILL = PatternFill("solid", fgColor="FFF2CC")
23
+ DELETED_FONT = Font(name=FONT_NAME, size=10, color="9AA3AF")
24
+ THIN = Side(style="thin", color="E3E6EA")
25
+
26
+
27
+ def read_previous_marks(xlsx_path: Path) -> list[dict]:
28
+ """读取现有工作簿里「链接标注」工作表的历史内容(用于保留已填写项)。"""
29
+ if not xlsx_path.exists():
30
+ return []
31
+ try:
32
+ workbook = load_workbook(str(xlsx_path))
33
+ except Exception:
34
+ return []
35
+ if SHEET_MARKS not in workbook.sheetnames:
36
+ return []
37
+ return parse_marks_rows(workbook[SHEET_MARKS], resolve_formulas=False)
38
+
39
+
40
+ def parse_marks_rows(ws, cached_ws=None, *, resolve_formulas: bool = True) -> list[dict]:
41
+ """把工作表读成行字典;遇到「标记」列空行就停止。
42
+
43
+ 「新内容」按单元格在 Excel 里的显示效果转换(与表格回写/占位符同口径):
44
+ 日期按数字格式渲染(如 2025年12月31日),不会出现 2025-12-31 00:00:00;
45
+ 金额千分位/小数位照显示。公式优先取 Excel 缓存结果,其次轻量求值。
46
+ """
47
+ from .errors import SyncError
48
+ from .valuefmt import display_cell, formula_result
49
+
50
+ rows: list[dict] = []
51
+ if ws.max_row is None:
52
+ return rows
53
+ for row_index in range(2, ws.max_row + 1):
54
+ def cell(column: int, display: bool = False) -> str:
55
+ c = ws.cell(row_index, column)
56
+ raw = c.value
57
+ if resolve_formulas and isinstance(raw, str) and raw.startswith("="):
58
+ raw = formula_result(ws, row_index, column, cached_ws)
59
+ if raw is None:
60
+ raise SyncError(
61
+ f"「{SHEET_MARKS}」{c.coordinate} 是公式但没有可用的计算结果。"
62
+ "请先在 Excel 中打开该工作簿,完成重算并保存后再同步。"
63
+ )
64
+ if display:
65
+ return display_cell(c, raw).strip()
66
+ return "" if raw is None else str(raw).strip()
67
+
68
+ label = cell(1)
69
+ if not label:
70
+ break
71
+ rows.append(
72
+ {
73
+ "row": row_index,
74
+ "label": label,
75
+ "bookmark": cell(2),
76
+ "position": cell(3),
77
+ "original": cell(4),
78
+ "new": cell(5, display=True),
79
+ "link": cell(6),
80
+ }
81
+ )
82
+ return rows
83
+
84
+
85
+ def build_marks_sheet(
86
+ wb,
87
+ docx_name: str,
88
+ marks: list,
89
+ previous: list[dict],
90
+ processed: list[dict] | None = None,
91
+ ) -> dict:
92
+ """在 ``wb`` 中创建/刷新「链接标注」工作表,返回统计。
93
+
94
+ 三类行:待处理(仍带高亮)→ 已处理(同步过、已去色,书签仍在)→ 已删除(Word 里连书签都没了)。
95
+ 行号(M01…)按书签沿用上一版,保证 Excel 里引用稳定。
96
+ """
97
+ previous_by_bookmark = {row["bookmark"]: row for row in previous if row["bookmark"]}
98
+ current = {mark.bookmark for mark in marks if mark.bookmark}
99
+ orphans = [row for row in previous if row["bookmark"] and row["bookmark"] not in current]
100
+ processed = processed or []
101
+ processed_names = {item["bookmark"] for item in processed}
102
+ orphans = [row for row in orphans if row["bookmark"] not in processed_names]
103
+
104
+ label_by_bookmark = {row["bookmark"]: row["label"] for row in previous if row["bookmark"]}
105
+ used_numbers = set()
106
+ for label in label_by_bookmark.values():
107
+ if isinstance(label, str) and label.startswith("M") and label[1:].isdigit():
108
+ used_numbers.add(int(label[1:]))
109
+ next_number = 1
110
+
111
+ def label_for(bookmark: str) -> str:
112
+ nonlocal next_number
113
+ if bookmark in label_by_bookmark:
114
+ return label_by_bookmark[bookmark]
115
+ while next_number in used_numbers:
116
+ next_number += 1
117
+ used_numbers.add(next_number)
118
+ label = f"M{next_number:02d}"
119
+ label_by_bookmark[bookmark] = label
120
+ return label
121
+
122
+ if SHEET_MARKS in wb.sheetnames:
123
+ ws = wb[SHEET_MARKS]
124
+ if ws.max_row:
125
+ ws.delete_rows(1, ws.max_row)
126
+ else:
127
+ ws = wb.create_sheet(SHEET_MARKS)
128
+
129
+ for column, title in enumerate(HEADERS, start=1):
130
+ cell = ws.cell(1, column, title)
131
+ cell.font = Font(name=FONT_NAME, size=10, bold=True, color="1F4E79")
132
+ cell.fill = HEADER_FILL
133
+ cell.alignment = Alignment(horizontal="center", vertical="center")
134
+ cell.border = Border(left=THIN, right=THIN, top=THIN, bottom=THIN)
135
+
136
+ row_index = 2
137
+ for mark in marks:
138
+ old = previous_by_bookmark.get(mark.bookmark, {})
139
+ ws.cell(row_index, 1, label_for(mark.bookmark))
140
+ ws.cell(row_index, 2, mark.bookmark)
141
+ ws.cell(row_index, 3, mark.location)
142
+ ws.cell(row_index, 4, mark.text)
143
+ if old.get("new"):
144
+ ws.cell(row_index, 5, old["new"])
145
+ if old.get("link"):
146
+ ws.cell(row_index, 6, old["link"])
147
+ link_cell = ws.cell(row_index, 7, "→定位Word")
148
+ link_cell.hyperlink = Hyperlink(
149
+ ref=link_cell.coordinate, target=docx_name, location=mark.bookmark, display="→定位Word"
150
+ )
151
+ _style_row(ws, row_index)
152
+ row_index += 1
153
+
154
+ for item in processed:
155
+ old = previous_by_bookmark.get(item["bookmark"], {})
156
+ ws.cell(row_index, 1, label_for(item["bookmark"]))
157
+ ws.cell(row_index, 2, item["bookmark"])
158
+ ws.cell(row_index, 3, f"{item['location']}(已处理)")
159
+ ws.cell(row_index, 4, item["text"] or old.get("original", ""))
160
+ if old.get("new"):
161
+ ws.cell(row_index, 5, old["new"])
162
+ if old.get("link"):
163
+ ws.cell(row_index, 6, old["link"])
164
+ ws.cell(row_index, 7, "(已处理)")
165
+ _style_row(ws, row_index, deleted=True)
166
+ row_index += 1
167
+
168
+ for orphan in orphans:
169
+ ws.cell(row_index, 1, label_for(orphan["bookmark"]) if orphan.get("bookmark") else orphan.get("label", ""))
170
+ ws.cell(row_index, 2, orphan.get("bookmark", ""))
171
+ position = (orphan.get("position") or "").replace("(Word 中已删除)", "")
172
+ ws.cell(row_index, 3, f"{position}(Word 中已删除)")
173
+ ws.cell(row_index, 4, orphan.get("original", ""))
174
+ if orphan.get("new"):
175
+ ws.cell(row_index, 5, orphan["new"])
176
+ if orphan.get("link"):
177
+ ws.cell(row_index, 6, orphan["link"])
178
+ ws.cell(row_index, 7, "(已删除)")
179
+ _style_row(ws, row_index, deleted=True)
180
+ row_index += 1
181
+
182
+ for column, width in {1: 7, 2: 12, 3: 18, 4: 26, 5: 26, 6: 34, 7: 12}.items():
183
+ ws.column_dimensions[get_column_letter(column)].width = width
184
+ ws.freeze_panes = "A2"
185
+ return {"marks": len(marks), "processed": len(processed), "orphans": len(orphans)}
186
+
187
+
188
+ def _style_row(ws, row_index: int, deleted: bool = False) -> None:
189
+ for column in range(1, len(HEADERS) + 1):
190
+ cell = ws.cell(row_index, column)
191
+ cell.font = DELETED_FONT if deleted else Font(name=FONT_NAME, size=10)
192
+ cell.alignment = Alignment(vertical="center", wrap_text=column in (3, 4, 5, 6))
193
+ cell.border = Border(left=THIN, right=THIN, top=THIN, bottom=THIN)
@@ -0,0 +1,53 @@
1
+ """导出时给合计行写求和公式:改明细后合计自动更新。
2
+
3
+ 口径:首列以「合计」开头的行视为合计行;对每个数值列写 =SUM(数据区首行:数据区末行),
4
+ 数据区 = 表头之后、该合计行之前。表头按 w:tblHeader 标记识别,未标记时按首行。
5
+ 文字列(如备注)与「—」等占位文字不写公式,保留原样。
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from openpyxl.utils import get_column_letter
11
+
12
+ from .valuefmt import to_excel_value
13
+
14
+ TOTAL_PREFIX = "合计"
15
+
16
+
17
+ def _is_number(text: str) -> bool:
18
+ value, _ = to_excel_value(text or "")
19
+ return isinstance(value, (int, float)) and not isinstance(value, bool)
20
+
21
+
22
+ def total_formula_cells(info: dict, grid_start: int, col0: int = 2) -> dict[tuple[int, int], str]:
23
+ """返回合计行应写 SUM 公式的单元格 {(Excel行, Excel列): 公式}。
24
+
25
+ grid_start 为该表网格首行(表头)在工作表中的行号;col0 为网格首列列号。
26
+ 仅对合计行里本身是数字或空、且数据区出现过数字的列写公式;合并掉的非 owner 格、文字占位格跳过。
27
+ """
28
+ text = info["text"]
29
+ nrows, ncols = info["nrows"], info["ncols"]
30
+ cellmap = info["cellmap"]
31
+ header = info.get("header_rows") or set()
32
+ data_start = (max(header) + 1) if header else 1
33
+ formulas: dict[tuple[int, int], str] = {}
34
+ for t in range(nrows):
35
+ if not (text[t][0] or "").strip().startswith(TOTAL_PREFIX):
36
+ continue
37
+ data_end = t - 1
38
+ if data_end < data_start:
39
+ continue
40
+ for c in range(1, ncols):
41
+ pos = cellmap[t][c]
42
+ if pos is None or not pos.owner:
43
+ continue
44
+ total_value, _ = to_excel_value(text[t][c] or "")
45
+ if isinstance(total_value, str): # 「—」等占位文字,保留原样
46
+ continue
47
+ if not any(_is_number(text[r][c]) for r in range(data_start, data_end + 1)):
48
+ continue
49
+ letter = get_column_letter(col0 + c)
50
+ formulas[(grid_start + t, col0 + c)] = (
51
+ f"=SUM({letter}{grid_start + data_start}:{letter}{grid_start + data_end})"
52
+ )
53
+ return formulas
@@ -0,0 +1,214 @@
1
+ """文件操作:路径解析、写前备份、占用检测、未指定文件时的自动识别。"""
2
+
3
+ import datetime as _dt
4
+ import os
5
+ import shutil
6
+ import sys
7
+ import tempfile
8
+ from pathlib import Path
9
+ from .console import log, warn
10
+ from .errors import SyncError
11
+
12
+
13
+ def project_root() -> Path:
14
+ """项目根目录;打包 exe 时为 exe 所在目录(约定:本项目文件不落项目外)。"""
15
+ if getattr(sys, "frozen", False):
16
+ return Path(sys.executable).resolve().parent
17
+ return Path(__file__).resolve().parents[2]
18
+
19
+
20
+ def tmp_root() -> Path:
21
+ """项目内临时/工作目录(.tmp,已 gitignore),替代系统 Temp。"""
22
+ root = project_root() / ".tmp"
23
+ root.mkdir(parents=True, exist_ok=True)
24
+ return root
25
+
26
+
27
+ def resolve_docx(path_text: str) -> Path:
28
+ path = Path(path_text).expanduser().resolve()
29
+ if not path.exists():
30
+ raise SyncError(f"找不到 Word 文件:{path}")
31
+ if path.suffix.lower() not in (".docx", ".docm"):
32
+ raise SyncError(f"只支持 .docx/.docm 文件:{path}")
33
+ return path
34
+
35
+
36
+ def resolve_xlsx(docx_path: Path, excel_text: str | None) -> Path:
37
+ if excel_text:
38
+ return Path(excel_text).expanduser().resolve()
39
+ return docx_path.with_name(f"{docx_path.stem}_表格数据.xlsx")
40
+
41
+
42
+ def find_default_docx(base_dir: Path) -> Path:
43
+ """在指定目录里找唯一的 .docx(忽略 Word 临时文件)。"""
44
+ candidates = sorted(
45
+ path for path in base_dir.glob("*.docx") if path.is_file() and not path.name.startswith("~$")
46
+ )
47
+ if not candidates:
48
+ raise SyncError(f"未在当前目录找到 .docx 文件,请把报告放到:{base_dir},或显式指定文件路径")
49
+ if len(candidates) > 1:
50
+ names = "\n ".join(path.name for path in candidates)
51
+ raise SyncError(f"当前目录有多个 .docx,请显式指定要处理哪一个:\n {names}")
52
+ return candidates[0]
53
+
54
+
55
+ def default_base_dir(script_dir: Path) -> Path:
56
+ """入口的“工作目录”:当前目录里有 .docx 就用当前目录,否则用入口所在目录。
57
+
58
+ 这样既能“双击界面(入口目录=工作目录)”,也能“在报告目录里直接运行命令行 exe”。
59
+ """
60
+ try:
61
+ cwd = Path.cwd()
62
+ except OSError:
63
+ return script_dir
64
+ if cwd != script_dir:
65
+ try:
66
+ if any(p.is_file() and not p.name.startswith("~$") for p in cwd.glob("*.docx")):
67
+ return cwd
68
+ except OSError:
69
+ return script_dir
70
+ return script_dir
71
+
72
+
73
+ def fill_docx_argument(argv: list[str], base_dir: Path) -> list[str]:
74
+ """未显式给出 Word 文件时,自动补上目录里唯一的 .docx。"""
75
+ if argv and not argv[0].startswith("-"):
76
+ return argv
77
+ docx_path = find_default_docx(base_dir)
78
+ log(f"未指定文件,已自动使用:{docx_path.name}")
79
+ return [str(docx_path), *argv]
80
+
81
+
82
+ def check_file_free(path: Path, force: bool) -> None:
83
+ """独占写测试;文件被 Word/Excel 打开时给出中文提示。"""
84
+ if not path.exists():
85
+ return
86
+ lock_names = {f"~${path.name}", f"~${path.name[2:]}"}
87
+ stale_lock = any((path.parent / name).exists() for name in lock_names)
88
+ try:
89
+ with open(path, "r+b"):
90
+ pass
91
+ except OSError:
92
+ if force:
93
+ warn(f"{path.name} 似乎正被其他程序占用,已按 --force 继续(可能失败)")
94
+ else:
95
+ raise SyncError(
96
+ f"{path.name} 正被其他程序占用,请先关闭 Word/Excel 后重试(或加 --force 强制继续)"
97
+ )
98
+ else:
99
+ if stale_lock:
100
+ warn(f"{path.name} 存在残留的临时锁文件(文件本身未被占用),已忽略并继续")
101
+
102
+
103
+ def backup_file(path: Path) -> Path | None:
104
+ """落盘前备份到同目录 _backup,文件名带时间戳。"""
105
+ if not path.exists():
106
+ return None
107
+ backup_dir = path.parent / "_backup"
108
+ backup_dir.mkdir(exist_ok=True)
109
+ stamp = _dt.datetime.now().strftime("%Y%m%d_%H%M%S")
110
+ target = backup_dir / f"{path.stem}.{stamp}.bak{path.suffix}"
111
+ counter = 1
112
+ while target.exists():
113
+ target = backup_dir / f"{path.stem}.{stamp}_{counter}.bak{path.suffix}"
114
+ counter += 1
115
+ shutil.copy2(path, target)
116
+ return target
117
+
118
+
119
+ def load_workbook_for_save(path: Path, **kwargs):
120
+ """读取待修改工作簿;.xlsm 保留 VBA,避免工具写回时丢宏。"""
121
+ from openpyxl import load_workbook
122
+
123
+ if str(path).lower().endswith(".xlsm"):
124
+ kwargs["keep_vba"] = True
125
+ return load_workbook(str(path), **kwargs)
126
+
127
+
128
+ def _stage_office_file(path: Path, save, validate) -> dict:
129
+ fd, temp_name = tempfile.mkstemp(prefix=f".{path.stem}.", suffix=path.suffix, dir=path.parent)
130
+ os.close(fd)
131
+ staged = Path(temp_name)
132
+ rollback = None
133
+ try:
134
+ save(staged)
135
+ validate(staged)
136
+ fd, rollback_name = tempfile.mkstemp(prefix=f".{path.stem}.rollback.", suffix=path.suffix, dir=path.parent)
137
+ os.close(fd)
138
+ rollback = Path(rollback_name)
139
+ shutil.copy2(path, rollback)
140
+ return {"path": path, "new": staged, "old": rollback, "backup": None, "keep_old": False}
141
+ except Exception:
142
+ staged.unlink(missing_ok=True)
143
+ if rollback is not None:
144
+ rollback.unlink(missing_ok=True)
145
+ raise
146
+
147
+
148
+ def save_docx_xlsx_transaction(
149
+ *,
150
+ docx_path: Path | None = None,
151
+ doc=None,
152
+ xlsx_path: Path | None = None,
153
+ wb=None,
154
+ backup: bool = True,
155
+ ) -> dict[Path, Path | None]:
156
+ """先序列化并校验 Word/Excel,再成对替换;第二步失败时恢复第一步。"""
157
+ import docx
158
+ from openpyxl import load_workbook
159
+
160
+ staged: list[dict] = []
161
+
162
+ def validate_xlsx(path: Path) -> None:
163
+ check = load_workbook(str(path), read_only=True, data_only=False)
164
+ try:
165
+ if not check.sheetnames:
166
+ raise ValueError("工作簿没有工作表")
167
+ finally:
168
+ check.close()
169
+
170
+ def validate_docx(path: Path) -> None:
171
+ docx.Document(str(path))
172
+
173
+ try:
174
+ if xlsx_path is not None:
175
+ staged.append(_stage_office_file(xlsx_path, lambda path: wb.save(str(path)), validate_xlsx))
176
+ if docx_path is not None:
177
+ staged.append(_stage_office_file(docx_path, lambda path: doc.save(str(path)), validate_docx))
178
+ if backup:
179
+ for item in staged:
180
+ item["backup"] = backup_file(item["path"])
181
+
182
+ replaced: list[dict] = []
183
+ for item in staged:
184
+ try:
185
+ os.replace(item["new"], item["path"])
186
+ except OSError as exc:
187
+ rollback_errors = []
188
+ for previous in reversed(replaced):
189
+ try:
190
+ os.replace(previous["old"], previous["path"])
191
+ previous["old"] = None
192
+ except OSError as rollback_exc:
193
+ previous["keep_old"] = True
194
+ rollback_errors.append(f"{previous['path'].name}({rollback_exc})")
195
+ if rollback_errors:
196
+ kept = "、".join(str(previous["old"]) for previous in replaced if previous["keep_old"])
197
+ raise SyncError(
198
+ f"保存 {item['path'].name} 失败,且自动回滚失败:{'、'.join(rollback_errors)}。"
199
+ f"原文件副本保留在:{kept}"
200
+ ) from exc
201
+ raise SyncError(f"保存 {item['path'].name} 失败,Word/Excel 已恢复为同步前状态:{exc}") from exc
202
+ item["new"] = None
203
+ replaced.append(item)
204
+ return {item["path"]: item["backup"] for item in staged}
205
+ except SyncError:
206
+ raise
207
+ except Exception as exc:
208
+ raise SyncError(f"保存前校验或备份失败,Word/Excel 均未替换:{exc}") from exc
209
+ finally:
210
+ for item in staged:
211
+ if item["new"] is not None:
212
+ item["new"].unlink(missing_ok=True)
213
+ if item["old"] is not None and not item["keep_old"]:
214
+ item["old"].unlink(missing_ok=True)
@@ -0,0 +1,34 @@
1
+ """桌面界面(PySide6):把各功能内置成页面,左侧导航切换。
2
+
3
+ 启动方式:
4
+ python -m wesync.gui 或双击 审计工具箱.pyw
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from pathlib import Path
10
+
11
+
12
+ def run(base_dir: Path | None = None) -> int:
13
+ """启动界面主循环,返回进程退出码。"""
14
+ from PySide6.QtCore import Qt
15
+ from PySide6.QtGui import QIcon
16
+ from PySide6.QtWidgets import QApplication
17
+
18
+ from . import theme
19
+ from .app import WesyncApp
20
+ from .resources import icon_path
21
+
22
+ # 按系统实际缩放比例渲染(150% 即 1.5 倍)。不能用 Round:它会把 150% 取整成 2 倍,
23
+ # 字体在一部分高分屏电脑上显得异常大;Qt6 支持分数缩放,不必担心半像素发虚。
24
+ QApplication.setHighDpiScaleFactorRoundingPolicy(Qt.HighDpiScaleFactorRoundingPolicy.PassThrough)
25
+ app = QApplication.instance() or QApplication([])
26
+ app.setApplicationName("审计工具箱")
27
+ app.setWindowIcon(QIcon(str(icon_path())))
28
+ theme.apply(app)
29
+ window = WesyncApp(base_dir=base_dir)
30
+ window.show()
31
+ return app.exec()
32
+
33
+
34
+ __all__ = ["run"]
@@ -0,0 +1,6 @@
1
+ """支持 ``python -m wesync.gui`` 启动界面。"""
2
+
3
+ from . import run
4
+
5
+ if __name__ == "__main__":
6
+ raise SystemExit(run())