@kevlns/xlmerge 2.0.0 → 2.0.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.
- package/AGENTS.md +12 -11
- package/README.md +14 -6
- package/package.json +1 -1
- package/python/xlsx_merge_engine/xlsx_git_merge_bridge.py +3 -0
- package/python/xlsx_resolver/formula_values.py +130 -35
- package/python/xlsx_resolver/loading_ui.html +44 -0
- package/python/xlsx_resolver/merge_server.py +58 -5
- package/python/xlsx_resolver/merge_ui.html +127 -15
- package/python/xlsx_resolver/prepare_progress.py +34 -0
- package/python/xlsx_resolver/recalculate_workbook.ps1 +4 -18
- package/python/xlsx_resolver/resolve_xlsx_conflict.py +31 -17
- package/python/xlsx_resolver/xlsx_conflict.py +349 -26
package/AGENTS.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# xlmerge Agent 使用规范
|
|
2
2
|
|
|
3
|
-
>
|
|
3
|
+
> 三方工作簿会在结构对齐前分别计算并固化公式最终值;apply 对来源、快照和工作树做完整预检,并以可回滚批次执行写回(版本以 package.json / npm 包为准)。
|
|
4
4
|
|
|
5
5
|
> 本文件是 AI Agent 调用 xlmerge 的规范正本。完整参数以 `xlmerge --help` / 子命令 `--help` 与 `v-cli.plugin.json`(经 v-cli 路由时用 `v-cli agent describe xlmerge`)为准;本文件锁定使用场景、调用规范、快速流程与边界。
|
|
6
6
|
|
|
@@ -21,7 +21,7 @@ xlmerge --repo <repo> launch
|
|
|
21
21
|
## 使用规范(Agent 必须遵守)
|
|
22
22
|
|
|
23
23
|
1. 用户确认要处理冲突后,**只做快速连贯的检测与启动**:`detect` → `count > 0` 时 `launch`。`reviewCount > 0` 时把返回的 `url` 告诉用户,然后停止分析,等待用户在页面完成选择;`reviewCount == 0` 时 `launch` 会直接采用过滤项的远端版本并提交,报告其 JSON 结果;`count == 0` 时报告没有未解决冲突并结束。
|
|
24
|
-
2. **不额外审查冲突情况**:不检查工作簿 Cell、不自行做三方 diff、不总结冲突内容、不读取 base/ours/theirs
|
|
24
|
+
2. **不额外审查冲突情况**:不检查工作簿 Cell、不自行做三方 diff、不总结冲突内容、不读取 base/ours/theirs;这些复杂度由工具内部流程处理。
|
|
25
25
|
3. **不默认走无头自动合并**:`launch --no-browser` + 程序化 decisions/apply 的无头链路仅限自动化测试或用户明确提供决策 JSON / 明确要求自动化的场景;默认流程必须走 UI `launch`,决策权始终在用户。
|
|
26
26
|
4. **不替用户选择 ours/theirs**;不因为冲突文件多、Sheet 多而进入计划模式。
|
|
27
27
|
5. `apply` 默认写回并 `git commit`;`--no-commit` 仅测试决策时使用;`--push` 仅用户明确要求推送时使用,正常流程不自动 push。
|
|
@@ -29,7 +29,7 @@ xlmerge --repo <repo> launch
|
|
|
29
29
|
|
|
30
30
|
## 最高优先级快速流程
|
|
31
31
|
|
|
32
|
-
|
|
32
|
+
用户确认要处理冲突后,只做以下动作:
|
|
33
33
|
|
|
34
34
|
1. 执行检测:
|
|
35
35
|
|
|
@@ -43,7 +43,7 @@ xlmerge --repo <repo> detect
|
|
|
43
43
|
xlmerge --repo <repo> launch
|
|
44
44
|
```
|
|
45
45
|
|
|
46
|
-
3. `reviewCount > 0` 时,把 `launch` 返回的 `url` 告诉用户,然后停止分析,等待用户在页面完成选择。`launch`
|
|
46
|
+
3. `reviewCount > 0` 时,把 `launch` 返回的 `url` 告诉用户,然后停止分析,等待用户在页面完成选择。`launch` 负责提取全部 Git 三方版本、计算多文件多 Sheet diff、后台启动服务并打开浏览器。`reviewCount == 0` 时不会启动 UI,命令会写回所有过滤项、提交并返回 `autoResolved`。
|
|
47
47
|
|
|
48
48
|
如果 `count` 为 `0`,报告没有未解决的 `.xlsx` / `.xlsm` 冲突并结束。
|
|
49
49
|
|
|
@@ -59,13 +59,13 @@ xlmerge --repo <repo> filter add locale/Key.xlsx
|
|
|
59
59
|
|
|
60
60
|
命中过滤项的冲突文件不进入结构化分析或 UI,而是逐字节写入 Git index stage 3(theirs)。若 stage 3 不存在则安全失败;混合批次会在用户确认人工冲突后,与 UI 处理结果一起写回并提交。
|
|
61
61
|
|
|
62
|
-
|
|
62
|
+
## 快速流程禁止事项
|
|
63
63
|
|
|
64
64
|
- 不调用通用 `xlsx` Skill、Excel API 或临时 Python 读取 base/ours/theirs。
|
|
65
65
|
- 不运行 `prepare` 后读取 manifest,也不枚举或总结 Cell/Sheet 差异。
|
|
66
66
|
- 不先搜索配置表结构、Luban schema、策划字段含义或项目代码。
|
|
67
67
|
- 不替用户判断某个 Cell 应选 ours 还是 theirs。
|
|
68
|
-
- 不因为冲突文件多、Sheet
|
|
68
|
+
- 不因为冲突文件多、Sheet 多而进入计划模式;这些复杂度由工具内部流程处理。
|
|
69
69
|
- 不使用阻塞式 `resolve` 作为正常入口;正常调用始终使用会快速返回 URL 的 `launch`。
|
|
70
70
|
- 默认流程禁止按文件循环调用 `launch --path`;单个文件异常也必须由同一批次页面展示或明确报错。
|
|
71
71
|
|
|
@@ -85,7 +85,7 @@ xlmerge --repo <repo> filter add locale/Key.xlsx
|
|
|
85
85
|
- `.xlsm` 的 VBA/ActiveX 单边变化自动采用变化侧;双边变化时在文件级选择本地宏/远端宏(默认本地)。
|
|
86
86
|
- 相对本地可自动合入的远端新增行/列用浅绿色整行/列展示并锁定;已确定删除的行/列用灰色墓碑展示并锁定。
|
|
87
87
|
- 单击行号/列头批量切换;“全部本地/全部远端”作用于当前 Sheet;“撤销”回退最近一次选择,“重置”恢复默认三方选择。
|
|
88
|
-
- 当前 Sheet
|
|
88
|
+
- 当前 Sheet 提供上一个/下一个冲突定位,覆盖可人工选择的单侧改动及双侧冲突,支持跨页循环跳转;每个含可选择改动或结构冲突的 Sheet 必须独立勾选“已确认”,顶部统计跨文件显示已确认数量,未全部确认时提交会给出可点击的定位清单。双方一致变化和锁定的自动处理项不单独要求确认。
|
|
89
89
|
- 悬停 Cell 时展示 base、双方值、双方文件作者和当前选择。
|
|
90
90
|
|
|
91
91
|
3. 用户点击“写回并提交”后:
|
|
@@ -108,7 +108,7 @@ git -C <repo> log -1 --oneline
|
|
|
108
108
|
|
|
109
109
|
## 非交互入口
|
|
110
110
|
|
|
111
|
-
仅在自动化测试或用户已提供明确决策 JSON 时使用 prepare/apply
|
|
111
|
+
仅在自动化测试或用户已提供明确决策 JSON 时使用 prepare/apply;不要用于查看 diff。决策必须同时包含文件、Sheet 和 Cell(Cell 优先使用 manifest 的稳定逻辑 ID):
|
|
112
112
|
|
|
113
113
|
```bash
|
|
114
114
|
xlmerge --repo <repo> prepare
|
|
@@ -123,15 +123,16 @@ xlmerge --repo <repo> apply --manifest <manifest.json> --decisions <decisions.js
|
|
|
123
123
|
- 文件级 delete/modify 冲突缺少完整双方工作簿时,解析器停止并报告;不要猜测删除还是保留。
|
|
124
124
|
- 过滤项要求 Git stage 3 存在;缺少远端版本时停止并报告,不退回本地版本。
|
|
125
125
|
- 写回前必须收齐所有人工选择;缺少任何选择时不改工作树。
|
|
126
|
-
- prepare
|
|
126
|
+
- prepare 生成的三方来源、审阅值快照和当时工作树指纹会在 apply 前全部校验;快照篡改、Git stage 变化、计算未完成或不可靠公式语义都会明确中止,整批次不写回、不 `git add`。
|
|
127
|
+
- 三方计算错误保留原公式、错误与位置作为未知值进入同一批次 UI,必须选择有效来源;无法可靠确认记录身份、表头或行列结构时必须选择整个 Sheet。双方同一记录、同一字段都错误时,工具按一致的显式基础类型替换(数值 0、string 空串、bool false),保留审计信息;ID、引用、约束字段、未知类型、重复 ID 不自动替换。未经处理的错误不能写回,安全限制不变。Agent 不代替用户选择人工项。
|
|
127
128
|
- 所有人工表和自动表先生成临时输出并通过预检,再统一替换;替换中途失败会回滚已替换文件,若文件系统同时阻止回滚则保留恢复副本并报告路径。
|
|
128
|
-
- Excel
|
|
129
|
+
- 替换失败(如 Excel 正在占用目标文件,替换整体回滚)时,应要求用户关闭该工作簿后重试。
|
|
129
130
|
- 不直接修改 XLSX 内部 XML,不使用未经本次完整计算验证的旧公式缓存冒充最终值。
|
|
130
131
|
- 运行时提取文件和 manifest 默认放系统临时目录,不写入业务仓库。
|
|
131
132
|
|
|
132
133
|
## 环境
|
|
133
134
|
|
|
134
|
-
npm 包通过 `bin/xlmerge.js` 启动:自动检测系统 Python(≥3.9
|
|
135
|
+
npm 包通过 `bin/xlmerge.js` 启动:自动检测系统 Python(≥3.9,`XLMERGE_PYTHON` 可直接指定;否则按平台探测 `python3` / `python`,Windows 追加 `py -3`);若缺 `openpyxl` / `bottle` 依赖,则在 `~/.xlmerge/venv` 创建用户级 venv 并安装 `openpyxl==3.1.5`、`bottle==0.13.4`。不含公式的工作簿保持跨平台;含公式时必须在 Windows 上安装桌面版 Excel,解析器只让 Excel 打开隔离的临时副本,并拒绝外链、UDF/VBA、volatile、循环引用、动态数组等不可安全复现的公式语义。`XLMERGE_EXCEL_TIMEOUT_SECONDS` 可覆盖每个工作簿默认 120 秒的重算硬超时。正常流程不检查环境;仅入口明确报环境错误时诊断。
|
|
135
136
|
|
|
136
137
|
## 验证
|
|
137
138
|
|
package/README.md
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
|
|
5
5
|
# xlmerge
|
|
6
6
|
|
|
7
|
-
**解决 Git 仓库中 `.xlsx` / `.xlsm`
|
|
7
|
+
**解决 Git 仓库中 `.xlsx` / `.xlsm` 策划配置表未合并冲突的可视化工具。**
|
|
8
8
|
|
|
9
9
|
[](https://www.npmjs.com/package/@kevlns/xlmerge)
|
|
10
10
|
[](https://www.npmjs.com/package/@kevlns/xlmerge)
|
|
@@ -42,6 +42,10 @@ npm install -g git+https://github.com/kevlns/xlmerge.git
|
|
|
42
42
|
|
|
43
43
|
要求:Node.js >= 16,系统 Python >= 3.9。首次运行若缺少依赖,会在 `~/.xlmerge/venv` 自动创建用户级 venv 并安装 `openpyxl==3.1.5`、`bottle==0.13.4`。不含公式的工作簿保持跨平台;工作簿含公式时,安全的最终值快照需要 Windows 桌面版 Excel,缺失时会明确失败而不会采用旧缓存。
|
|
44
44
|
|
|
45
|
+
支持 Excel 共享公式:先校验每个工作表内的共享组、主公式和引用范围,再展开各单元格的相对/绝对引用,执行公式安全检查并由 Excel 重算隔离副本。缺少或重复主公式、越界成员及不可安全展开的公式会明确失败;数组公式和数据表公式仍不支持。源工作簿保持不变,差异比较使用本次重算得到的最终值快照。
|
|
46
|
+
|
|
47
|
+
计算完成后直接校验 Excel 保存的公式缓存类型、错误和缺失结果,不再通过 COM 逐单元格遍历格式范围。三方版本的计算错误保留原公式、错误与位置,作为未知值进入界面;必须选择有效来源,错误涉及无法可靠确认的记录身份、表头或行列结构时需选择整个 Sheet。双方同一记录、同一字段都报错,且有一致的显式基础类型时,数值自动替换为 0、string 为 `""`、bool 为 false;ID、引用、约束字段、未知类型及重复 ID 不自动替换。替换只发生在审阅快照,原始表不变,界面与提交信息记录替代值。未处理错误不能写入结果。外链、宏/UDF、volatile、循环引用、缺失缓存等安全限制保持不变。
|
|
48
|
+
|
|
45
49
|
### Quick start
|
|
46
50
|
|
|
47
51
|
```bash
|
|
@@ -78,9 +82,12 @@ xlmerge --repo <仓库路径> launch
|
|
|
78
82
|
# 只处理单个文件
|
|
79
83
|
xlmerge --repo <仓库路径> launch --path new_meta/Items.xlsx
|
|
80
84
|
|
|
85
|
+
# 前台阻塞式运行(与 launch 等价,进程前台等待完成)
|
|
86
|
+
xlmerge --repo <仓库路径> resolve
|
|
87
|
+
|
|
81
88
|
# 非交互(自动化/CI):先 prepare 再 apply
|
|
82
89
|
xlmerge --repo <仓库路径> prepare
|
|
83
|
-
xlmerge --repo <仓库路径> apply --manifest <manifest.json> --decisions <decisions.json> [--no-commit] [--push]
|
|
90
|
+
xlmerge --repo <仓库路径> apply --manifest <manifest.json> --decisions <decisions.json> [--no-commit] [--message <text>] [--push]
|
|
84
91
|
```
|
|
85
92
|
|
|
86
93
|
`--repo` 缺省为当前目录(向上查找 Git 根)。
|
|
@@ -147,17 +154,18 @@ python/
|
|
|
147
154
|
└── tests/ # 引擎与解析器测试(不随 npm 包发布)
|
|
148
155
|
```
|
|
149
156
|
|
|
150
|
-
> 注:为兼容嵌入式 Python 发行版(`._pth` 忽略 `PYTHONPATH
|
|
157
|
+
> 注:为兼容嵌入式 Python 发行版(`._pth` 忽略 `PYTHONPATH`),模块内通过自举 `sys.path` 注入定位依赖,勿改为纯包导入。
|
|
151
158
|
|
|
152
159
|
## Package family
|
|
153
160
|
|
|
154
161
|
kevlns 工具家族共享同一套发布约定(tag 驱动、CI 护栏、MIT)。
|
|
155
162
|
|
|
156
|
-
| Package | Purpose |
|
|
163
|
+
| Package | Purpose | Version |
|
|
157
164
|
| --- | --- | --- |
|
|
158
|
-
| [`v-cli`](https://github.com/kevlns/v-cli) | 个人工具箱 CLI | v0.2.
|
|
165
|
+
| [`v-cli`](https://github.com/kevlns/v-cli) | 个人工具箱 CLI | v0.2.14 |
|
|
159
166
|
| [`xlmerge`](https://github.com/kevlns/xlmerge) | Git 中 .xlsx/.xlsm 冲突可视化解决工具(本仓库) | v2.0.0 |
|
|
160
|
-
| [`u-cli-mod`](https://github.com/kevlns/u-cli-mod) | Unity 精确版本路由 + CLI + pipeline 包(Windows-first) | v0.
|
|
167
|
+
| [`u-cli-mod`](https://github.com/kevlns/u-cli-mod) | Unity 精确版本路由 + CLI + pipeline 包(Windows-first) | v0.2.3 |
|
|
168
|
+
| [`figma-to-uprefab`](https://github.com/kevlns/figma-to-uprefab) | Figma 导出、契约校验与 Unity UGUI staging Prefab 构建 | v0.1.1 |
|
|
161
169
|
|
|
162
170
|
## Compatibility
|
|
163
171
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kevlns/xlmerge",
|
|
3
|
-
"version": "2.0.
|
|
3
|
+
"version": "2.0.2",
|
|
4
4
|
"description": "Formula-aware visual resolver for unresolved Git merge conflicts in .xlsx/.xlsm workbooks: three-way sheet/row/cell diff, local UI, atomic write-back and commit.",
|
|
5
5
|
"bin": {
|
|
6
6
|
"xlmerge": "bin/xlmerge.js"
|
|
@@ -1368,6 +1368,7 @@ def analyze_workbooks(
|
|
|
1368
1368
|
ignore_columns: Iterable[str] = (),
|
|
1369
1369
|
write_sidecars: bool = True,
|
|
1370
1370
|
skip_hidden_sheets: bool = True,
|
|
1371
|
+
progress=None,
|
|
1371
1372
|
) -> dict[str, Any]:
|
|
1372
1373
|
base_path = Path(base_path).resolve()
|
|
1373
1374
|
ours_path = Path(ours_path).resolve()
|
|
@@ -1388,6 +1389,8 @@ def analyze_workbooks(
|
|
|
1388
1389
|
clean_merges = 0
|
|
1389
1390
|
triplets = _sheet_triplets(wb_base, wb_ours, wb_theirs)
|
|
1390
1391
|
for sheet_index, triplet in enumerate(triplets, 1):
|
|
1392
|
+
if progress:
|
|
1393
|
+
progress(sheet=str(triplet['logical']), sheetDone=sheet_index - 1, sheetTotal=len(triplets))
|
|
1391
1394
|
name = str(triplet["logical"])
|
|
1392
1395
|
base_name = triplet["base"]
|
|
1393
1396
|
ours_name = triplet["ours"]
|
|
@@ -26,7 +26,8 @@ from xml.etree import ElementTree
|
|
|
26
26
|
from openpyxl import load_workbook
|
|
27
27
|
from openpyxl.cell.rich_text import CellRichText, InlineFont, TextBlock
|
|
28
28
|
from openpyxl.formula import Tokenizer
|
|
29
|
-
from openpyxl.
|
|
29
|
+
from openpyxl.formula.translate import Translator
|
|
30
|
+
from openpyxl.utils.cell import coordinate_to_tuple, range_boundaries
|
|
30
31
|
|
|
31
32
|
|
|
32
33
|
class FormulaValueError(RuntimeError):
|
|
@@ -131,13 +132,72 @@ def _without_string_literals(formula: str) -> str:
|
|
|
131
132
|
|
|
132
133
|
def _iter_formula_cells(workbook: Any) -> Iterable[tuple[Any, Any]]:
|
|
133
134
|
for worksheet in workbook.worksheets:
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
135
|
+
# These are normal, fully loaded worksheets. Inspect stored cells,
|
|
136
|
+
# rather than constructing the rectangular formatted UsedRange.
|
|
137
|
+
for cell in worksheet._cells.values():
|
|
138
|
+
if cell.data_type == "f":
|
|
139
|
+
yield worksheet, cell
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _scan_sheet_formulas(root: Any, sheet_part: str) -> None:
|
|
143
|
+
"""Validate shared groups before openpyxl expands their relative references."""
|
|
144
|
+
groups: dict[str, list[tuple[str, Any]]] = {}
|
|
145
|
+
coordinates: set[str] = set()
|
|
146
|
+
for cell in root.iter():
|
|
147
|
+
if cell.tag.rsplit("}", 1)[-1] != "c":
|
|
148
|
+
continue
|
|
149
|
+
coordinate = cell.get("r", "")
|
|
150
|
+
formula_nodes = [node for node in cell if node.tag.rsplit("}", 1)[-1] == "f"]
|
|
151
|
+
if not formula_nodes:
|
|
152
|
+
continue
|
|
153
|
+
location = f"{sheet_part}!{coordinate or '<missing coordinate>'}"
|
|
154
|
+
if not re.fullmatch(r"[A-Z]{1,3}[1-9][0-9]*", coordinate):
|
|
155
|
+
raise FormulaValueError(f"Invalid formula coordinate at {location}")
|
|
156
|
+
row, column = coordinate_to_tuple(coordinate)
|
|
157
|
+
if row > 1048576 or column > 16384 or coordinate in coordinates or len(formula_nodes) != 1:
|
|
158
|
+
raise FormulaValueError(f"Invalid or duplicate formula cell at {location}")
|
|
159
|
+
coordinates.add(coordinate)
|
|
160
|
+
formula = formula_nodes[0]
|
|
161
|
+
kind = formula.get("t", "normal").lower()
|
|
162
|
+
if kind == "shared":
|
|
163
|
+
index = formula.get("si", "")
|
|
164
|
+
if not re.fullmatch(r"[0-9]+", index) or int(index) > 4294967295:
|
|
165
|
+
raise FormulaValueError(f"Invalid shared formula index at {location}")
|
|
166
|
+
groups.setdefault(index, []).append((coordinate, formula))
|
|
167
|
+
elif kind != "normal" or "ref" in formula.attrib or "si" in formula.attrib:
|
|
168
|
+
raise FormulaValueError(f"Unsupported {kind} formula at {location}")
|
|
169
|
+
elif not formula.text:
|
|
170
|
+
raise FormulaValueError(f"Formula has no body at {location}")
|
|
171
|
+
|
|
172
|
+
for index, members in groups.items():
|
|
173
|
+
masters = [(coordinate, formula) for coordinate, formula in members if formula.text]
|
|
174
|
+
if len(masters) != 1:
|
|
175
|
+
raise FormulaValueError(f"Shared formula group {index} in {sheet_part} must have exactly one master")
|
|
176
|
+
origin, master = masters[0]
|
|
177
|
+
location = f"{sheet_part}!{origin}"
|
|
178
|
+
# openpyxl translates followers as it reads them. A missing or late
|
|
179
|
+
# master would otherwise silently turn their bodies into '='.
|
|
180
|
+
if members[0][0] != origin:
|
|
181
|
+
raise FormulaValueError(f"Shared formula master follows its members at {location}")
|
|
182
|
+
reference = master.get("ref", "")
|
|
183
|
+
if not re.fullmatch(r"[A-Z]{1,3}[1-9][0-9]*(?::[A-Z]{1,3}[1-9][0-9]*)?", reference):
|
|
184
|
+
raise FormulaValueError(f"Invalid shared formula range at {location}: {reference}")
|
|
185
|
+
min_col, min_row, max_col, max_row = range_boundaries(reference)
|
|
186
|
+
if not (1 <= min_col <= max_col <= 16384 and 1 <= min_row <= max_row <= 1048576):
|
|
187
|
+
raise FormulaValueError(f"Invalid shared formula range at {location}: {reference}")
|
|
188
|
+
try:
|
|
189
|
+
translator = Translator("=" + master.text, origin=origin)
|
|
190
|
+
for coordinate, formula in members:
|
|
191
|
+
row, column = coordinate_to_tuple(coordinate)
|
|
192
|
+
if not (min_col <= column <= max_col and min_row <= row <= max_row):
|
|
193
|
+
raise FormulaValueError(f"Shared formula member outside {reference} at {sheet_part}!{coordinate}")
|
|
194
|
+
if coordinate != origin and "ref" in formula.attrib:
|
|
195
|
+
raise FormulaValueError(f"Shared formula follower declares a range at {sheet_part}!{coordinate}")
|
|
196
|
+
translator.translate_formula(coordinate)
|
|
197
|
+
except FormulaValueError:
|
|
198
|
+
raise
|
|
199
|
+
except Exception as exc:
|
|
200
|
+
raise FormulaValueError(f"Cannot expand shared formula at {location}") from exc
|
|
141
201
|
|
|
142
202
|
|
|
143
203
|
def _scan_package(path: Path) -> None:
|
|
@@ -168,30 +228,22 @@ def _scan_package(path: Path) -> None:
|
|
|
168
228
|
# or connection, avoiding false positives for user URLs.
|
|
169
229
|
if b"externallink" in lowered or b"externalconnection" in lowered:
|
|
170
230
|
raise FormulaValueError(f"Workbook contains an external relationship: {name}")
|
|
171
|
-
# Shared
|
|
172
|
-
#
|
|
173
|
-
#
|
|
174
|
-
#
|
|
231
|
+
# Shared formulas are ordinary formulas compressed into a master
|
|
232
|
+
# and relative followers. Validate the groups before openpyxl
|
|
233
|
+
# expands them; array/data-table ranges still require separate
|
|
234
|
+
# semantics and remain unsupported.
|
|
175
235
|
for name in names:
|
|
176
236
|
if not name.startswith("xl/worksheets/") or not name.endswith(".xml"):
|
|
177
237
|
continue
|
|
178
238
|
root = ElementTree.fromstring(archive.read(archive_names[name]))
|
|
179
|
-
|
|
180
|
-
if formula_node.tag.rsplit("}", 1)[-1] != "f":
|
|
181
|
-
continue
|
|
182
|
-
attrs = {key.rsplit("}", 1)[-1]: value for key, value in formula_node.attrib.items()}
|
|
183
|
-
kind = attrs.get("t", "").lower()
|
|
184
|
-
if kind in {"shared", "array", "datatable"} or "ref" in attrs:
|
|
185
|
-
raise FormulaValueError(f"Unsupported shared/array formula in {name}")
|
|
186
|
-
if formula_node.text is None and kind:
|
|
187
|
-
raise FormulaValueError(f"Unsupported formula without body in {name}")
|
|
239
|
+
_scan_sheet_formulas(root, name)
|
|
188
240
|
except ElementTree.ParseError as exc:
|
|
189
241
|
raise FormulaValueError(f"Cannot inspect workbook XML safely: {path}") from exc
|
|
190
242
|
except (OSError, zipfile.BadZipFile) as exc:
|
|
191
243
|
raise FormulaValueError(f"Cannot inspect workbook package: {path}") from exc
|
|
192
244
|
|
|
193
245
|
|
|
194
|
-
def _scan_formulas(workbook: Any) -> list[tuple[str, str, str]]:
|
|
246
|
+
def _scan_formulas(workbook: Any, *, allow_errors: bool = False) -> list[tuple[str, str, str]]:
|
|
195
247
|
formulas: list[tuple[str, str, str]] = []
|
|
196
248
|
for worksheet, cell in _iter_formula_cells(workbook):
|
|
197
249
|
formula = cell.value.text if hasattr(cell.value, "text") else cell.value
|
|
@@ -209,7 +261,7 @@ def _scan_formulas(workbook: Any) -> list[tuple[str, str, str]]:
|
|
|
209
261
|
raise FormulaValueError(f"Dynamic/implicit-array formula at {worksheet.title}!{cell.coordinate}")
|
|
210
262
|
if any(re.search(rf"(?<![A-Z0-9_.]){re.escape(name)}\s*\(", upper) for name in _VOLATILE_FUNCTIONS):
|
|
211
263
|
raise FormulaValueError(f"Volatile formula is not reproducible at {worksheet.title}!{cell.coordinate}")
|
|
212
|
-
if "#REF!" in upper:
|
|
264
|
+
if "#REF!" in upper and not allow_errors:
|
|
213
265
|
raise FormulaValueError(f"Broken formula reference at {worksheet.title}!{cell.coordinate}")
|
|
214
266
|
for match in _FUNCTION_CALL_RE.finditer(scan_formula):
|
|
215
267
|
name = match.group(1).upper()
|
|
@@ -218,11 +270,11 @@ def _scan_formulas(workbook: Any) -> list[tuple[str, str, str]]:
|
|
|
218
270
|
if name.startswith("_XLFN.") or name.startswith("_XLWS.") or name not in _BUILTIN_FUNCTIONS:
|
|
219
271
|
raise FormulaValueError(f"Unknown/UDF formula function {name} at {worksheet.title}!{cell.coordinate}")
|
|
220
272
|
formulas.append((worksheet.title, cell.coordinate, formula))
|
|
221
|
-
_detect_formula_cycles(workbook)
|
|
273
|
+
_detect_formula_cycles(workbook, allow_errors=allow_errors)
|
|
222
274
|
return formulas
|
|
223
275
|
|
|
224
276
|
|
|
225
|
-
def _detect_formula_cycles(workbook: Any) -> None:
|
|
277
|
+
def _detect_formula_cycles(workbook: Any, *, allow_errors: bool = False) -> None:
|
|
226
278
|
"""Fail closed on cycles or references we cannot statically account for."""
|
|
227
279
|
nodes = {(ws.title, cell.coordinate): cell for ws, cell in _iter_formula_cells(workbook)}
|
|
228
280
|
graph = {}
|
|
@@ -245,6 +297,11 @@ def _detect_formula_cycles(workbook: Any) -> None:
|
|
|
245
297
|
if token.type != "OPERAND" or token.subtype != "RANGE":
|
|
246
298
|
continue
|
|
247
299
|
raw = token.value.strip()
|
|
300
|
+
if allow_errors and "#REF!" in raw.upper():
|
|
301
|
+
# A deleted reference (including Sheet!#REF!) has no target
|
|
302
|
+
# node. Excel still computes and records its typed error;
|
|
303
|
+
# other dependencies and cycles remain fully checked.
|
|
304
|
+
continue
|
|
248
305
|
if "!" in raw:
|
|
249
306
|
sheet_text, raw_ref = raw.rsplit("!", 1)
|
|
250
307
|
if ":" in sheet_text:
|
|
@@ -306,7 +363,7 @@ def _detect_formula_cycles(workbook: Any) -> None:
|
|
|
306
363
|
raise FormulaValueError(f"Circular formula dependency detected at {node[0]}!{node[1]}")
|
|
307
364
|
|
|
308
365
|
|
|
309
|
-
def _scan_defined_names(workbook: Any) -> None:
|
|
366
|
+
def _scan_defined_names(workbook: Any, *, allow_errors: bool = False) -> None:
|
|
310
367
|
"""Reject names which smuggle an external link or executable reference."""
|
|
311
368
|
all_names = [*workbook.defined_names.values(),
|
|
312
369
|
*(name for ws in workbook.worksheets for name in ws.defined_names.values())]
|
|
@@ -314,7 +371,7 @@ def _scan_defined_names(workbook: Any) -> None:
|
|
|
314
371
|
text = str(getattr(defined_name, "attr_text", "") or "")
|
|
315
372
|
scan_text = _without_string_literals(text)
|
|
316
373
|
scan_upper = scan_text.upper()
|
|
317
|
-
if _EXTERNAL_REF_RE.search(scan_text) or re.search(r"\bDDE\s*\(", scan_text, re.IGNORECASE) or "#REF!" in scan_upper:
|
|
374
|
+
if _EXTERNAL_REF_RE.search(scan_text) or re.search(r"\bDDE\s*\(", scan_text, re.IGNORECASE) or ("#REF!" in scan_upper and not allow_errors):
|
|
318
375
|
name = getattr(defined_name, "name", "<unnamed>")
|
|
319
376
|
raise FormulaValueError(f"Defined name contains an unsafe reference: {name}")
|
|
320
377
|
name = getattr(defined_name, "name", "<unnamed>")
|
|
@@ -360,6 +417,7 @@ def _cleanup_excel_process(state_path: Path) -> None:
|
|
|
360
417
|
|
|
361
418
|
|
|
362
419
|
def _run_excel_recalculate(source: Path, result: Path, timeout_seconds: int) -> None:
|
|
420
|
+
from prepare_progress import checkpoint, cancellable, PreparationCancelled
|
|
363
421
|
script = Path(__file__).with_name("recalculate_workbook.ps1")
|
|
364
422
|
if not script.is_file():
|
|
365
423
|
raise FormulaValueError(f"Excel recalculation helper is missing: {script}")
|
|
@@ -373,9 +431,37 @@ def _run_excel_recalculate(source: Path, result: Path, timeout_seconds: int) ->
|
|
|
373
431
|
command = [_powershell_executable(), "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass",
|
|
374
432
|
"-File", str(script), "-ParametersPath", str(params_path)]
|
|
375
433
|
try:
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
434
|
+
if not cancellable():
|
|
435
|
+
completed = subprocess.run(command, capture_output=True, text=True,
|
|
436
|
+
encoding="utf-8", errors="replace",
|
|
437
|
+
timeout=max(1, int(timeout_seconds) + 20), check=False)
|
|
438
|
+
else:
|
|
439
|
+
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
|
|
440
|
+
text=True, encoding='utf-8', errors='replace')
|
|
441
|
+
deadline = time.monotonic() + max(1, int(timeout_seconds) + 20)
|
|
442
|
+
try:
|
|
443
|
+
while True:
|
|
444
|
+
checkpoint()
|
|
445
|
+
remaining = deadline - time.monotonic()
|
|
446
|
+
if remaining <= 0:
|
|
447
|
+
raise subprocess.TimeoutExpired(command, timeout_seconds)
|
|
448
|
+
try:
|
|
449
|
+
stdout, stderr = process.communicate(timeout=min(.25, remaining))
|
|
450
|
+
completed = subprocess.CompletedProcess(command, process.returncode, stdout, stderr)
|
|
451
|
+
break
|
|
452
|
+
except subprocess.TimeoutExpired:
|
|
453
|
+
continue
|
|
454
|
+
except BaseException:
|
|
455
|
+
# Cleanup before terminating the harness; its PID/start time
|
|
456
|
+
# ownership record excludes Excel instances opened by users.
|
|
457
|
+
_cleanup_excel_process(state_path)
|
|
458
|
+
process.terminate()
|
|
459
|
+
try:
|
|
460
|
+
process.communicate(timeout=10)
|
|
461
|
+
except subprocess.TimeoutExpired:
|
|
462
|
+
process.kill()
|
|
463
|
+
process.communicate()
|
|
464
|
+
raise
|
|
379
465
|
except subprocess.TimeoutExpired as exc:
|
|
380
466
|
_cleanup_excel_process(state_path)
|
|
381
467
|
raise FormulaValueError("Excel recalculation exceeded the hard timeout") from exc
|
|
@@ -463,7 +549,7 @@ def _formula_cache_presence(path: Path) -> dict[tuple[str, str], bool]:
|
|
|
463
549
|
|
|
464
550
|
|
|
465
551
|
def _materialize_from_result(source: Path, calculated: Path, output: Path,
|
|
466
|
-
formula_keys: set[tuple[str, str]]) -> Path:
|
|
552
|
+
formula_keys: set[tuple[str, str]], *, allow_errors: bool = False) -> Path:
|
|
467
553
|
keep_vba = source.suffix.lower() == ".xlsm"
|
|
468
554
|
try:
|
|
469
555
|
original = load_workbook(source, data_only=False, keep_links=True, keep_vba=keep_vba)
|
|
@@ -478,6 +564,14 @@ def _materialize_from_result(source: Path, calculated: Path, output: Path,
|
|
|
478
564
|
source_cell = original[sheet_name][coordinate]
|
|
479
565
|
result_cell = values[sheet_name][coordinate]
|
|
480
566
|
value = result_cell.value
|
|
567
|
+
if result_cell.data_type == "e" and allow_errors:
|
|
568
|
+
if not isinstance(value, str) or value not in _ERROR_VALUES:
|
|
569
|
+
raise FormulaValueError(f"Invalid Excel error result at {sheet_name}!{coordinate}: {value}")
|
|
570
|
+
# Historical errors are typed unknowns, never literal text or
|
|
571
|
+
# invented numeric results. Consumers must require review.
|
|
572
|
+
source_cell.value = value
|
|
573
|
+
source_cell.data_type = "e"
|
|
574
|
+
continue
|
|
481
575
|
_validate_result(value, sheet_name, coordinate, result_cell.data_type)
|
|
482
576
|
# A missing <v> cache is different from a legitimate cached empty
|
|
483
577
|
# string. Excel's data_only reader returns None in both unusual
|
|
@@ -513,7 +607,7 @@ def _materialize_from_result(source: Path, calculated: Path, output: Path,
|
|
|
513
607
|
return output
|
|
514
608
|
|
|
515
609
|
|
|
516
|
-
def materialize_values(source_path: Path | str, output_path: Path | str) -> Path:
|
|
610
|
+
def materialize_values(source_path: Path | str, output_path: Path | str, *, allow_errors: bool = False) -> Path:
|
|
517
611
|
"""Calculate every formula in ``source_path`` and emit a literal snapshot.
|
|
518
612
|
|
|
519
613
|
The source is never opened by Excel and is never modified. A workbook with
|
|
@@ -537,8 +631,8 @@ def materialize_values(source_path: Path | str, output_path: Path | str) -> Path
|
|
|
537
631
|
except Exception as exc:
|
|
538
632
|
raise FormulaValueError(f"Cannot open workbook for formula inspection: {exc}") from exc
|
|
539
633
|
try:
|
|
540
|
-
formulas = _scan_formulas(workbook)
|
|
541
|
-
_scan_defined_names(workbook)
|
|
634
|
+
formulas = _scan_formulas(workbook, allow_errors=allow_errors)
|
|
635
|
+
_scan_defined_names(workbook, allow_errors=allow_errors)
|
|
542
636
|
finally:
|
|
543
637
|
workbook.close()
|
|
544
638
|
if not formulas:
|
|
@@ -557,7 +651,8 @@ def materialize_values(source_path: Path | str, output_path: Path | str) -> Path
|
|
|
557
651
|
shutil.copy2(source, temporary_source)
|
|
558
652
|
_run_excel_recalculate(temporary_source, temporary_result, timeout_seconds)
|
|
559
653
|
return _materialize_from_result(source, temporary_result, output,
|
|
560
|
-
{(sheet, coordinate) for sheet, coordinate, _ in formulas}
|
|
654
|
+
{(sheet, coordinate) for sheet, coordinate, _ in formulas},
|
|
655
|
+
allow_errors=allow_errors)
|
|
561
656
|
finally:
|
|
562
657
|
shutil.rmtree(temp_dir, ignore_errors=True)
|
|
563
658
|
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
<!doctype html>
|
|
2
|
+
<html lang="zh-CN"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
|
3
|
+
<title>Excel 冲突解析进度</title>
|
|
4
|
+
<style>
|
|
5
|
+
:root{--ink:#24221d;--paper:#fffdf4;--gold:#f2cb54;--muted:#777367}*{box-sizing:border-box}
|
|
6
|
+
body{margin:0;background:#eeeadd;color:var(--ink);font-family:"Microsoft YaHei",sans-serif;min-height:100vh;display:grid;place-items:center;background-image:linear-gradient(#24221d06 1px,transparent 1px),linear-gradient(90deg,#24221d06 1px,transparent 1px);background-size:24px 24px}
|
|
7
|
+
main{width:min(780px,calc(100% - 40px));border:2px solid var(--ink);background:var(--paper);box-shadow:8px 8px 0 var(--ink)}
|
|
8
|
+
header{display:flex;justify-content:space-between;gap:16px;border-bottom:2px solid var(--ink);padding:18px 28px;font-size:12px;font-weight:bold;letter-spacing:2px}
|
|
9
|
+
.status{background:var(--gold);padding:3px 8px;letter-spacing:0}.body{padding:36px 28px}h1{font-size:32px;margin:0 0 12px;font-family:Georgia,"SimSun",serif}.hint{color:var(--muted);font-size:13px;line-height:1.8;margin-bottom:32px}
|
|
10
|
+
.file{font-size:17px;font-weight:bold;overflow-wrap:anywhere;margin:10px 0 24px}.label{font-size:11px;letter-spacing:2px;color:var(--muted)}
|
|
11
|
+
.counts{display:grid;grid-template-columns:1fr 1fr;border:1px solid var(--ink)}.metric{padding:18px}.metric+ .metric{border-left:1px solid var(--ink)}.number{font:32px Consolas,monospace;margin:8px 0}.detail{font-size:12px;color:var(--muted);overflow-wrap:anywhere;min-height:18px}
|
|
12
|
+
progress{display:block;appearance:none;width:100%;height:8px;margin:24px 0 12px;border:0;background:#e4dfd1}progress::-webkit-progress-bar{background:#e4dfd1}progress::-webkit-progress-value{background:var(--ink)}progress:not([value]){animation:pulse 1.4s infinite}
|
|
13
|
+
footer{border-top:2px solid var(--ink);padding:18px 28px;display:flex;align-items:center;justify-content:space-between;gap:20px;font-size:12px}button{font:inherit;font-weight:bold;border:2px solid var(--ink);background:var(--gold);padding:11px 18px;box-shadow:3px 3px 0 var(--ink);cursor:pointer;white-space:nowrap}button:disabled{opacity:.5;cursor:wait;box-shadow:none}button:focus-visible{outline:3px solid #267da0;outline-offset:4px}#error{color:#a32929;white-space:pre-wrap;overflow-wrap:anywhere}
|
|
14
|
+
@keyframes pulse{50%{opacity:.35}}@media(prefers-reduced-motion:reduce){progress:not([value]){animation:none}}@media(max-width:520px){header,.body,footer{padding:20px}h1{font-size:26px}.counts{grid-template-columns:1fr}.metric+.metric{border-left:0;border-top:1px solid var(--ink)}footer{align-items:flex-start;flex-direction:column}}
|
|
15
|
+
</style>
|
|
16
|
+
<main><header><span>XLMERGE / EXCEL 冲突解决工具</span><span class="status" id="state">解析中</span></header>
|
|
17
|
+
<div class="body" aria-live="polite"><h1 id="phase">准备解析工作簿</h1><div class="hint">解析完成后自动进入审阅页面。你可以随时中断本次解析。</div>
|
|
18
|
+
<div class="label">当前工作簿</div><div class="file" id="file">正在读取冲突列表…</div>
|
|
19
|
+
<div class="counts"><div class="metric"><div class="label">已完成工作簿 / 总数</div><div class="number" id="files">— / —</div><div class="detail" id="side">等待解析</div></div><div class="metric"><div class="label">当前阶段 Sheet 已处理 / 总数</div><div class="number" id="sheets">— / —</div><div class="detail" id="sheet">等待 Sheet 对齐</div></div></div>
|
|
20
|
+
<progress id="progress" aria-label="已完成工作簿进度"></progress><div class="detail" id="detail">进度按实际完成数量更新</div><p id="error" role="alert"></p></div>
|
|
21
|
+
<footer><span id="footer">解析期间不会修改仓库表格。</span><button id="cancel">关闭并中断解析</button></footer></main>
|
|
22
|
+
<script>
|
|
23
|
+
let stopping=false, acknowledged=false, finished=false;
|
|
24
|
+
const el=id=>document.getElementById(id);
|
|
25
|
+
async function poll(){
|
|
26
|
+
try{
|
|
27
|
+
const r=await fetch('/api/status',{cache:'no-store'});if(!r.ok)throw Error('无法读取解析进度');const s=await r.json();
|
|
28
|
+
if(s.state==='ready'&&!stopping){location.reload();return;}
|
|
29
|
+
el('phase').textContent=s.phase;el('file').textContent=s.file||'正在读取冲突列表…';
|
|
30
|
+
el('files').textContent=s.fileTotal?`${s.fileDone} / ${s.fileTotal}`:'— / —';
|
|
31
|
+
el('sheets').textContent=s.sheetTotal?`${s.sheetDone} / ${s.sheetTotal}`:'— / —';
|
|
32
|
+
el('sheet').textContent=s.sheet||'整本计算期间不提供逐 Sheet 进度';
|
|
33
|
+
el('side').textContent=({base:'Base 版本',ours:'本地版本',theirs:'远端版本'})[s.side]||s.phase;
|
|
34
|
+
if(s.fileTotal){el('progress').max=s.fileTotal;el('progress').value=s.fileDone;}
|
|
35
|
+
el('state').textContent=({preparing:'解析中',cancelling:'正在中断',cancelled:'已中断',failed:'解析失败'})[s.state]||'已完成';
|
|
36
|
+
if(s.state==='failed'){el('error').textContent=s.error||'解析失败';el('cancel').textContent='关闭页面和服务';}
|
|
37
|
+
if(s.state==='cancelled'){finish();return;}
|
|
38
|
+
}catch(e){if(acknowledged){finish();return;}el('error').textContent=e.message+',正在重试…';}
|
|
39
|
+
if(!finished)setTimeout(poll,500);
|
|
40
|
+
}
|
|
41
|
+
function finish(){finished=true;el('state').textContent='已停止';el('phase').textContent='解析已停止';el('footer').textContent='工作树未修改,可以关闭此页。';el('cancel').disabled=false;el('cancel').textContent='关闭页面';el('cancel').onclick=()=>window.close();if(stopping)window.close();}
|
|
42
|
+
el('cancel').onclick=async()=>{stopping=true;el('cancel').disabled=true;el('cancel').textContent='正在停止计算…';try{const r=await fetch('/api/shutdown',{method:'POST'});if(!r.ok)throw Error('中断请求失败');acknowledged=true;}catch(e){stopping=false;el('cancel').disabled=false;el('error').textContent=e.message;}};
|
|
43
|
+
poll();
|
|
44
|
+
</script></html>
|
|
@@ -16,6 +16,7 @@ if str(SCRIPT_DIR) not in sys.path:
|
|
|
16
16
|
sys.path.insert(0, str(SCRIPT_DIR))
|
|
17
17
|
|
|
18
18
|
from xlsx_conflict import ConflictError, _build_commit_message, apply_manifest, load_manifest
|
|
19
|
+
from prepare_progress import preparation_context, PreparationCancelled, checkpoint
|
|
19
20
|
|
|
20
21
|
|
|
21
22
|
def _payload() -> dict:
|
|
@@ -54,10 +55,11 @@ def _public_manifest(manifest):
|
|
|
54
55
|
}
|
|
55
56
|
|
|
56
57
|
|
|
57
|
-
def serve(manifest_path: Path | str, *, open_browser: bool = True, port: int = 0
|
|
58
|
+
def serve(manifest_path: Path | str, *, open_browser: bool = True, port: int = 0,
|
|
59
|
+
prepare_repo=None, relative_path=None) -> bool:
|
|
58
60
|
manifest_path = Path(manifest_path).resolve()
|
|
59
|
-
manifest = load_manifest(manifest_path)
|
|
60
|
-
if not manifest["files"]:
|
|
61
|
+
manifest = None if prepare_repo else load_manifest(manifest_path)
|
|
62
|
+
if manifest is not None and not manifest["files"]:
|
|
61
63
|
print(
|
|
62
64
|
"Manifest has no conflicts requiring review; use resolve/apply for auto-theirs entries.",
|
|
63
65
|
file=sys.stderr,
|
|
@@ -66,20 +68,59 @@ def serve(manifest_path: Path | str, *, open_browser: bool = True, port: int = 0
|
|
|
66
68
|
html_path = Path(__file__).with_name("merge_ui.html")
|
|
67
69
|
app = Bottle()
|
|
68
70
|
state = {"resolved": False, "server": None}
|
|
71
|
+
lock = threading.Lock()
|
|
72
|
+
cancelled = threading.Event()
|
|
73
|
+
status = {'state': 'preparing' if prepare_repo else 'ready', 'phase': '开始解析',
|
|
74
|
+
'file': '', 'fileDone': 0, 'fileTotal': 0, 'sheet': '', 'sheetDone': 0, 'sheetTotal': 0, 'side': ''}
|
|
75
|
+
|
|
76
|
+
def report(progress):
|
|
77
|
+
with lock:
|
|
78
|
+
status.update(progress)
|
|
79
|
+
|
|
80
|
+
def prepare():
|
|
81
|
+
nonlocal manifest
|
|
82
|
+
try:
|
|
83
|
+
from xlsx_conflict import prepare_conflicts
|
|
84
|
+
with preparation_context(report, cancelled):
|
|
85
|
+
path = prepare_conflicts(prepare_repo, relative_path=relative_path, runtime_dir=manifest_path.parent)
|
|
86
|
+
checkpoint()
|
|
87
|
+
prepared = load_manifest(path)
|
|
88
|
+
with lock:
|
|
89
|
+
if cancelled.is_set():
|
|
90
|
+
raise PreparationCancelled()
|
|
91
|
+
manifest = prepared
|
|
92
|
+
status.update(state='ready', phase='可开始审阅')
|
|
93
|
+
except PreparationCancelled:
|
|
94
|
+
report({'state': 'cancelled', 'phase': '已中断,工作树未修改'})
|
|
95
|
+
except Exception as exc:
|
|
96
|
+
report({'state': 'failed', 'error': str(exc), 'phase': '解析失败'})
|
|
97
|
+
|
|
98
|
+
worker = threading.Thread(target=prepare, name='xlmerge-prepare') if prepare_repo else None
|
|
69
99
|
|
|
70
100
|
@app.get("/")
|
|
71
101
|
def index():
|
|
72
102
|
response.content_type = "text/html; charset=utf-8"
|
|
73
|
-
|
|
103
|
+
with lock:
|
|
104
|
+
ready = status['state'] == 'ready'
|
|
105
|
+
return (html_path if ready else html_path.with_name('loading_ui.html')).read_text(encoding="utf-8")
|
|
106
|
+
|
|
107
|
+
@app.get('/api/status')
|
|
108
|
+
def progress():
|
|
109
|
+
with lock:
|
|
110
|
+
return _json(dict(status))
|
|
74
111
|
|
|
75
112
|
@app.get("/api/diff")
|
|
76
113
|
def diff():
|
|
114
|
+
if manifest is None:
|
|
115
|
+
return _json({'error': '解析尚未完成'}, 409)
|
|
77
116
|
return _json(_public_manifest(manifest))
|
|
78
117
|
|
|
79
118
|
@app.post("/api/commit-preview")
|
|
80
119
|
def commit_preview():
|
|
81
120
|
"""只读:按当前 decisions 生成结构化 commit 信息,不执行任何写操作。"""
|
|
82
121
|
payload = _payload()
|
|
122
|
+
if manifest is None:
|
|
123
|
+
return _json({'error': '解析尚未完成'}, 409)
|
|
83
124
|
try:
|
|
84
125
|
message = _build_commit_message(manifest, payload.get("decisions") or {})
|
|
85
126
|
return _json({"message": message})
|
|
@@ -89,6 +130,8 @@ def serve(manifest_path: Path | str, *, open_browser: bool = True, port: int = 0
|
|
|
89
130
|
@app.post("/api/resolve")
|
|
90
131
|
def resolve():
|
|
91
132
|
payload = _payload()
|
|
133
|
+
if manifest is None:
|
|
134
|
+
return _json({'error': '解析尚未完成'}, 409)
|
|
92
135
|
try:
|
|
93
136
|
result = apply_manifest(
|
|
94
137
|
manifest_path,
|
|
@@ -110,11 +153,21 @@ def serve(manifest_path: Path | str, *, open_browser: bool = True, port: int = 0
|
|
|
110
153
|
|
|
111
154
|
@app.post("/api/shutdown")
|
|
112
155
|
def shutdown():
|
|
113
|
-
|
|
156
|
+
with lock:
|
|
157
|
+
if status['state'] == 'preparing':
|
|
158
|
+
cancelled.set()
|
|
159
|
+
status['state'] = 'cancelling'
|
|
160
|
+
def stop():
|
|
161
|
+
if worker:
|
|
162
|
+
worker.join()
|
|
163
|
+
state['server'].shutdown()
|
|
164
|
+
threading.Thread(target=stop, daemon=True).start()
|
|
114
165
|
return _json({"success": True})
|
|
115
166
|
|
|
116
167
|
server = make_server("127.0.0.1", port, app)
|
|
117
168
|
state["server"] = server
|
|
169
|
+
if worker:
|
|
170
|
+
worker.start()
|
|
118
171
|
url = f"http://127.0.0.1:{server.server_port}"
|
|
119
172
|
print(f"MERGE_SERVER_URL={url}", flush=True)
|
|
120
173
|
if open_browser:
|