@kevlns/xlmerge 2.0.5 → 2.0.7

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.
@@ -1,2381 +1,2381 @@
1
- """Three-way, sheet-aware XLSX conflict detection and merge primitives."""
2
-
3
- from __future__ import annotations
4
-
5
- import hashlib
6
- import io
7
- import json
8
- import os
9
- import re
10
- import shutil
11
- import subprocess
12
- import sys
13
- import tempfile
14
- import zipfile
15
- from copy import copy
16
- from datetime import date, datetime, time
17
- from pathlib import Path
18
- from typing import Any, Iterable
19
-
20
- from openpyxl import load_workbook
21
- from openpyxl.cell.cell import MergedCell
22
- from openpyxl.utils import column_index_from_string, get_column_letter
23
- from openpyxl.utils.datetime import to_excel
24
-
25
- # 兼容嵌入式 Python(._pth 忽略 PYTHONPATH):包内自举,将包根加入 sys.path
26
- _PKG_ROOT = Path(__file__).resolve().parents[1]
27
- if str(_PKG_ROOT) not in sys.path:
28
- sys.path.insert(0, str(_PKG_ROOT))
29
-
30
- from xlsx_merge_engine.xlsx_git_merge_bridge import analyze_workbooks as analyze_structural_workbooks
31
- from prepare_progress import checkpoint, PreparationCancelled
32
-
33
-
34
- class ConflictError(RuntimeError):
35
- """Raised when a conflict cannot be prepared or resolved safely."""
36
-
37
-
38
- WORKBOOK_EXTENSIONS = {".xlsx", ".xlsm"}
39
-
40
-
41
- def _is_supported_workbook(path: str | Path) -> bool:
42
- return Path(path).suffix.lower() in WORKBOOK_EXTENSIONS
43
-
44
-
45
- def _is_macro_workbook(path: str | Path) -> bool:
46
- return Path(path).suffix.lower() == ".xlsm"
47
-
48
-
49
- CONFIG_FILENAME = ".xlmerge.json"
50
-
51
-
52
- def _normalize_filter_path(pattern: str) -> str:
53
- normalized = pattern.replace("\\", "/").strip()
54
- while normalized.startswith("./"):
55
- normalized = normalized[2:]
56
- parts = normalized.split("/")
57
- if (
58
- not normalized
59
- or Path(normalized).is_absolute()
60
- or any(part in ("", ".", "..") for part in parts)
61
- or not _is_supported_workbook(normalized)
62
- ):
63
- raise ConflictError("Filter must be a relative .xlsx/.xlsm path without empty, '.' or '..' segments.")
64
- return normalized
65
-
66
-
67
- def load_auto_theirs_filters(repo: Path | str) -> list[str]:
68
- """Load repository-scoped auto-theirs suffix filters; missing config means no filters."""
69
- repo_root = find_repo_root(repo)
70
- config_path = repo_root / CONFIG_FILENAME
71
- if not config_path.exists():
72
- return []
73
- try:
74
- data = json.loads(config_path.read_text(encoding="utf-8"))
75
- except (OSError, json.JSONDecodeError) as exc:
76
- raise ConflictError(f"Invalid {CONFIG_FILENAME}: {exc}") from exc
77
- if not isinstance(data, dict) or not isinstance(data.get("autoTheirs", []), list):
78
- raise ConflictError(f"Invalid {CONFIG_FILENAME}: 'autoTheirs' must be an array.")
79
- filters: list[str] = []
80
- for value in data.get("autoTheirs", []):
81
- if not isinstance(value, str):
82
- raise ConflictError(f"Invalid {CONFIG_FILENAME}: every autoTheirs entry must be a string.")
83
- filters.append(_normalize_filter_path(value))
84
- return filters
85
-
86
-
87
- def add_auto_theirs_filter(repo: Path | str, pattern: str) -> dict[str, Any]:
88
- """Persist one repository-scoped auto-theirs suffix filter atomically."""
89
- repo_root = find_repo_root(repo)
90
- normalized = _normalize_filter_path(pattern)
91
- config_path = repo_root / CONFIG_FILENAME
92
- data: dict[str, Any] = {}
93
- if config_path.exists():
94
- try:
95
- loaded = json.loads(config_path.read_text(encoding="utf-8"))
96
- except (OSError, json.JSONDecodeError) as exc:
97
- raise ConflictError(f"Invalid {CONFIG_FILENAME}: {exc}") from exc
98
- if not isinstance(loaded, dict):
99
- raise ConflictError(f"Invalid {CONFIG_FILENAME}: root must be an object.")
100
- data = loaded
101
- filters = load_auto_theirs_filters(repo_root)
102
- existing = {value.lower() for value in filters}
103
- added = normalized.lower() not in existing
104
- if added:
105
- filters.append(normalized)
106
- data["autoTheirs"] = filters
107
- temp_path = config_path.with_name(f".{config_path.name}.{os.getpid()}.tmp")
108
- try:
109
- temp_path.write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
110
- os.replace(temp_path, config_path)
111
- finally:
112
- temp_path.unlink(missing_ok=True)
113
- return {
114
- "config": str(config_path),
115
- "filter": normalized,
116
- "added": added,
117
- "filters": filters,
118
- }
119
-
120
-
121
- def auto_theirs_path(relative_path: str, filters: Iterable[str]) -> str | None:
122
- """Return the canonical filter for a case-insensitive path-suffix match."""
123
- parts = relative_path.replace("\\", "/").lower().split("/")
124
- for pattern in filters:
125
- expected = pattern.lower().split("/")
126
- if len(parts) >= len(expected) and parts[-len(expected):] == expected:
127
- return pattern
128
- return None
129
-
130
-
131
- def _is_macro_payload_entry(name: str) -> bool:
132
- lowered = name.lower()
133
- return (
134
- lowered.startswith(("xl/vba", "xl/ctrlprops/", "customui/", "xl/activex/"))
135
- or (lowered.startswith("xl/drawings/") and "vmldrawing" in lowered and lowered.endswith(".vml"))
136
- or (lowered.startswith("xl/media/") and lowered.endswith(".emf"))
137
- )
138
-
139
-
140
- def _macro_payload_digest(source: bytes | Path | str) -> tuple[str, list[str]]:
141
- raw = source if isinstance(source, bytes) else Path(source).read_bytes()
142
- try:
143
- with zipfile.ZipFile(io.BytesIO(raw)) as archive:
144
- entries = sorted(name for name in archive.namelist() if _is_macro_payload_entry(name))
145
- digest = hashlib.sha256()
146
- for name in entries:
147
- digest.update(name.encode("utf-8"))
148
- digest.update(b"\0")
149
- digest.update(archive.read(name))
150
- return digest.hexdigest(), entries
151
- except (OSError, zipfile.BadZipFile) as exc:
152
- raise ConflictError(f"Invalid macro-enabled workbook package: {exc}") from exc
153
-
154
-
155
- def _macro_payload_info(base_blob: bytes | None, ours_blob: bytes, theirs_blob: bytes) -> dict[str, Any]:
156
- base_hash, base_entries = _macro_payload_digest(base_blob) if base_blob is not None else (None, [])
157
- ours_hash, ours_entries = _macro_payload_digest(ours_blob)
158
- theirs_hash, theirs_entries = _macro_payload_digest(theirs_blob)
159
- ours_key = (ours_hash, ours_entries)
160
- theirs_key = (theirs_hash, theirs_entries)
161
- base_key = (base_hash, base_entries) if base_hash is not None else None
162
- compatible = ours_entries == theirs_entries
163
- if ours_key == theirs_key:
164
- status, default = "same", "ours"
165
- elif not compatible:
166
- status, default = "incompatible", "ours"
167
- elif base_key is not None and ours_key == base_key:
168
- status, default = "auto_theirs", "theirs"
169
- elif base_key is not None and theirs_key == base_key:
170
- status, default = "auto_ours", "ours"
171
- else:
172
- status, default = "conflict", "ours"
173
- return {
174
- "status": status,
175
- "default": default,
176
- "canChooseTheirs": compatible,
177
- "baseHash": base_hash,
178
- "oursHash": ours_hash,
179
- "theirsHash": theirs_hash,
180
- "baseEntries": base_entries,
181
- "oursEntries": ours_entries,
182
- "theirsEntries": theirs_entries,
183
- }
184
-
185
-
186
- def _replace_macro_payload(target: Path, source: Path | str) -> None:
187
- source_path = Path(source)
188
- with zipfile.ZipFile(target) as target_archive, zipfile.ZipFile(source_path) as source_archive:
189
- target_parts = [
190
- (info, target_archive.read(info.filename))
191
- for info in target_archive.infolist()
192
- if not _is_macro_payload_entry(info.filename)
193
- ]
194
- source_parts = [
195
- (info, source_archive.read(info.filename))
196
- for info in source_archive.infolist()
197
- if _is_macro_payload_entry(info.filename)
198
- ]
199
- fd, replacement_name = tempfile.mkstemp(prefix=f".{target.stem}-macro-", suffix=target.suffix, dir=target.parent)
200
- os.close(fd)
201
- replacement = Path(replacement_name)
202
- try:
203
- with zipfile.ZipFile(replacement, "w") as output_archive:
204
- for info, payload in [*target_parts, *source_parts]:
205
- output_archive.writestr(info, payload)
206
- os.replace(replacement, target)
207
- finally:
208
- replacement.unlink(missing_ok=True)
209
-
210
-
211
- def _close_workbook(workbook) -> None:
212
- if workbook is None:
213
- return
214
- vba_archive = getattr(workbook, "vba_archive", None)
215
- workbook.close()
216
- if vba_archive is not None:
217
- vba_archive.close()
218
-
219
-
220
- def _run_git(repo: Path, args: list[str], *, binary: bool = False, check: bool = False):
221
- result = subprocess.run(
222
- ["git", "-C", str(repo), "-c", "core.quotepath=false", *args],
223
- capture_output=True,
224
- text=not binary,
225
- encoding=None if binary else "utf-8",
226
- errors=None if binary else "replace",
227
- timeout=60,
228
- )
229
- if check and result.returncode != 0:
230
- stderr = result.stderr.decode("utf-8", "replace") if binary else result.stderr
231
- raise ConflictError(f"git {' '.join(args)} failed: {stderr.strip()}")
232
- return result
233
-
234
-
235
- def find_repo_root(repo: Path | str) -> Path:
236
- candidate = Path(repo).resolve()
237
- result = _run_git(candidate, ["rev-parse", "--show-toplevel"])
238
- if result.returncode != 0:
239
- raise ConflictError(f"Not a Git repository: {candidate}")
240
- return Path(result.stdout.strip()).resolve()
241
-
242
-
243
- def detect_conflicts(repo: Path | str) -> list[dict[str, Any]]:
244
- repo_root = find_repo_root(repo)
245
- result = _run_git(repo_root, ["diff", "--name-only", "--diff-filter=U", "-z"], binary=True, check=True)
246
- paths = result.stdout.decode("utf-8", "surrogateescape").split("\0")
247
- conflicts: list[dict[str, Any]] = []
248
- for relative_path in paths:
249
- if not relative_path or not _is_supported_workbook(relative_path):
250
- continue
251
- stages_result = _run_git(repo_root, ["ls-files", "-u", "--", relative_path], check=True)
252
- stages: list[int] = []
253
- for line in stages_result.stdout.splitlines():
254
- prefix = line.split("\t", 1)[0].split()
255
- if len(prefix) >= 3:
256
- stages.append(int(prefix[2]))
257
- conflicts.append({"path": relative_path.replace("\\", "/"), "stages": sorted(set(stages))})
258
- return conflicts
259
-
260
-
261
- def _git_blob(repo: Path, stage: int, relative_path: str) -> bytes | None:
262
- result = _run_git(repo, ["show", f":{stage}:{relative_path}"], binary=True)
263
- return result.stdout if result.returncode == 0 else None
264
-
265
-
266
- def _safe_runtime_dir(repo: Path, runtime_dir: Path | str | None) -> Path:
267
- if runtime_dir:
268
- target = Path(runtime_dir).resolve()
269
- else:
270
- repo_key = str(abs(hash(str(repo).lower())))
271
- target = Path(tempfile.gettempdir()) / "xlmerge" / repo_key
272
- target.mkdir(parents=True, exist_ok=True)
273
- return target
274
-
275
-
276
- def _slug(relative_path: str) -> str:
277
- safe = "".join(ch if ch.isalnum() or ch in "-_." else "_" for ch in relative_path)
278
- return safe[-120:] or "workbook"
279
-
280
-
281
- def _repair_invalid_dimension_styles(path: Path) -> None:
282
- """Remove row or column style ids missing from an extracted style table."""
283
- with zipfile.ZipFile(path, "r") as source:
284
- try:
285
- styles = source.read("xl/styles.xml")
286
- except KeyError:
287
- return
288
- cell_xfs = re.search(rb"<cellXfs\b[^>]*>(.*?)</cellXfs>", styles, re.DOTALL)
289
- if cell_xfs is None:
290
- return
291
- style_count = len(re.findall(rb"<xf\b", cell_xfs.group(1)))
292
- replacements: dict[str, bytes] = {}
293
- for name in source.namelist():
294
- if not name.startswith("xl/worksheets/") or not name.endswith(".xml"):
295
- continue
296
- payload = source.read(name)
297
-
298
- def repair_row(match: re.Match[bytes]) -> bytes:
299
- tag = match.group(0)
300
- style = re.search(rb'\bs="(\d+)"', tag)
301
- if style is None or int(style.group(1)) < style_count:
302
- return tag
303
- tag = re.sub(rb'\s+s="\d+"', b"", tag, count=1)
304
- return re.sub(rb'\s+customFormat="[01]"', b"", tag, count=1)
305
-
306
- repaired = re.sub(rb"<row\b[^>]*>", repair_row, payload)
307
- def repair_column(match: re.Match[bytes]) -> bytes:
308
- tag = match.group(0)
309
- style = re.search(rb'\bstyle="(\d+)"', tag)
310
- if style is None or int(style.group(1)) < style_count:
311
- return tag
312
- return re.sub(rb'\s+style="\d+"', b"", tag, count=1)
313
-
314
- repaired = re.sub(rb"<col\b[^>]*/?>", repair_column, repaired)
315
- if repaired != payload:
316
- replacements[name] = repaired
317
- if not replacements:
318
- return
319
- entries = [(info, replacements.get(info.filename, source.read(info.filename))) for info in source.infolist()]
320
-
321
- temporary = path.with_name(f".{path.name}.row-styles.tmp")
322
- try:
323
- with zipfile.ZipFile(temporary, "w") as output:
324
- for info, payload in entries:
325
- output.writestr(info, payload)
326
- os.replace(temporary, path)
327
- finally:
328
- if temporary.exists():
329
- temporary.unlink()
330
-
331
-
332
- def _json_value(value: Any) -> Any:
333
- if value is None or isinstance(value, (bool, int, float, str)):
334
- return value
335
- if isinstance(value, (datetime, date, time)):
336
- return value.isoformat()
337
- return str(value)
338
-
339
-
340
- def _sha256_path(path: Path | str) -> str:
341
- """Return a content digest without loading large workbook into memory."""
342
- digest = hashlib.sha256()
343
- with Path(path).open("rb") as handle:
344
- for block in iter(lambda: handle.read(1024 * 1024), b""):
345
- digest.update(block)
346
- return digest.hexdigest()
347
-
348
-
349
- def _workbook_has_formula(path: Path | str) -> bool:
350
- workbook = load_workbook(path, data_only=False, keep_links=True, read_only=True)
351
- try:
352
- return any(
353
- cell.data_type == "f"
354
- for ws in workbook.worksheets
355
- for row in ws.iter_rows()
356
- for cell in row
357
- )
358
- finally:
359
- workbook.close()
360
-
361
-
362
- def _validate_value_workbook(path: Path | str, *, allow_errors: bool = False) -> list[dict[str, Any]]:
363
- """Validate literal snapshots; only history can contain typed unknowns."""
364
- from formula_values import _ERROR_VALUES
365
- errors = []
366
- workbook = load_workbook(path, data_only=False, keep_links=True, read_only=True)
367
- try:
368
- for ws in workbook.worksheets:
369
- for row in ws.iter_rows():
370
- for cell in row:
371
- if cell.data_type == "f":
372
- raise ConflictError(
373
- f"Formula materialization produced a formula in {path} ({ws.title}!{cell.coordinate})."
374
- )
375
- if cell.data_type == "e":
376
- if not isinstance(cell.value, str) or cell.value not in _ERROR_VALUES:
377
- raise ConflictError(f"Invalid Excel error at {ws.title}!{cell.coordinate}: {cell.value}")
378
- if not allow_errors:
379
- raise ConflictError(
380
- f"Formula materialization produced an Excel error in {path} ({ws.title}!{cell.coordinate})."
381
- )
382
- errors.append({"sheet": ws.title, "coordinate": cell.coordinate, "error": cell.value})
383
- finally:
384
- workbook.close()
385
- return errors
386
-
387
-
388
- def _materialize_value_snapshot(source_path: Path | str, output_path: Path | str | None, *, allow_errors: bool = False) -> Path:
389
- """Calculate one complete source workbook and return its literal snapshot.
390
-
391
- The implementation lives in formula_values.py so Excel/LibreOffice policy is
392
- kept in one place. This wrapper intentionally validates its contract at the
393
- boundary: a successful return that still contains formulas is unsafe.
394
- """
395
- source = Path(source_path).resolve()
396
- if output_path is None:
397
- output_path = source.with_name(f"{source.stem}.values{source.suffix}")
398
- destination = Path(output_path).resolve()
399
- destination.parent.mkdir(parents=True, exist_ok=True)
400
- try:
401
- from formula_values import materialize_values
402
- except ImportError as exc:
403
- raise ConflictError("Formula materialization is unavailable; refusing to compare formula workbooks.") from exc
404
- try:
405
- result = materialize_values(source, destination, allow_errors=allow_errors)
406
- except PreparationCancelled:
407
- raise
408
- except Exception as exc:
409
- raise ConflictError(f"Failed to calculate workbook {source}: {exc}") from exc
410
- value_path = Path(result) if result is not None else destination
411
- if not value_path.is_absolute():
412
- value_path = (destination.parent / value_path).resolve()
413
- if not value_path.exists():
414
- raise ConflictError(f"Formula materialization did not produce a workbook for {source}.")
415
- _validate_value_workbook(value_path, allow_errors=allow_errors)
416
- return value_path
417
-
418
-
419
- def _snapshot_workbooks(
420
- base_path: Path | str | None,
421
- ours_path: Path | str,
422
- theirs_path: Path | str,
423
- analysis_dir: Path,
424
- ) -> tuple[dict[str, Path | None], dict[str, dict[str, Any]]]:
425
- """Create and describe immutable value snapshots for all three sides."""
426
- analysis_dir.mkdir(parents=True, exist_ok=True)
427
- sources = {"base": Path(base_path).resolve() if base_path else None,
428
- "ours": Path(ours_path).resolve(), "theirs": Path(theirs_path).resolve()}
429
- snapshots: dict[str, Path | None] = {}
430
- metadata: dict[str, dict[str, Any]] = {}
431
- for side, source in sources.items():
432
- checkpoint(phase='计算公式并验证', side=side, sheet='', sheetDone=0, sheetTotal=0)
433
- if source is None:
434
- snapshots[side] = None
435
- continue
436
- source_hash = _sha256_path(source)
437
- # No-formula workbooks are already valid value snapshots. Avoid a
438
- # needless package rewrite (and preserve exact zip bytes for safety).
439
- if _workbook_has_formula(source):
440
- output = analysis_dir / f"{side}.values{source.suffix.lower()}"
441
- value_path = _materialize_value_snapshot(source, output, allow_errors=True)
442
- else:
443
- value_path = source
444
- _validate_value_workbook(value_path, allow_errors=True)
445
- snapshots[side] = value_path
446
- metadata[side] = {
447
- "sourcePath": str(source),
448
- "sourceSha256": source_hash,
449
- "valuePath": str(value_path),
450
- "valueSha256": _sha256_path(value_path),
451
- }
452
- errors = _validate_value_workbook(value_path, allow_errors=True)
453
- metadata[side]["errors"] = errors
454
- if errors:
455
- source_book = load_workbook(source, data_only=False, keep_links=False)
456
- try:
457
- for error in errors:
458
- error["formula"] = source_book[error["sheet"]][error["coordinate"]].value
459
- error.update(_repair_field_info(source_book[error['sheet']], error['coordinate']))
460
- finally:
461
- source_book.close()
462
- _replace_common_errors(snapshots, metadata, analysis_dir)
463
- return snapshots, metadata
464
-
465
-
466
- def _repair_field_info(ws, coordinate):
467
- column = ws[coordinate].column
468
- var = next((r for r in range(1, min(ws.max_row, 40) + 1) if ws.cell(r, 1).value == '##var'), None)
469
- typ = next((r for r in range(1, min(ws.max_row, 80) + 1) if ws.cell(r, 1).value == '##type'), None)
470
- if var is None or typ is None:
471
- return {}
472
- field = str(ws.cell(var, column).value or '')
473
- kind = str(ws.cell(typ, column).value or '').strip().casefold()
474
- info = {'field': field, 'type': kind}
475
- default = '' if kind == 'string' else False if kind == 'bool' else 0
476
- try:
477
- _validate_repair_value(kind, default)
478
- except ConflictError:
479
- return info
480
- guarded = field.casefold().endswith('id') or 'ref' in field.casefold() or any(
481
- ws.cell(r, 1).value in ('##ref', '##refs', '##key', '##index', '##validator', '##validate', '##validation', '##min', '##max', '##range', '##constraint')
482
- and ws.cell(r, column).value not in (None, '') for r in range(var, typ + 10))
483
- if not guarded:
484
- info['defaultValue'] = default
485
- return info
486
-
487
-
488
- def _validate_repair_value(kind, value):
489
- import math
490
- if not kind and type(value) in (int, float) and math.isfinite(value):
491
- return
492
- if kind == 'string' and isinstance(value, str):
493
- return
494
- if kind == 'bool' and isinstance(value, bool):
495
- return
496
- if kind in ('float', 'double', 'decimal') and type(value) in (int, float) and math.isfinite(value):
497
- return
498
- match = re.fullmatch(r'(u?int)(8|16|32|64)?|(s?byte|u?short|u?long)', kind)
499
- if match and type(value) is int:
500
- bits = int(match.group(2) or 32) if match.group(1) else {'byte': 8, 'sbyte': 8, 'short': 16, 'ushort': 16, 'long': 64, 'ulong': 64}[kind]
501
- unsigned = kind.startswith('u') or kind == 'byte'
502
- if (0 if unsigned else -(2 ** (bits - 1))) <= value <= 2 ** (bits if unsigned else bits - 1) - 1:
503
- return
504
- raise ConflictError(f'修复值不符合声明类型 {kind!r};ID/引用值还需人工核对业务有效性。')
505
-
506
-
507
- def _selected_repairs(sheet, selection):
508
- side = selection.get('sheet')
509
- errors = [e for e in sheet.get('calculationErrors', []) if e['side'] == side]
510
- values = (selection.get('repairs') or {}).get(side, {})
511
- if not isinstance(values, dict):
512
- raise ConflictError('修复值必须按单元格提供。')
513
- allowed = {e['coordinate']: e for e in errors}
514
- if set(values) - set(allowed):
515
- raise ConflictError('修复包含未经审阅的单元格。')
516
- for coordinate, value in values.items():
517
- _validate_repair_value(allowed[coordinate].get('type', ''), value)
518
- for error in errors:
519
- if error['coordinate'] not in values:
520
- raise ConflictError(f"请修复所选 {side} 来源的 {sheet['name']}!{error['coordinate']}: {error['error']}")
521
- return values
522
-
523
-
524
- def _error_replacement_schema(ws):
525
- """Only explicit primitive Luban fields with unique, valid IDs qualify."""
526
- var_row = next((row for row in range(1, min(ws.max_row, 40) + 1)
527
- if ws.cell(row, 1).value == "##var"), None)
528
- if var_row is None:
529
- return None
530
- type_row = next((row for row in range(var_row + 1, min(ws.max_row, var_row + 40) + 1)
531
- if ws.cell(row, 1).value == "##type"), None)
532
- if type_row is None:
533
- return None
534
- fields = {}
535
- duplicates = set()
536
- for cell in list(ws._cells.values()):
537
- if cell.row != var_row or cell.column == 1 or not isinstance(cell.value, str) or not cell.value.strip():
538
- continue
539
- field = cell.value.strip()
540
- if field in fields:
541
- duplicates.add(field)
542
- fields[field] = cell.column
543
- fields = {field: column for field, column in fields.items() if field not in duplicates}
544
- ids = [column for field, column in fields.items() if field.casefold() == "id"]
545
- if len(ids) != 1:
546
- return None
547
- start = var_row
548
- while start <= ws.max_row and isinstance(ws.cell(start, 1).value, str) and ws.cell(start, 1).value.startswith("##"):
549
- start += 1
550
- records, duplicate_ids = {}, set()
551
- for cell in list(ws._cells.values()):
552
- if cell.column != ids[0] or cell.row < start:
553
- continue
554
- if cell.data_type == "e" or cell.value in (None, "") or not isinstance(cell.value, (str, int, float)) or isinstance(cell.value, bool):
555
- continue
556
- key = (cell.data_type, cell.value)
557
- if key in records:
558
- duplicate_ids.add(key)
559
- records[key] = cell.row
560
- records = {key: row for key, row in records.items() if key not in duplicate_ids}
561
- defaults = {}
562
- for field, column in fields.items():
563
- if not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", field) or field.casefold().endswith("id") or "ref" in field.casefold():
564
- continue
565
- if any(ws.cell(row, 1).value in ("##ref", "##refs", "##key", "##index", "##validator", "##validate", "##validation", "##min", "##max", "##range", "##constraint")
566
- and ws.cell(row, column).value not in (None, "") for row in range(var_row, start)):
567
- continue
568
- kind = str(ws.cell(type_row, column).value or "").strip().casefold()
569
- if kind == "string":
570
- defaults[field] = (column, kind, "")
571
- elif kind == "bool":
572
- defaults[field] = (column, kind, False)
573
- elif re.fullmatch(r"(?:s?byte|u?short|u?int|u?long|float|double|decimal|u?int(?:8|16|32|64))", kind):
574
- defaults[field] = (column, kind, 0)
575
- return records, defaults
576
-
577
-
578
- def _replace_common_errors(paths, metadata, analysis_dir):
579
- """Apply authorized defaults only to corresponding errors on both sides.
580
-
581
- Use declared fields and unique IDs before structural alignment. Never
582
- guess types from number formats, errors, or adjacent cells, and never
583
- modify an extracted Git source or the repository working tree.
584
- """
585
- if not all(metadata.get(side, {}).get("errors") for side in ("ours", "theirs")):
586
- return
587
- from formula_values import _set_literal
588
- books = {side: load_workbook(paths[side], keep_vba=paths[side].suffix.lower() == ".xlsm")
589
- for side in ("ours", "theirs")}
590
- replacements = {side: [] for side in books}
591
- try:
592
- errors = {side: {(error["sheet"], error["coordinate"]): error for error in metadata[side]["errors"]}
593
- for side in books}
594
- for name in set(books["ours"].sheetnames) & set(books["theirs"].sheetnames):
595
- schemas = {side: _error_replacement_schema(book[name]) for side, book in books.items()}
596
- if not all(schemas.values()):
597
- continue
598
- ours_rows, ours_fields = schemas["ours"]
599
- theirs_rows, theirs_fields = schemas["theirs"]
600
- by_row = {row: key for key, row in ours_rows.items()}
601
- by_column = {info[0]: field for field, info in ours_fields.items()}
602
- for error in metadata["ours"]["errors"]:
603
- if error["sheet"] != name:
604
- continue
605
- own = books["ours"][name][error["coordinate"]]
606
- key, field = by_row.get(own.row), by_column.get(own.column)
607
- if key not in theirs_rows or field not in theirs_fields or ours_fields[field][1] != theirs_fields[field][1]:
608
- continue
609
- cells = {"ours": own, "theirs": books["theirs"][name].cell(theirs_rows[key], theirs_fields[field][0])}
610
- if not all(cell.data_type == "e" for cell in cells.values()):
611
- continue
612
- kind, value = ours_fields[field][1:]
613
- for side, cell in cells.items():
614
- issue = errors[side][(name, cell.coordinate)]
615
- replacements[side].append({**issue, "field": field, "recordId": key[1], "type": kind, "value": value})
616
- _set_literal(cell, value)
617
- for side, repairs in replacements.items():
618
- if not repairs:
619
- continue
620
- output = analysis_dir / f"{side}.review.values{paths[side].suffix}"
621
- books[side].save(output)
622
- paths[side] = output
623
- removed = {(repair["sheet"], repair["coordinate"]) for repair in repairs}
624
- metadata[side].update(valuePath=str(output), valueSha256=_sha256_path(output), replacements=repairs,
625
- errors=[error for error in metadata[side]["errors"] if (error["sheet"], error["coordinate"]) not in removed])
626
- finally:
627
- for book in books.values():
628
- book.close()
629
-
630
-
631
- def _cell_token(cell, cached_cell=None) -> tuple[Any, str] | None:
632
- if cell is None or isinstance(cell, MergedCell):
633
- return None
634
- # 公式 cell 按缓存值参与比较,避免公式不变但引用值变了被误判为 same
635
- if cell.data_type == 'f' and cached_cell is not None and not isinstance(cached_cell, MergedCell):
636
- return cached_cell.value, cached_cell.data_type
637
- return cell.value, cell.data_type
638
-
639
-
640
- def _cell_display_value(cell, cached_cell) -> Any:
641
- """UI 展示值:公式 cell 取缓存值,其余取原始值。"""
642
- if cell is None or isinstance(cell, MergedCell):
643
- return None
644
- if cell.data_type == 'f' and cached_cell is not None and not isinstance(cached_cell, MergedCell):
645
- return cached_cell.value
646
- return cell.value
647
-
648
-
649
- def _value_cells(ws) -> dict[tuple[int, int], Any]:
650
- if ws is None:
651
- return {}
652
- result = {}
653
- for key, cell in ws._cells.items():
654
- if isinstance(cell, MergedCell):
655
- continue
656
- if cell.value is not None:
657
- result[key] = cell
658
- return result
659
-
660
-
661
- def _sheet_values(ws) -> dict[tuple[int, int], tuple[Any, str] | None]:
662
- return {key: _cell_token(cell) for key, cell in _value_cells(ws).items()}
663
-
664
-
665
- def _sheet_equal(left, right) -> bool:
666
- return _sheet_values(left) == _sheet_values(right)
667
-
668
-
669
- def _ordered_sheet_names(*workbooks) -> list[str]:
670
- names: list[str] = []
671
- for workbook in workbooks:
672
- if workbook is None:
673
- continue
674
- for name in workbook.sheetnames:
675
- if name not in names:
676
- names.append(name)
677
- return names
678
-
679
-
680
- def _context_rows(ws, ws_v, rows: set[int], max_col: int) -> dict[str, list[Any]]:
681
- if ws is None or max_col <= 0:
682
- return {}
683
- header_rows: set[int] = set()
684
- for row in range(1, min(max(ws.max_row or 1, 1), 20) + 1):
685
- value = ws.cell(row, 1).value
686
- if isinstance(value, str) and value.startswith("##"):
687
- header_rows.add(row)
688
- elif header_rows:
689
- break
690
- wanted = sorted(rows | header_rows)
691
- return {
692
- str(row): [_json_value(_cell_display_value(
693
- ws.cell(row, col),
694
- ws_v.cell(row, col) if ws_v is not None else None
695
- )) for col in range(1, max_col + 1)]
696
- for row in wanted
697
- }
698
-
699
-
700
- def _modified_sheet_diff(name, ws_base, ws_ours, ws_theirs,
701
- ws_base_v=None, ws_ours_v=None, ws_theirs_v=None) -> dict[str, Any]:
702
- base_cells = _value_cells(ws_base)
703
- ours_cells = _value_cells(ws_ours)
704
- theirs_cells = _value_cells(ws_theirs)
705
- coordinates = sorted(set(base_cells) | set(ours_cells) | set(theirs_cells))
706
- cells: list[dict[str, Any]] = []
707
- changed_rows: set[int] = set()
708
-
709
- for row, col in coordinates:
710
- base_cell = base_cells.get((row, col))
711
- ours_cell = ours_cells.get((row, col))
712
- theirs_cell = theirs_cells.get((row, col))
713
- base_cached = ws_base_v.cell(row, col) if ws_base_v is not None else None
714
- ours_cached = ws_ours_v.cell(row, col) if ws_ours_v is not None else None
715
- theirs_cached = ws_theirs_v.cell(row, col) if ws_theirs_v is not None else None
716
- base_token = _cell_token(base_cell, base_cached)
717
- ours_token = _cell_token(ours_cell, ours_cached)
718
- theirs_token = _cell_token(theirs_cell, theirs_cached)
719
- if ours_token == theirs_token:
720
- continue
721
- if ours_token == base_token:
722
- resolution = "theirs"
723
- elif theirs_token == base_token:
724
- resolution = "ours"
725
- else:
726
- resolution = "conflict"
727
- changed_rows.add(row)
728
- cells.append({
729
- "row": row,
730
- "col": col,
731
- "coordinate": f"{get_column_letter(col)}{row}",
732
- "base": _json_value(_cell_display_value(base_cell, base_cached)),
733
- "ours": _json_value(_cell_display_value(ours_cell, ours_cached)),
734
- "theirs": _json_value(_cell_display_value(theirs_cell, theirs_cached)),
735
- "resolution": resolution,
736
- })
737
-
738
- preferred_ws = ws_ours or ws_theirs or ws_base
739
- preferred_ws_v = ws_ours_v or ws_theirs_v or ws_base_v
740
- max_col = max([col for _, col in coordinates] or [1])
741
- return {
742
- "name": name,
743
- "action": "merge",
744
- "cells": cells,
745
- "contextRows": _context_rows(preferred_ws, preferred_ws_v, changed_rows, max_col),
746
- "maxCol": max_col,
747
- "changedCount": len(cells),
748
- "conflictCount": sum(cell["resolution"] == "conflict" for cell in cells),
749
- }
750
-
751
-
752
- def _axis_state(status: str, *, ours_present: bool) -> dict[str, Any]:
753
- if status.startswith("added_"):
754
- return {
755
- "state": "added",
756
- "locked": True,
757
- "incoming": status == "added_theirs",
758
- "default": "keep",
759
- }
760
- if status.startswith("delete_modify_"):
761
- return {
762
- "state": "delete_modify",
763
- "locked": False,
764
- "incoming": False,
765
- "default": "keep" if ours_present else "delete",
766
- }
767
- if status.startswith("deleted_"):
768
- return {
769
- "state": "deleted",
770
- "locked": True,
771
- "incoming": False,
772
- "default": "delete",
773
- }
774
- return {"state": "common", "locked": False, "incoming": False, "default": "keep"}
775
-
776
-
777
- def _side_cell(workbook, sheet_name: str | None, row: int | None, column: int | None):
778
- if workbook is None or sheet_name is None or row is None or column is None:
779
- return None
780
- return workbook[sheet_name].cell(row, column)
781
-
782
-
783
- def _cell_resolution(base_cell, ours_cell, theirs_cell, *, has_base: bool,
784
- base_cached=None, ours_cached=None, theirs_cached=None) -> str:
785
- base_token = _cell_token(base_cell, base_cached)
786
- ours_token = _cell_token(ours_cell, ours_cached)
787
- theirs_token = _cell_token(theirs_cell, theirs_cached)
788
- if not has_base:
789
- return "theirs" if theirs_cell is not None else "ours"
790
- if ours_token == theirs_token:
791
- return "same"
792
- if ours_token == base_token:
793
- return "theirs"
794
- if theirs_token == base_token:
795
- return "ours"
796
- return "conflict"
797
-
798
-
799
- def _header_rows(ws) -> list[int]:
800
- if ws is None:
801
- return []
802
- rows = []
803
- for row in range(1, min(ws.max_row or 0, 40) + 1):
804
- marker = ws.cell(row, 1).value
805
- if isinstance(marker, str) and marker.startswith("##"):
806
- rows.append(row)
807
- elif rows:
808
- break
809
- return rows
810
-
811
-
812
- def _merged_region_key(region: dict[str, Any]) -> tuple[tuple[str, ...], tuple[str, ...]]:
813
- return tuple(region["rows"]), tuple(region["columns"])
814
-
815
-
816
- def _canonical_merged_regions(ws, side: str, rows, columns) -> list[dict[str, Any]]:
817
- if ws is None:
818
- return []
819
- header_rows = set(_header_rows(ws))
820
- row_lookup = {
821
- row.get(f"{side}Row"): row["id"]
822
- for row in rows
823
- if row.get(f"{side}Row") is not None
824
- }
825
- column_lookup = {
826
- column.get(f"{side}Col"): column["id"]
827
- for column in columns
828
- if column.get(f"{side}Col") is not None
829
- }
830
- regions = []
831
- for merged_range in ws.merged_cells.ranges:
832
- row_ids = []
833
- for row_number in range(merged_range.min_row, merged_range.max_row + 1):
834
- row_id = f"header:{row_number}" if row_number in header_rows else row_lookup.get(row_number)
835
- if row_id is None:
836
- break
837
- row_ids.append(row_id)
838
- else:
839
- column_ids = []
840
- for column_number in range(merged_range.min_col, merged_range.max_col + 1):
841
- column_id = column_lookup.get(column_number)
842
- if column_id is None:
843
- break
844
- column_ids.append(column_id)
845
- else:
846
- regions.append({"rows": row_ids, "columns": column_ids})
847
- return sorted(regions, key=_merged_region_key)
848
-
849
-
850
- def _regions_overlap(regions: list[dict[str, Any]]) -> bool:
851
- occupied: set[tuple[str, str]] = set()
852
- for region in regions:
853
- cells = {(row, column) for row in region["rows"] for column in region["columns"]}
854
- if occupied & cells:
855
- return True
856
- occupied.update(cells)
857
- return False
858
-
859
-
860
- def _merged_cells_diff(names, rows, columns, wb_base, wb_ours, wb_theirs) -> dict[str, Any]:
861
- workbooks = {"base": wb_base, "ours": wb_ours, "theirs": wb_theirs}
862
- regions = {}
863
- for side, workbook in workbooks.items():
864
- sheet_name = names.get(side)
865
- ws = workbook[sheet_name] if workbook is not None and sheet_name in workbook.sheetnames else None
866
- regions[side] = _canonical_merged_regions(ws, side, rows, columns)
867
-
868
- keyed = {side: {_merged_region_key(item): item for item in items} for side, items in regions.items()}
869
- base_keys, ours_keys, theirs_keys = (set(keyed[side]) for side in ("base", "ours", "theirs"))
870
- if ours_keys == theirs_keys:
871
- status, resolved = "same", regions["ours"]
872
- elif ours_keys == base_keys:
873
- status, resolved = "auto_theirs", regions["theirs"]
874
- elif theirs_keys == base_keys:
875
- status, resolved = "auto_ours", regions["ours"]
876
- else:
877
- all_keys = base_keys | ours_keys | theirs_keys
878
- resolved_keys = set()
879
- for key in all_keys:
880
- base_present = key in base_keys
881
- ours_present = key in ours_keys
882
- theirs_present = key in theirs_keys
883
- if ours_present == theirs_present:
884
- keep = ours_present
885
- elif ours_present == base_present:
886
- keep = theirs_present
887
- else:
888
- keep = ours_present
889
- if keep:
890
- resolved_keys.add(key)
891
- source_items = {**keyed["base"], **keyed["ours"], **keyed["theirs"]}
892
- candidate = [source_items[key] for key in sorted(resolved_keys)]
893
- if _regions_overlap(candidate):
894
- status, resolved = "conflict", []
895
- else:
896
- status, resolved = "auto_merge", candidate
897
- return {
898
- "status": status,
899
- "default": "ours" if status == "conflict" else None,
900
- "base": regions["base"],
901
- "ours": regions["ours"],
902
- "theirs": regions["theirs"],
903
- "resolved": resolved,
904
- }
905
-
906
-
907
- def _structural_sheet_diff(report_sheet, wb_base, wb_ours, wb_theirs,
908
- wb_base_v=None, wb_ours_v=None, wb_theirs_v=None) -> dict[str, Any]:
909
- names = report_sheet.get("names") or {
910
- "base": report_sheet["name"], "ours": report_sheet["name"], "theirs": report_sheet["name"]
911
- }
912
- rows = []
913
- for index, entry in enumerate(report_sheet.get("rowAlignment") or [], 1):
914
- item = dict(entry)
915
- item.update(_axis_state(entry["status"], ours_present=entry.get("oursRow") is not None))
916
- item["display"] = entry.get("oursRow") or entry.get("baseRow") or entry.get("theirsRow") or index
917
- rows.append(item)
918
- columns = []
919
- for index, entry in enumerate(report_sheet.get("columnAlignment") or [], 1):
920
- item = dict(entry)
921
- item["id"] = entry["field"]
922
- item.update(_axis_state(entry["status"], ours_present=entry.get("oursColumn") is not None))
923
- item["baseCol"] = column_index_from_string(entry["baseColumn"]) if entry.get("baseColumn") else None
924
- item["oursCol"] = column_index_from_string(entry["oursColumn"]) if entry.get("oursColumn") else None
925
- item["theirsCol"] = column_index_from_string(entry["theirsColumn"]) if entry.get("theirsColumn") else None
926
- item["display"] = entry.get("oursColumn") or entry.get("baseColumn") or entry.get("theirsColumn") or get_column_letter(index)
927
- columns.append(item)
928
-
929
- all_cells: list[dict[str, Any]] = []
930
- changed_row_ids: set[str] = set()
931
- row_attention: set[str] = set()
932
- for row in rows:
933
- for column in columns:
934
- base_cell = _side_cell(wb_base, names.get("base"), row.get("baseRow"), column.get("baseCol"))
935
- ours_cell = _side_cell(wb_ours, names.get("ours"), row.get("oursRow"), column.get("oursCol"))
936
- theirs_cell = _side_cell(wb_theirs, names.get("theirs"), row.get("theirsRow"), column.get("theirsCol"))
937
- base_cached = _side_cell(wb_base_v, names.get("base"), row.get("baseRow"), column.get("baseCol")) if wb_base_v else None
938
- ours_cached = _side_cell(wb_ours_v, names.get("ours"), row.get("oursRow"), column.get("oursCol")) if wb_ours_v else None
939
- theirs_cached = _side_cell(wb_theirs_v, names.get("theirs"), row.get("theirsRow"), column.get("theirsCol")) if wb_theirs_v else None
940
- base_token = _cell_token(base_cell, base_cached)
941
- ours_token = _cell_token(ours_cell, ours_cached)
942
- theirs_token = _cell_token(theirs_cell, theirs_cached)
943
- has_base = row.get("baseRow") is not None and column.get("baseCol") is not None
944
- error_sides = {side: cell.value for side, cell in
945
- (("base", base_cell), ("ours", ours_cell), ("theirs", theirs_cell))
946
- if cell is not None and cell.data_type == "e"}
947
- changed = bool(error_sides) or not (ours_token == theirs_token == base_token)
948
- structural = row["state"] != "common" or column["state"] != "common"
949
- selectable = (
950
- row["state"] in ("common", "delete_modify")
951
- and column["state"] in ("common", "delete_modify")
952
- )
953
- if changed or structural:
954
- changed_row_ids.add(row["id"])
955
- resolution = _cell_resolution(base_cell, ours_cell, theirs_cell, has_base=has_base,
956
- base_cached=base_cached, ours_cached=ours_cached, theirs_cached=theirs_cached)
957
- if error_sides:
958
- resolution = "conflict"
959
- if changed and resolution != "same":
960
- row_attention.add(row["id"])
961
- stable_id = f'{row["id"]}|{column["id"]}'
962
- display_coordinate = (
963
- f'{get_column_letter(column["oursCol"])}{row["oursRow"]}'
964
- if row.get("oursRow") is not None and column.get("oursCol") is not None
965
- else stable_id
966
- )
967
- all_cells.append({
968
- "id": stable_id,
969
- "coordinate": display_coordinate,
970
- "rowId": row["id"],
971
- "colId": column["id"],
972
- "base": _json_value(_cell_display_value(base_cell, base_cached)),
973
- "ours": _json_value(_cell_display_value(ours_cell, ours_cached)),
974
- "theirs": _json_value(_cell_display_value(theirs_cell, theirs_cached)),
975
- "basePresent": base_cell is not None,
976
- "oursPresent": ours_cell is not None,
977
- "theirsPresent": theirs_cell is not None,
978
- "resolution": resolution,
979
- "changed": changed,
980
- "structural": structural,
981
- "selectable": selectable,
982
- "requiresChoice": bool(error_sides),
983
- "errorSides": error_sides,
984
- })
985
-
986
- # 只显示需要关注的行:结构变化行 + 含非 same(需决策/有变化信息)cell 的行
987
- visible_rows = [
988
- row for row in rows
989
- if row["state"] != "common" or row["id"] in row_attention
990
- ]
991
- visible_ids = {row["id"] for row in visible_rows}
992
- grid_cells = [cell for cell in all_cells if cell["rowId"] in visible_ids]
993
- cells = [cell for cell in grid_cells if cell["changed"]]
994
- decision_cell_count = sum(cell["changed"] and cell["selectable"] for cell in cells)
995
- preferred_ws = None
996
- for workbook, key in ((wb_ours, "ours"), (wb_theirs, "theirs"), (wb_base, "base")):
997
- if workbook is not None and names.get(key) in workbook.sheetnames:
998
- preferred_ws = workbook[names[key]]
999
- break
1000
- header_rows = []
1001
- for row_number in _header_rows(preferred_ws):
1002
- header_rows.append({
1003
- "row": row_number,
1004
- "cells": [
1005
- _json_value(preferred_ws.cell(row_number, column.get("oursCol") or column.get("theirsCol") or column.get("baseCol")).value)
1006
- for column in columns
1007
- ],
1008
- })
1009
- merged_cells = _merged_cells_diff(names, rows, columns, wb_base, wb_ours, wb_theirs)
1010
- merged_cells_conflict = merged_cells["status"] == "conflict"
1011
- structural_conflicts = (
1012
- sum(axis["state"] == "delete_modify" for axis in [*rows, *columns])
1013
- + int(merged_cells_conflict)
1014
- )
1015
- rebuild_required = (
1016
- any(axis["state"] != "common" for axis in [*rows, *columns])
1017
- or any(cell["changed"] for cell in all_cells)
1018
- or merged_cells["status"] != "same"
1019
- )
1020
- selectable_cells = [
1021
- cell for cell in cells
1022
- if cell["changed"] and cell["resolution"] == "conflict"
1023
- and next(row for row in rows if row["id"] == cell["rowId"])["state"] == "common"
1024
- and next(column for column in columns if column["id"] == cell["colId"])["state"] == "common"
1025
- ]
1026
- return {
1027
- "name": report_sheet["name"],
1028
- "names": names,
1029
- "renameStatus": report_sheet.get("renameStatus", "unchanged"),
1030
- "action": "merge",
1031
- "rows": visible_rows,
1032
- "allRows": rows,
1033
- "columns": columns,
1034
- "cells": cells,
1035
- "gridCells": grid_cells,
1036
- "allCells": all_cells,
1037
- "headerRows": header_rows,
1038
- "mergedCells": merged_cells,
1039
- "rebuildRequired": rebuild_required,
1040
- "maxCol": len(columns),
1041
- "changedCount": decision_cell_count,
1042
- "decisionCellCount": decision_cell_count,
1043
- "rawChangedCellCount": sum(cell["changed"] for cell in cells),
1044
- "conflictCount": len(selectable_cells),
1045
- "structuralConflictCount": structural_conflicts,
1046
- "needsAttention": decision_cell_count > 0 or structural_conflicts > 0
1047
- or report_sheet.get("renameStatus") == "rename_conflict",
1048
- }
1049
-
1050
-
1051
- def _require_error_review(sheet: dict[str, Any], snapshots: dict[str, Any]) -> None:
1052
- """Unknown values may never justify alignment or automatic resolution."""
1053
- names = sheet.get("names") or {side: sheet["name"] for side in ("base", "ours", "theirs")}
1054
- relevant = [{**error, "side": side} for side, meta in snapshots.items()
1055
- for error in meta.get("errors", []) if error["sheet"] == names.get(side)]
1056
- repairs = [{**repair, "side": side} for side, meta in snapshots.items()
1057
- for repair in meta.get("replacements", []) if repair["sheet"] == names.get(side)]
1058
- if repairs:
1059
- sheet.update(replacements=repairs, needsAttention=True, rebuildRequired=True)
1060
- lookup = {(repair["side"], repair["coordinate"]): repair for repair in repairs}
1061
- rows = {row["id"]: row for row in sheet.get("allRows", [])}
1062
- columns = {column["id"]: column for column in sheet.get("columns", [])}
1063
- corrected_rows, excluded = set(), set()
1064
- for cell in sheet.get("allCells", []):
1065
- row, column = rows[cell["rowId"]], columns[cell["colId"]]
1066
- pair = {}
1067
- for side in ("ours", "theirs"):
1068
- if row.get(f"{side}Row") is not None and column.get(f"{side}Col") is not None:
1069
- coordinate = f'{get_column_letter(column[f"{side}Col"])}{row[f"{side}Row"]}'
1070
- if (side, coordinate) in lookup:
1071
- pair[side] = lookup[(side, coordinate)]
1072
- if len(pair) != 2 or pair["ours"]["recordId"] != pair["theirs"]["recordId"] or pair["ours"]["field"] != pair["theirs"]["field"]:
1073
- continue
1074
- cell.update(replacement=pair, requiresChoice=False, selectable=False, resolution="replacement", changed=True)
1075
- corrected_rows.add(row["id"])
1076
- if row.get("baseRow") is not None and column.get("baseCol") is not None:
1077
- excluded.add(("base", f'{get_column_letter(column["baseCol"])}{row["baseRow"]}'))
1078
- relevant = [error for error in relevant if (error["side"], error["coordinate"]) not in excluded]
1079
- visible = {row["id"] for row in sheet.get("rows", [])} | corrected_rows
1080
- sheet["rows"] = [row for row in sheet.get("allRows", []) if row["id"] in visible]
1081
- sheet["gridCells"] = [cell for cell in sheet.get("allCells", []) if cell["rowId"] in visible]
1082
- sheet["cells"] = [cell for cell in sheet["gridCells"] if cell["changed"]]
1083
- sheet["changedCount"] = sheet["decisionCellCount"] = sum(cell["selectable"] for cell in sheet["cells"])
1084
- sheet["conflictCount"] = sum(cell["resolution"] == "conflict" for cell in sheet["cells"])
1085
- if not relevant:
1086
- return
1087
- sheet["calculationErrors"] = relevant
1088
- sheet["needsAttention"] = True
1089
- if sheet["action"] == "merge":
1090
- represented = sum(len(cell.get("errorSides", {})) for cell in sheet.get("allCells", []) if cell.get("requiresChoice"))
1091
- structural = any(axis["state"] != "common"
1092
- for axis in [*sheet.get("allRows", []), *sheet.get("columns", [])])
1093
- id_columns = [column for column in sheet.get("columns", []) if column["id"].casefold() == "id"]
1094
- identity_cells = [cell for cell in sheet.get("allCells", [])
1095
- if id_columns and cell["colId"] == id_columns[0]["id"]]
1096
- uncertain_rows = {cell["rowId"] for cell in sheet.get("allCells", []) if cell.get("requiresChoice")}
1097
- reliable = bool(id_columns) and all(
1098
- any(cell["rowId"] == row_id and not cell.get("requiresChoice")
1099
- and cell["base"] is not None and cell["base"] == cell["ours"] == cell["theirs"]
1100
- and all(sum(other[side] == cell[side] for other in identity_cells) == 1
1101
- for side in ("base", "ours", "theirs")) for cell in identity_cells)
1102
- for row_id in uncertain_rows
1103
- )
1104
- if not structural and represented == len(relevant) and reliable:
1105
- by_coordinate = {(error["side"], error["coordinate"]): error for error in relevant}
1106
- rows = {row["id"]: row for row in sheet["allRows"]}
1107
- columns = {column["id"]: column for column in sheet["columns"]}
1108
- for cell in sheet["allCells"]:
1109
- if cell.get("requiresChoice"):
1110
- cell["calculationErrors"] = {}
1111
- for side in cell["errorSides"]:
1112
- coordinate = f'{get_column_letter(columns[cell["colId"]][f"{side}Col"])}{rows[cell["rowId"]][f"{side}Row"]}'
1113
- cell["calculationErrors"][side] = by_coordinate[(side, coordinate)]
1114
- return
1115
- # Errors in headers, unmatched/deleted rows, or changing axes undermine
1116
- # structural evidence. Require a whole-sheet choice instead of guessing
1117
- # row/column correspondence or interpreting an unknown as "unchanged".
1118
- sheet.update(action="conflict_calculation_errors", requiresChoice=True,
1119
- cells=[], gridCells=[], allCells=[], rows=[], allRows=[], columns=[],
1120
- headerRows=[], changedCount=0, conflictCount=0,
1121
- structuralConflictCount=1, renameStatus="unchanged", mergedCells=None)
1122
-
1123
-
1124
- def diff_workbooks(
1125
- base_path: Path | str | None,
1126
- ours_path: Path | str,
1127
- theirs_path: Path | str,
1128
- *,
1129
- analysis_dir: Path | str | None = None,
1130
- skip_hidden_sheets: bool = True,
1131
- ) -> dict[str, Any]:
1132
- structural_dir = Path(analysis_dir) if analysis_dir else Path(tempfile.mkdtemp(prefix="xlsx-merge-analysis-"))
1133
- snapshot_paths, value_snapshots = _snapshot_workbooks(
1134
- base_path, ours_path, theirs_path, structural_dir,
1135
- )
1136
- # These workbooks are complete, calculated snapshots with typed errors
1137
- # represented as unknowns requiring review. Keeping the
1138
- # three sides separate is important for cross-sheet formulas: each side is
1139
- # calculated against its own original workbook before alignment/merge.
1140
- wb_base = load_workbook(snapshot_paths["base"], data_only=False, keep_links=True) if snapshot_paths["base"] else None
1141
- wb_ours = load_workbook(snapshot_paths["ours"], data_only=False, keep_links=True)
1142
- wb_theirs = load_workbook(snapshot_paths["theirs"], data_only=False, keep_links=True)
1143
- wb_base_v = wb_ours_v = wb_theirs_v = None
1144
- try:
1145
- if any(meta.get("errors") or meta.get("replacements") for meta in value_snapshots.values()):
1146
- skip_hidden_sheets = False
1147
- if base_path is not None:
1148
- structural = analyze_structural_workbooks(
1149
- snapshot_paths["base"], snapshot_paths["ours"], snapshot_paths["theirs"], structural_dir,
1150
- write_sidecars=False, skip_hidden_sheets=skip_hidden_sheets,
1151
- progress=lambda **p: checkpoint(phase='对齐 Sheet / 行 / 列', **p),
1152
- )
1153
- sheets = []
1154
- for index, report_sheet in enumerate(structural["sheets"]):
1155
- checkpoint(phase='生成审阅数据', sheet=report_sheet['name'], sheetDone=index, sheetTotal=len(structural['sheets']))
1156
- if report_sheet["action"] == "merge":
1157
- sheets.append(_structural_sheet_diff(
1158
- report_sheet, wb_base, wb_ours, wb_theirs,
1159
- wb_base_v, wb_ours_v, wb_theirs_v,
1160
- ))
1161
- continue
1162
- names = report_sheet.get("names") or {}
1163
- if not names.get("base"):
1164
- if names.get("ours") and names.get("theirs"):
1165
- action = "auto_add_theirs"
1166
- else:
1167
- action = "auto_add_ours" if names.get("ours") else "auto_add_theirs"
1168
- elif report_sheet.get("status") == "conflict":
1169
- conflict_kind = (report_sheet.get("sheetConflict") or {}).get("kind", "")
1170
- if conflict_kind.startswith("delete_modify_"):
1171
- action = f'conflict_delete_{conflict_kind.rsplit("_", 1)[-1]}'
1172
- else:
1173
- action = "conflict_sheet_structure"
1174
- else:
1175
- action = "auto_delete"
1176
- sheets.append({
1177
- "name": report_sheet["name"],
1178
- "names": names,
1179
- "renameStatus": report_sheet.get("renameStatus", "unchanged"),
1180
- "action": action,
1181
- "sheetConflict": report_sheet.get("sheetConflict"),
1182
- "cells": [],
1183
- "rows": [],
1184
- "allRows": [],
1185
- "columns": [],
1186
- "headerRows": [],
1187
- "maxCol": 0,
1188
- "changedCount": 0,
1189
- "conflictCount": 0,
1190
- "structuralConflictCount": int(action.startswith("conflict_")),
1191
- "needsAttention": action.startswith("conflict_"),
1192
- })
1193
- for sheet in sheets:
1194
- _require_error_review(sheet, value_snapshots)
1195
- return {
1196
- "engineVersion": structural["version"],
1197
- "valueSnapshots": value_snapshots,
1198
- "sheets": sheets,
1199
- "summary": {
1200
- "sheetCount": len(sheets),
1201
- "changedCellCount": sum(sheet["changedCount"] for sheet in sheets),
1202
- "cellConflictCount": sum(sheet["conflictCount"] for sheet in sheets),
1203
- "structuralConflictCount": sum(sheet.get("structuralConflictCount", 0) for sheet in sheets),
1204
- "sheetConflictCount": sum(sheet["action"].startswith("conflict_") for sheet in sheets),
1205
- },
1206
- }
1207
-
1208
- sheets: list[dict[str, Any]] = []
1209
- ordered_names = _ordered_sheet_names(wb_base, wb_ours, wb_theirs)
1210
- for index, name in enumerate(ordered_names):
1211
- checkpoint(phase='生成审阅数据', sheet=name, sheetDone=index, sheetTotal=len(ordered_names))
1212
- base_exists = wb_base is not None and name in wb_base.sheetnames
1213
- ours_exists = name in wb_ours.sheetnames
1214
- theirs_exists = name in wb_theirs.sheetnames
1215
- ws_base = wb_base[name] if base_exists else None
1216
- ws_ours = wb_ours[name] if ours_exists else None
1217
- ws_theirs = wb_theirs[name] if theirs_exists else None
1218
- ws_base_v = wb_base_v[name] if base_exists and wb_base_v is not None else None
1219
- ws_ours_v = wb_ours_v[name] if ours_exists and wb_ours_v is not None else None
1220
- ws_theirs_v = wb_theirs_v[name] if theirs_exists and wb_theirs_v is not None else None
1221
-
1222
- if ours_exists and theirs_exists:
1223
- sheet = _modified_sheet_diff(name, ws_base, ws_ours, ws_theirs,
1224
- ws_base_v, ws_ours_v, ws_theirs_v)
1225
- if sheet["changedCount"]:
1226
- sheets.append(sheet)
1227
- continue
1228
- if not base_exists:
1229
- source = "ours" if ours_exists else "theirs"
1230
- sheets.append({
1231
- "name": name,
1232
- "action": f"auto_add_{source}",
1233
- "cells": [],
1234
- "contextRows": {},
1235
- "maxCol": 0,
1236
- "changedCount": 0,
1237
- "conflictCount": 0,
1238
- })
1239
- continue
1240
- if not ours_exists and not theirs_exists:
1241
- sheets.append({
1242
- "name": name,
1243
- "action": "auto_delete",
1244
- "cells": [],
1245
- "contextRows": {},
1246
- "maxCol": 0,
1247
- "changedCount": 0,
1248
- "conflictCount": 0,
1249
- })
1250
- continue
1251
-
1252
- existing_ws = ws_ours or ws_theirs
1253
- missing_side = "theirs" if ours_exists else "ours"
1254
- if _sheet_equal(ws_base, existing_ws):
1255
- action = "auto_delete"
1256
- conflict_count = 0
1257
- else:
1258
- action = f"conflict_delete_{missing_side}"
1259
- conflict_count = 1
1260
- sheets.append({
1261
- "name": name,
1262
- "action": action,
1263
- "cells": [],
1264
- "contextRows": {},
1265
- "maxCol": 0,
1266
- "changedCount": 0,
1267
- "conflictCount": conflict_count,
1268
- })
1269
-
1270
- for sheet in sheets:
1271
- _require_error_review(sheet, value_snapshots)
1272
- return {
1273
- "valueSnapshots": value_snapshots,
1274
- "sheets": sheets,
1275
- "summary": {
1276
- "sheetCount": len(sheets),
1277
- "changedCellCount": sum(sheet["changedCount"] for sheet in sheets),
1278
- "cellConflictCount": sum(
1279
- sum(cell["resolution"] == "conflict" for cell in sheet["cells"])
1280
- for sheet in sheets
1281
- ),
1282
- "sheetConflictCount": sum(sheet["action"].startswith("conflict_") for sheet in sheets),
1283
- },
1284
- }
1285
- finally:
1286
- if wb_base is not None:
1287
- wb_base.close()
1288
- wb_ours.close()
1289
- wb_theirs.close()
1290
- if wb_base_v is not None:
1291
- wb_base_v.close()
1292
- if wb_ours_v is not None:
1293
- wb_ours_v.close()
1294
- if wb_theirs_v is not None:
1295
- wb_theirs_v.close()
1296
-
1297
-
1298
- def _author_and_date(repo: Path, relative_path: str, ref: str) -> tuple[str, str]:
1299
- verify = _run_git(repo, ["rev-parse", "--verify", "--quiet", ref])
1300
- if verify.returncode != 0:
1301
- return "", ""
1302
- result = _run_git(repo, ["log", "-1", "--format=%an|%cI", ref, "--", relative_path])
1303
- if result.returncode != 0 or not result.stdout.strip():
1304
- return "", ""
1305
- parts = result.stdout.strip().split("|", 1)
1306
- if len(parts) != 2:
1307
- return parts[0], ""
1308
- author, iso_date = parts
1309
- # ISO 8601 -> "2000-1-1 8:24"
1310
- try:
1311
- from datetime import datetime
1312
- dt = datetime.fromisoformat(iso_date)
1313
- date_str = f"{dt.year}-{dt.month}-{dt.day} {dt.hour}:{dt.minute:02d}"
1314
- except (ValueError, TypeError):
1315
- date_str = ""
1316
- return author, date_str
1317
-
1318
-
1319
- def _author(repo: Path, relative_path: str, ref: str) -> str:
1320
- author, _ = _author_and_date(repo, relative_path, ref)
1321
- return author
1322
-
1323
-
1324
- def _theirs_author(repo: Path, relative_path: str) -> str:
1325
- for ref in ("MERGE_HEAD", "CHERRY_PICK_HEAD", "REBASE_HEAD"):
1326
- author = _author(repo, relative_path, ref)
1327
- if author:
1328
- return author
1329
- return ""
1330
-
1331
-
1332
- def _ours_date(repo: Path, relative_path: str) -> str:
1333
- _, date_str = _author_and_date(repo, relative_path, "HEAD")
1334
- return date_str
1335
-
1336
-
1337
- def _theirs_date(repo: Path, relative_path: str) -> str:
1338
- for ref in ("MERGE_HEAD", "CHERRY_PICK_HEAD", "REBASE_HEAD"):
1339
- _, date_str = _author_and_date(repo, relative_path, ref)
1340
- if date_str:
1341
- return date_str
1342
- return ""
1343
-
1344
-
1345
- def prepare_conflicts(
1346
- repo: Path | str,
1347
- *,
1348
- relative_path: str | None = None,
1349
- runtime_dir: Path | str | None = None,
1350
- ) -> Path:
1351
- repo_root = find_repo_root(repo)
1352
- conflicts = detect_conflicts(repo_root)
1353
- if relative_path:
1354
- normalized = relative_path.replace("\\", "/")
1355
- conflicts = [item for item in conflicts if item["path"] == normalized]
1356
- if not conflicts:
1357
- raise ConflictError("No unresolved .xlsx/.xlsm conflicts were found.")
1358
-
1359
- target_dir = _safe_runtime_dir(repo_root, runtime_dir)
1360
- auto_filters = load_auto_theirs_filters(repo_root)
1361
- prepared_files = []
1362
- auto_entries: list[dict[str, Any]] = []
1363
- for index, item in enumerate(conflicts):
1364
- checkpoint(file=item['path'], fileDone=index, fileTotal=len(conflicts), phase='提取三方版本', sheet='', sheetDone=0, sheetTotal=0, side='')
1365
- path = item["path"]
1366
- if auto_theirs_path(path, auto_filters):
1367
- if 3 not in item["stages"]:
1368
- raise ConflictError(
1369
- f"{path} matches the auto-theirs rule, but Git stage 3 is missing."
1370
- )
1371
- auto_entries.append({
1372
- "path": path,
1373
- "theirsAuthor": _theirs_author(repo_root, path),
1374
- "theirsDate": _theirs_date(repo_root, path),
1375
- "theirsSha256": hashlib.sha256(_git_blob(repo_root, 3, path)).hexdigest(),
1376
- "outputSha256": _sha256_path(repo_root / Path(path)) if (repo_root / Path(path)).exists() else None,
1377
- })
1378
- continue
1379
- ours_blob = _git_blob(repo_root, 2, path)
1380
- theirs_blob = _git_blob(repo_root, 3, path)
1381
- if ours_blob is None or theirs_blob is None:
1382
- raise ConflictError(
1383
- f"{path} is a delete/modify conflict. This resolver currently requires both workbook versions."
1384
- )
1385
- base_blob = _git_blob(repo_root, 1, path)
1386
- extension = Path(path).suffix.lower()
1387
- macro = None
1388
- if extension == ".xlsm":
1389
- macro = _macro_payload_info(base_blob, ours_blob, theirs_blob)
1390
- work_dir = target_dir / _slug(path)
1391
- work_dir.mkdir(parents=True, exist_ok=True)
1392
- ours_path = work_dir / f"ours{extension}"
1393
- theirs_path = work_dir / f"theirs{extension}"
1394
- base_path = work_dir / f"base{extension}"
1395
- ours_path.write_bytes(ours_blob)
1396
- theirs_path.write_bytes(theirs_blob)
1397
- if base_blob is not None:
1398
- base_path.write_bytes(base_blob)
1399
- elif base_path.exists():
1400
- base_path.unlink()
1401
- for extracted_path in (base_path if base_blob is not None else None, ours_path, theirs_path):
1402
- if extracted_path is not None:
1403
- _repair_invalid_dimension_styles(extracted_path)
1404
- workbook_diff = diff_workbooks(
1405
- base_path if base_blob is not None else None,
1406
- ours_path,
1407
- theirs_path,
1408
- analysis_dir=work_dir / "analysis",
1409
- )
1410
- value_snapshots = workbook_diff.get("valueSnapshots") or {}
1411
- index_hashes = {
1412
- "base": hashlib.sha256(base_blob).hexdigest() if base_blob is not None else None,
1413
- "ours": hashlib.sha256(ours_blob).hexdigest(),
1414
- "theirs": hashlib.sha256(theirs_blob).hexdigest(),
1415
- }
1416
- for side, snapshot_meta in value_snapshots.items():
1417
- snapshot_meta["gitIndexSha256"] = index_hashes.get(side)
1418
- prepared_files.append({
1419
- "id": path,
1420
- "path": path,
1421
- "base": str(base_path) if base_blob is not None else None,
1422
- "ours": str(ours_path),
1423
- "theirs": str(theirs_path),
1424
- "output": str((repo_root / Path(path)).resolve()),
1425
- "oursAuthor": _author(repo_root, path, "HEAD"),
1426
- "theirsAuthor": _theirs_author(repo_root, path),
1427
- "oursDate": _ours_date(repo_root, path),
1428
- "theirsDate": _theirs_date(repo_root, path),
1429
- "macro": macro,
1430
- # Keep both source and value digests in the manifest. apply must
1431
- # reuse exactly what the user saw, never silently recalculate.
1432
- "valueSnapshots": value_snapshots,
1433
- "outputSha256": _sha256_path(repo_root / Path(path)) if (repo_root / Path(path)).exists() else None,
1434
- "diff": workbook_diff,
1435
- })
1436
-
1437
- manifest = {
1438
- "version": 4,
1439
- "repoRoot": str(repo_root),
1440
- "files": prepared_files,
1441
- "autoTheirs": auto_entries,
1442
- "summary": {
1443
- "fileCount": len(prepared_files),
1444
- "cellConflictCount": sum(f["diff"]["summary"]["cellConflictCount"] for f in prepared_files),
1445
- "sheetConflictCount": sum(f["diff"]["summary"]["sheetConflictCount"] for f in prepared_files),
1446
- "structuralConflictCount": sum(f["diff"]["summary"].get("structuralConflictCount", 0) for f in prepared_files),
1447
- "autoTheirsCount": len(auto_entries),
1448
- },
1449
- }
1450
- checkpoint(phase='完成解析', fileDone=len(conflicts), sheet='', sheetDone=0, sheetTotal=0)
1451
- manifest_path = target_dir / "manifest.json"
1452
- manifest_path.write_text(json.dumps(manifest, ensure_ascii=False, indent=2), encoding="utf-8")
1453
- return manifest_path
1454
-
1455
-
1456
- def load_manifest(path: Path | str) -> dict[str, Any]:
1457
- manifest_path = Path(path).resolve()
1458
- data = json.loads(manifest_path.read_text(encoding="utf-8"))
1459
- if data.get("version") != 4 or not isinstance(data.get("files"), list):
1460
- if data.get("version") == 3:
1461
- raise ConflictError(
1462
- f"Manifest {manifest_path} was created by the pre-materialization resolver; "
1463
- "re-run prepare so formula values can be calculated safely."
1464
- )
1465
- raise ConflictError(f"Unsupported manifest: {manifest_path}")
1466
- for entry in data["files"]:
1467
- if not isinstance(entry.get("valueSnapshots"), dict):
1468
- raise ConflictError(f"Manifest {manifest_path} has no immutable formula value snapshots.")
1469
- return data
1470
-
1471
-
1472
- def _copy_cell(source, target) -> None:
1473
- if getattr(source, "data_type", None) == "s" and source.value == "":
1474
- # Formula snapshots may legitimately contain an empty-string result.
1475
- # Copy the typed rich-text payload so openpyxl does not serialize it as
1476
- # an absent cell (None) on the next save.
1477
- target.data_type = "s"
1478
- target._value = copy(getattr(source, "_value", ""))
1479
- else:
1480
- target.value = source.value
1481
- # openpyxl infers a string beginning with '=' as a formula. Snapshot
1482
- # cells are literals, so restore the source type after assigning value;
1483
- # otherwise a calculated string could become executable formula syntax.
1484
- if getattr(source, "data_type", None) not in (None, "f"):
1485
- target.data_type = source.data_type
1486
- if source.has_style:
1487
- if source.parent is not None and source.parent.parent is target.parent.parent:
1488
- # 同 workbook:样式表索引通用,浅拷贝 StyleArray 避免对象复制(大表 40 万+ 格)
1489
- target._style = copy(source._style)
1490
- else:
1491
- target.font = copy(source.font)
1492
- target.fill = copy(source.fill)
1493
- target.border = copy(source.border)
1494
- target.alignment = copy(source.alignment)
1495
- target.number_format = source.number_format
1496
- target.protection = copy(source.protection)
1497
- target.hyperlink = source.hyperlink
1498
- target.comment = source.comment
1499
-
1500
-
1501
- def _copy_sheet(source_ws, target_wb, *, index: int | None = None):
1502
- target_ws = target_wb.create_sheet(source_ws.title, index=index)
1503
- for row in source_ws.iter_rows():
1504
- for source_cell in row:
1505
- if isinstance(source_cell, MergedCell):
1506
- continue
1507
- _copy_cell(source_cell, target_ws.cell(source_cell.row, source_cell.column))
1508
- for key, dimension in source_ws.column_dimensions.items():
1509
- target_ws.column_dimensions[key] = copy(dimension)
1510
- target_ws.column_dimensions[key].worksheet = target_ws
1511
- for key, dimension in source_ws.row_dimensions.items():
1512
- target_ws.row_dimensions[key] = copy(dimension)
1513
- target_ws.row_dimensions[key].worksheet = target_ws
1514
- for merged_range in source_ws.merged_cells.ranges:
1515
- target_ws.merge_cells(str(merged_range))
1516
- target_ws.views = copy(source_ws.views)
1517
- target_ws.sheet_format = copy(source_ws.sheet_format)
1518
- target_ws.sheet_properties = copy(source_ws.sheet_properties)
1519
- target_ws.page_margins = copy(source_ws.page_margins)
1520
- target_ws.page_setup = copy(source_ws.page_setup)
1521
- target_ws.print_options = copy(source_ws.print_options)
1522
- target_ws.auto_filter.ref = source_ws.auto_filter.ref
1523
- target_ws.sheet_state = source_ws.sheet_state
1524
- return target_ws
1525
-
1526
-
1527
- def _replace_sheet(target_wb, source_ws, order: list[str]) -> None:
1528
- if source_ws.title in target_wb.sheetnames:
1529
- index = target_wb.sheetnames.index(source_ws.title)
1530
- target_wb.remove(target_wb[source_ws.title])
1531
- else:
1532
- desired = order.index(source_ws.title) if source_ws.title in order else len(target_wb.sheetnames)
1533
- index = min(desired, len(target_wb.sheetnames))
1534
- _copy_sheet(source_ws, target_wb, index=index)
1535
-
1536
-
1537
- def _file_decisions(decisions: dict[str, Any], file_id: str) -> dict[str, Any]:
1538
- return ((decisions.get("files") or {}).get(file_id) or {})
1539
-
1540
-
1541
- def _cell_choice(cell_choices: dict[str, Any], cell: dict[str, Any]) -> Any:
1542
- return cell_choices.get(cell.get("id"), cell_choices.get(cell.get("coordinate")))
1543
-
1544
-
1545
- def _validate_decisions(manifest: dict[str, Any], decisions: dict[str, Any]) -> None:
1546
- missing: list[str] = []
1547
- for file_entry in manifest["files"]:
1548
- file_choice = _file_decisions(decisions, file_entry["id"])
1549
- macro = file_entry.get("macro") or {}
1550
- macro_choice = file_choice.get("macro", macro.get("default"))
1551
- if macro.get("status") == "conflict" and macro_choice not in ("ours", "theirs"):
1552
- missing.append(f"{file_entry['path']} / <VBA/ActiveX>")
1553
- if macro_choice == "theirs" and not macro.get("canChooseTheirs", True):
1554
- raise ConflictError(
1555
- f"{file_entry['path']} has incompatible LOCAL and REMOTE VBA/ActiveX package structures; "
1556
- "only the LOCAL macro payload can be preserved safely."
1557
- )
1558
- sheet_choices = file_choice.get("sheets") or {}
1559
- for sheet in file_entry["diff"]["sheets"]:
1560
- choice = sheet_choices.get(sheet["name"]) or {}
1561
- if choice.get('sheet') in ('ours', 'theirs'):
1562
- if sheet['action'] != 'merge' and not sheet['action'].startswith('conflict_'):
1563
- raise ConflictError('自动处理 Sheet 不支持额外整表覆盖。')
1564
- _selected_repairs(sheet, choice)
1565
- continue
1566
- if sheet["action"].startswith("conflict_") and choice.get("sheet") not in ("ours", "theirs"):
1567
- missing.append(f"{file_entry['path']} / {sheet['name']} / <sheet>")
1568
- if sheet["action"].startswith("conflict_"):
1569
- selected_errors = [error for error in sheet.get("calculationErrors", [])
1570
- if error["side"] == choice.get("sheet")]
1571
- if selected_errors:
1572
- error = selected_errors[0]
1573
- raise ConflictError(f"Selected {error['side']} source has an Excel error at {file_entry['path']} / {error['sheet']}!{error['coordinate']}: {error['error']}")
1574
- if sheet.get("renameStatus") == "rename_conflict" and choice.get("rename") not in ("ours", "theirs"):
1575
- missing.append(f"{file_entry['path']} / {sheet['name']} / <rename>")
1576
- if (sheet.get("mergedCells") or {}).get("status") == "conflict" and choice.get("mergedCells") not in ("ours", "theirs"):
1577
- missing.append(f"{file_entry['path']} / {sheet['name']} / <merged-cells>")
1578
- row_choices = choice.get("rows") or {}
1579
- for row in sheet.get("allRows") or sheet.get("rows") or []:
1580
- if row.get("state") == "delete_modify" and row_choices.get(row["id"]) not in ("keep", "delete"):
1581
- missing.append(f"{file_entry['path']} / {sheet['name']} / {row['id']}")
1582
- column_choices = choice.get("columns") or {}
1583
- for column in sheet.get("columns") or []:
1584
- if column.get("state") == "delete_modify" and column_choices.get(column["id"]) not in ("keep", "delete"):
1585
- missing.append(f"{file_entry['path']} / {sheet['name']} / {column['id']}")
1586
- cell_choices = choice.get("cells") or {}
1587
- for cell in sheet["cells"]:
1588
- side = _cell_choice(cell_choices, cell)
1589
- if side in cell.get("errorSides", {}):
1590
- raise ConflictError(f"Selected {side} source has an Excel error at {file_entry['path']} / {sheet['name']} / {cell['coordinate']}: {cell['errorSides'][side]}")
1591
- if cell["resolution"] == "conflict" and side not in ("ours", "theirs"):
1592
- missing.append(f"{file_entry['path']} / {sheet['name']} / {cell['coordinate']}")
1593
- if missing:
1594
- preview = "\n".join(f"- {item}" for item in missing[:20])
1595
- suffix = f"\n... and {len(missing) - 20} more" if len(missing) > 20 else ""
1596
- raise ConflictError(f"Unresolved choices remain:\n{preview}{suffix}")
1597
-
1598
-
1599
- def _copy_sheet_properties(source_ws, target_ws) -> None:
1600
- # freeze_panes only exposes topLeftCell. Reassigning it turns a scrolled
1601
- # viewport such as topLeftCell=D857/ySplit=4 into a 856-row freeze.
1602
- target_ws.views = copy(source_ws.views)
1603
- target_ws.sheet_format = copy(source_ws.sheet_format)
1604
- target_ws.sheet_properties = copy(source_ws.sheet_properties)
1605
- target_ws.page_margins = copy(source_ws.page_margins)
1606
- target_ws.page_setup = copy(source_ws.page_setup)
1607
- target_ws.print_options = copy(source_ws.print_options)
1608
- target_ws.auto_filter.ref = source_ws.auto_filter.ref
1609
- target_ws.sheet_state = source_ws.sheet_state
1610
-
1611
-
1612
- def _restore_merged_cells(target_ws, sheet, selection, active_rows, active_columns, header_count) -> None:
1613
- model = sheet.get("mergedCells") or {}
1614
- if model.get("status") == "conflict":
1615
- regions = model.get(selection.get("mergedCells")) or []
1616
- else:
1617
- regions = model.get("resolved") or []
1618
- row_positions = {f"header:{row}": row for row in range(1, header_count + 1)}
1619
- row_positions.update({row["id"]: header_count + index for index, row in enumerate(active_rows, 1)})
1620
- column_positions = {column["id"]: index for index, column in enumerate(active_columns, 1)}
1621
- occupied: set[tuple[int, int]] = set()
1622
- for region in regions:
1623
- output_rows = sorted({row_positions[row] for row in region["rows"] if row in row_positions})
1624
- output_columns = sorted({column_positions[column] for column in region["columns"] if column in column_positions})
1625
- if not output_rows or not output_columns or len(output_rows) * len(output_columns) < 2:
1626
- continue
1627
- if output_rows != list(range(output_rows[0], output_rows[-1] + 1)):
1628
- raise ConflictError(f"Merged rows are no longer contiguous in {sheet['name']}")
1629
- if output_columns != list(range(output_columns[0], output_columns[-1] + 1)):
1630
- raise ConflictError(f"Merged columns are no longer contiguous in {sheet['name']}")
1631
- cells = {(row, column) for row in output_rows for column in output_columns}
1632
- if occupied & cells:
1633
- raise ConflictError(f"Merged regions overlap after alignment in {sheet['name']}")
1634
- occupied.update(cells)
1635
- target_ws.merge_cells(
1636
- start_row=output_rows[0], end_row=output_rows[-1],
1637
- start_column=output_columns[0], end_column=output_columns[-1],
1638
- )
1639
-
1640
-
1641
- def _axis_kept(axis: dict[str, Any], choices: dict[str, Any]) -> bool:
1642
- if axis.get("state") == "deleted":
1643
- return False
1644
- if axis.get("state") == "delete_modify":
1645
- return choices.get(axis["id"], axis.get("default", "keep")) == "keep"
1646
- return True
1647
-
1648
-
1649
- def _source_cell(workbooks, names, row, column, side: str):
1650
- workbook = workbooks.get(side)
1651
- sheet_name = names.get(side)
1652
- row_number = row.get(f"{side}Row")
1653
- column_number = column.get(f"{side}Col")
1654
- if workbook is None or sheet_name is None or row_number is None or column_number is None:
1655
- return None
1656
- return workbook[sheet_name].cell(row_number, column_number)
1657
-
1658
-
1659
- def _selected_source_cell(workbooks, names, row, column, cell, choice: str | None):
1660
- preferred = []
1661
- if choice in ("ours", "theirs"):
1662
- preferred.append(choice)
1663
- elif cell.get("resolution") == "theirs":
1664
- preferred.append("theirs")
1665
- elif cell.get("resolution") == "ours":
1666
- preferred.append("ours")
1667
- elif cell.get("resolution") == "same":
1668
- preferred.extend(("ours", "theirs"))
1669
- else:
1670
- preferred.append("theirs")
1671
- preferred.extend(side for side in ("ours", "theirs", "base") if side not in preferred)
1672
- for side in preferred:
1673
- source = _source_cell(workbooks, names, row, column, side)
1674
- if source is not None:
1675
- return source
1676
- return None
1677
-
1678
-
1679
- def _selected_sheet_name(sheet: dict[str, Any], selection: dict[str, Any]) -> str:
1680
- names = sheet.get("names") or {}
1681
- if sheet.get("renameStatus") == "rename_conflict":
1682
- return names[selection["rename"]]
1683
- return names.get("ours") or names.get("theirs") or names.get("base") or sheet["name"]
1684
-
1685
-
1686
- _FORMULA_CACHE_NS = '{http://schemas.openxmlformats.org/spreadsheetml/2006/main}'
1687
- _FORMULA_CACHE_RNS = '{http://schemas.openxmlformats.org/officeDocument/2006/relationships}'
1688
-
1689
-
1690
-
1691
-
1692
- def _restore_untouched_formula_caches(source: Path, target: Path, sheet_names: set[str]) -> None:
1693
- """Copy raw cache types/values, avoiding date-epoch and empty/error coercion."""
1694
- import xml.etree.ElementTree as ET
1695
-
1696
- def sheet_files(parts):
1697
- relationships = ET.fromstring(parts['xl/_rels/workbook.xml.rels'])
1698
- targets = {rel.get('Id'): rel.get('Target') for rel in relationships}
1699
- result = {}
1700
- for sheet in ET.fromstring(parts['xl/workbook.xml']).iter(f'{_FORMULA_CACHE_NS}sheet'):
1701
- value = targets.get(sheet.get(f'{_FORMULA_CACHE_RNS}id'), '')
1702
- if value:
1703
- result[sheet.get('name')] = value.lstrip('/') if value.startswith('/') else 'xl/' + value
1704
- return result
1705
-
1706
- with zipfile.ZipFile(source) as archive:
1707
- original = {item.filename: archive.read(item.filename) for item in archive.infolist()}
1708
- with zipfile.ZipFile(target) as archive:
1709
- infos = archive.infolist()
1710
- parts = {item.filename: archive.read(item.filename) for item in infos}
1711
- original_files, output_files = sheet_files(original), sheet_files(parts)
1712
- for name in sheet_names:
1713
- if name not in original_files or name not in output_files:
1714
- continue
1715
- original_tree = ET.fromstring(original[original_files[name]])
1716
- caches = {cell.get('r'): cell for cell in original_tree.iter(f'{_FORMULA_CACHE_NS}c')
1717
- if cell.find(f'{_FORMULA_CACHE_NS}f') is not None}
1718
- if not caches:
1719
- continue
1720
- output_tree = ET.fromstring(parts[output_files[name]])
1721
- for cell in output_tree.iter(f'{_FORMULA_CACHE_NS}c'):
1722
- old = caches.get(cell.get('r'))
1723
- if old is None or cell.find(f'{_FORMULA_CACHE_NS}f') is None:
1724
- continue
1725
- cell.attrib.pop('t', None)
1726
- if 't' in old.attrib:
1727
- cell.set('t', old.get('t'))
1728
- for value in list(cell.findall(f'{_FORMULA_CACHE_NS}v')):
1729
- cell.remove(value)
1730
- old_value = old.find(f'{_FORMULA_CACHE_NS}v')
1731
- if old_value is not None:
1732
- cell.append(copy(old_value))
1733
- parts[output_files[name]] = ET.tostring(output_tree, encoding='utf-8')
1734
- with zipfile.ZipFile(target, 'w', zipfile.ZIP_DEFLATED) as archive:
1735
- for info in infos:
1736
- archive.writestr(info, parts[info.filename])
1737
-
1738
-
1739
- def _preserve_empty_inline_strings(path: Path) -> None:
1740
- """Make zero-length literal strings round-trip as ``''`` rather than None."""
1741
- import xml.etree.ElementTree as ET
1742
- namespace = "http://schemas.openxmlformats.org/spreadsheetml/2006/main"
1743
- ET.register_namespace("", namespace)
1744
- with zipfile.ZipFile(path) as source:
1745
- infos = source.infolist()
1746
- parts = {info.filename: source.read(info.filename) for info in infos}
1747
- changed = False
1748
- for name, payload in list(parts.items()):
1749
- if not name.startswith("xl/worksheets/") or not name.endswith(".xml"):
1750
- continue
1751
- tree = ET.fromstring(payload)
1752
- modified = False
1753
- for cell in tree.iter(f"{{{namespace}}}c"):
1754
- if cell.get("t") != "inlineStr" or cell.find(f"{{{namespace}}}is") is not None:
1755
- continue
1756
- inline = ET.SubElement(cell, f"{{{namespace}}}is")
1757
- ET.SubElement(inline, f"{{{namespace}}}t").text = ""
1758
- modified = True
1759
- if modified:
1760
- parts[name] = ET.tostring(tree, encoding="UTF-8")
1761
- changed = True
1762
- if not changed:
1763
- return
1764
- replacement = path.with_name(f".{path.name}.empty-strings")
1765
- try:
1766
- with zipfile.ZipFile(replacement, "w", zipfile.ZIP_DEFLATED) as output:
1767
- for info in infos:
1768
- output.writestr(info, parts[info.filename])
1769
- os.replace(replacement, path)
1770
- finally:
1771
- replacement.unlink(missing_ok=True)
1772
-
1773
-
1774
-
1775
-
1776
- def _rebuild_structural_sheet(wb_out, wb_base, wb_ours, wb_theirs, sheet, selection,
1777
- wb_base_v=None, wb_ours_v=None, wb_theirs_v=None) -> dict[str, Any]:
1778
- names = sheet.get("names") or {"base": sheet["name"], "ours": sheet["name"], "theirs": sheet["name"]}
1779
- source_ws = None
1780
- for workbook, side in ((wb_ours, "ours"), (wb_theirs, "theirs"), (wb_base, "base")):
1781
- if workbook is not None and names.get(side) in workbook.sheetnames:
1782
- source_ws = workbook[names[side]]
1783
- break
1784
- if source_ws is None:
1785
- raise ConflictError(f"No source sheet is available for {sheet['name']}")
1786
-
1787
- existing_name = names.get("ours")
1788
- index = wb_out.sheetnames.index(existing_name) if existing_name in wb_out.sheetnames else len(wb_out.sheetnames)
1789
- temp_title = f"__merge_{len(wb_out.sheetnames)}__"
1790
- while temp_title in wb_out.sheetnames:
1791
- temp_title += "_"
1792
- target_ws = wb_out.create_sheet(temp_title, index=index)
1793
- _copy_sheet_properties(source_ws, target_ws)
1794
-
1795
- row_choices = selection.get("rows") or {}
1796
- column_choices = selection.get("columns") or {}
1797
- active_rows = [row for row in sheet.get("allRows") or [] if _axis_kept(row, row_choices)]
1798
- active_columns = [column for column in sheet.get("columns") or [] if _axis_kept(column, column_choices)]
1799
- workbooks = {"base": wb_base, "ours": wb_ours, "theirs": wb_theirs}
1800
- workbooks_v = {"base": wb_base_v, "ours": wb_ours_v, "theirs": wb_theirs_v}
1801
- cell_map = {cell["id"]: cell for cell in sheet.get("allCells") or sheet.get("cells") or []}
1802
- cell_choices = selection.get("cells") or {}
1803
- formula_cache: dict[str, Any] = {}
1804
-
1805
- header_count = max(
1806
- [max(_header_rows(workbook[names[side]]) or [0])
1807
- for workbook, side in ((wb_base, "base"), (wb_ours, "ours"), (wb_theirs, "theirs"))
1808
- if workbook is not None and names.get(side) in workbook.sheetnames]
1809
- or [0]
1810
- )
1811
- for output_col, column in enumerate(active_columns, 1):
1812
- dimension_source = None
1813
- for workbook, side in ((wb_ours, "ours"), (wb_theirs, "theirs"), (wb_base, "base")):
1814
- source_col = column.get(f"{side}Col")
1815
- if workbook is not None and names.get(side) in workbook.sheetnames and source_col is not None:
1816
- dimension_source = workbook[names[side]].column_dimensions[get_column_letter(source_col)]
1817
- break
1818
- if dimension_source is not None:
1819
- target_ws.column_dimensions[get_column_letter(output_col)] = copy(dimension_source)
1820
- target_ws.column_dimensions[get_column_letter(output_col)].worksheet = target_ws
1821
- # 表头行高:ours 优先,回退 theirs/base
1822
- for header_row in range(1, header_count + 1):
1823
- for workbook, side in ((wb_ours, "ours"), (wb_theirs, "theirs"), (wb_base, "base")):
1824
- if workbook is not None and names.get(side) in workbook.sheetnames:
1825
- dim = workbook[names[side]].row_dimensions[header_row]
1826
- if dim.height is not None:
1827
- target_ws.row_dimensions[header_row] = copy(dim)
1828
- target_ws.row_dimensions[header_row].worksheet = target_ws
1829
- break
1830
- for header_row in range(1, header_count + 1):
1831
- for output_col, column in enumerate(active_columns, 1):
1832
- source = None
1833
- for side in ("theirs", "ours", "base"):
1834
- workbook = workbooks[side]
1835
- source_col = column.get(f"{side}Col")
1836
- if workbook is not None and names.get(side) in workbook.sheetnames and source_col is not None:
1837
- source = workbook[names[side]].cell(header_row, source_col)
1838
- if source.value is not None:
1839
- break
1840
- if source is not None:
1841
- _copy_cell(source, target_ws.cell(header_row, output_col))
1842
-
1843
- for output_offset, row in enumerate(active_rows, 1):
1844
- output_row = header_count + output_offset
1845
- dimension_source = None
1846
- for workbook, side in ((wb_ours, "ours"), (wb_theirs, "theirs"), (wb_base, "base")):
1847
- source_row = row.get(f"{side}Row")
1848
- if workbook is not None and names.get(side) in workbook.sheetnames and source_row is not None:
1849
- dimension_source = workbook[names[side]].row_dimensions[source_row]
1850
- break
1851
- if dimension_source is not None:
1852
- target_ws.row_dimensions[output_row] = copy(dimension_source)
1853
- target_ws.row_dimensions[output_row].worksheet = target_ws
1854
- for output_col, column in enumerate(active_columns, 1):
1855
- cell = cell_map.get(f'{row["id"]}|{column["id"]}') or {
1856
- "resolution": "same", "id": f'{row["id"]}|{column["id"]}', "coordinate": ""
1857
- }
1858
- choice = _cell_choice(cell_choices, cell)
1859
- source = _selected_source_cell(workbooks, names, row, column, cell, choice)
1860
- if source is not None:
1861
- # 空且无格式的 cell 跳过写入:目标默认状态即空,输出等价
1862
- if (
1863
- source.value is None
1864
- and not source.has_style
1865
- and source.hyperlink is None
1866
- and source.comment is None
1867
- ):
1868
- continue
1869
- _copy_cell(source, target_ws.cell(output_row, output_col))
1870
- # 公式 cell:记录输出坐标 -> 缓存值,保存后注入 XML
1871
- if source.data_type == 'f':
1872
- cached_source = _selected_source_cell(workbooks_v, names, row, column, cell, choice)
1873
- cached_val = cached_source.value if cached_source is not None else None
1874
- if cached_val is not None:
1875
- formula_cache[f'{get_column_letter(output_col)}{output_row}'] = cached_val
1876
-
1877
- _restore_merged_cells(target_ws, sheet, selection, active_rows, active_columns, header_count)
1878
-
1879
- if existing_name in wb_out.sheetnames:
1880
- wb_out.remove(wb_out[existing_name])
1881
- final_name = _selected_sheet_name(sheet, selection)
1882
- if final_name in wb_out.sheetnames and wb_out[final_name] is not target_ws:
1883
- raise ConflictError(f"Sheet name collision after merge: {final_name}")
1884
- target_ws.title = final_name
1885
- return {final_name: formula_cache}
1886
-
1887
-
1888
- def _build_merged_file(file_entry: dict[str, Any], decisions: dict[str, Any]) -> Path:
1889
- output = Path(file_entry["output"]).resolve()
1890
- output.parent.mkdir(parents=True, exist_ok=True)
1891
- extension = output.suffix.lower()
1892
- keep_vba = extension == ".xlsm"
1893
- file_choice = _file_decisions(decisions, file_entry["id"])
1894
- macro = file_entry.get("macro") or {}
1895
- macro_choice = file_choice.get("macro", macro.get("default", "ours"))
1896
- snapshot_meta = file_entry.get("valueSnapshots") or (file_entry.get("diff") or {}).get("valueSnapshots") or {}
1897
- if not snapshot_meta:
1898
- # Direct callers from older integrations may still build a workbook
1899
- # without a manifest. Permit that only when there are no formulas;
1900
- # a formula-bearing old input must never fall back to stale caches.
1901
- if any(_workbook_has_formula(file_entry[side]) for side in ("base", "ours", "theirs") if file_entry.get(side)):
1902
- raise ConflictError(
1903
- f"{file_entry['path']} has formulas but no immutable value snapshot; re-run prepare."
1904
- )
1905
- snapshot_meta = {
1906
- side: {"valuePath": file_entry.get(side)}
1907
- for side in ("base", "ours", "theirs") if file_entry.get(side)
1908
- }
1909
- value_paths: dict[str, Path | None] = {}
1910
- for side in ("base", "ours", "theirs"):
1911
- meta = snapshot_meta.get(side) or {}
1912
- path = meta.get("valuePath")
1913
- if path is None:
1914
- value_paths[side] = None
1915
- continue
1916
- value_path = Path(path).resolve()
1917
- if not value_path.exists():
1918
- raise ConflictError(f"Missing immutable {side} value snapshot for {file_entry['path']}: {value_path}")
1919
- expected = meta.get("valueSha256")
1920
- if expected and _sha256_path(value_path) != expected:
1921
- raise ConflictError(f"Immutable {side} value snapshot changed for {file_entry['path']}; refusing apply.")
1922
- _validate_value_workbook(value_path, allow_errors=True)
1923
- value_paths[side] = value_path
1924
- fd, temp_name = tempfile.mkstemp(prefix=f".{output.stem}-", suffix=extension, dir=output.parent)
1925
- os.close(fd)
1926
- temp_path = Path(temp_name)
1927
- wb_out = load_workbook(file_entry["ours"], data_only=False, keep_links=True, keep_vba=keep_vba)
1928
- # Original ours is the package/style/macro base. All sources used to
1929
- # rebuild an affected Sheet are the calculated literal snapshots.
1930
- wb_base = load_workbook(value_paths["base"], data_only=False, keep_links=True, keep_vba=keep_vba) if value_paths["base"] else None
1931
- wb_ours = load_workbook(value_paths["ours"], data_only=False, keep_links=True, keep_vba=keep_vba)
1932
- wb_theirs = load_workbook(value_paths["theirs"], data_only=False, keep_links=True, keep_vba=keep_vba)
1933
- wb_base_v = wb_ours_v = wb_theirs_v = None
1934
- sheet_choices = file_choice.get("sheets") or {}
1935
- formula_cache: dict[str, dict[str, Any]] = {}
1936
- affected_sheet_names: set[str] = set()
1937
- affected_output_sheet_names: set[str] = set()
1938
- output_sheet_names: set[str] = set()
1939
- try:
1940
- theirs_order = wb_theirs.sheetnames
1941
- for sheet in file_entry["diff"]["sheets"]:
1942
- name = sheet["name"]
1943
- action = sheet["action"]
1944
- selection = sheet_choices.get(name) or {}
1945
- whole_source = selection.get('sheet') in ('ours', 'theirs')
1946
- original_name = (sheet.get("names") or {}).get("ours") or name
1947
- is_affected = (
1948
- whole_source or action.startswith("conflict_")
1949
- or action in ("auto_add_ours", "auto_add_theirs")
1950
- or (
1951
- action == "merge"
1952
- and (
1953
- sheet.get("rebuildRequired", True)
1954
- or sheet.get("renameStatus") != "unchanged"
1955
- or (sheet.get("mergedCells") or {}).get("status") != "same"
1956
- )
1957
- )
1958
- )
1959
- if is_affected:
1960
- affected_sheet_names.add(original_name)
1961
- if whole_source:
1962
- affected_output_sheet_names.add((sheet.get('names') or {}).get(selection['sheet']) or name)
1963
- elif action == "merge":
1964
- affected_output_sheet_names.add(_selected_sheet_name(sheet, selection))
1965
- elif action.startswith("conflict_"):
1966
- affected_output_sheet_names.add((sheet.get("names") or {}).get(selection.get("sheet")) or name)
1967
- elif action == "auto_add_ours":
1968
- affected_output_sheet_names.add((sheet.get("names") or {}).get("ours") or name)
1969
- elif action == "auto_add_theirs":
1970
- affected_output_sheet_names.add((sheet.get("names") or {}).get("theirs") or name)
1971
- if action == "auto_delete":
1972
- if name in wb_out.sheetnames:
1973
- wb_out.remove(wb_out[name])
1974
- continue
1975
- if action == "auto_add_theirs":
1976
- theirs_name = (sheet.get("names") or {}).get("theirs") or name
1977
- ours_name = (sheet.get("names") or {}).get("ours")
1978
- if ours_name in wb_out.sheetnames:
1979
- wb_out.remove(wb_out[ours_name])
1980
- if theirs_name not in wb_out.sheetnames:
1981
- _copy_sheet(wb_theirs[theirs_name], wb_out, index=min(theirs_order.index(theirs_name), len(wb_out.sheetnames)))
1982
- continue
1983
- if action == "auto_add_ours":
1984
- ours_name = (sheet.get("names") or {}).get("ours") or name
1985
- if ours_name in wb_out.sheetnames:
1986
- wb_out.remove(wb_out[ours_name])
1987
- if ours_name in wb_ours.sheetnames:
1988
- _copy_sheet(
1989
- wb_ours[ours_name], wb_out,
1990
- index=min(wb_ours.sheetnames.index(ours_name), len(wb_out.sheetnames)),
1991
- )
1992
- continue
1993
- if whole_source or action.startswith("conflict_"):
1994
- side = selection["sheet"]
1995
- if side == "ours":
1996
- source_wb = wb_ours
1997
- else:
1998
- source_wb = wb_theirs
1999
- source_name = (sheet.get("names") or {}).get(side) or name
2000
- if source_name in source_wb.sheetnames:
2001
- from formula_values import _set_literal
2002
- for coordinate, value in _selected_repairs(sheet, selection).items():
2003
- _set_literal(source_wb[source_name][coordinate], value)
2004
- ours_name = (sheet.get("names") or {}).get("ours") or name
2005
- if ours_name != source_name and ours_name in wb_out.sheetnames:
2006
- wb_out.remove(wb_out[ours_name])
2007
- if source_name in source_wb.sheetnames:
2008
- _replace_sheet(wb_out, source_wb[source_name], source_wb.sheetnames)
2009
- elif name in wb_out.sheetnames:
2010
- wb_out.remove(wb_out[name])
2011
- continue
2012
- if action != "merge":
2013
- continue
2014
- if not is_affected:
2015
- # Formula text may differ while final values are equal. This
2016
- # is intentionally an untouched Sheet: preserve ours exactly.
2017
- continue
2018
- if not sheet.get("rebuildRequired", True):
2019
- existing_name = (sheet.get("names") or {}).get("ours") or name
2020
- final_name = _selected_sheet_name(sheet, selection)
2021
- # A rename-only/metadata-only changed Sheet is still affected;
2022
- # replace it from the selected calculated value snapshot so no
2023
- # formula survives through this fast path.
2024
- source_side = selection.get("rename", "ours") if sheet.get("renameStatus") == "rename_conflict" else "ours"
2025
- source_name = (sheet.get("names") or {}).get(source_side) or existing_name
2026
- source_wb = wb_theirs if source_side == "theirs" else wb_ours
2027
- if source_name in source_wb.sheetnames:
2028
- if existing_name in wb_out.sheetnames:
2029
- old_index = wb_out.sheetnames.index(existing_name)
2030
- wb_out.remove(wb_out[existing_name])
2031
- else:
2032
- old_index = len(wb_out.sheetnames)
2033
- copied = _copy_sheet(source_wb[source_name], wb_out, index=old_index)
2034
- if final_name != copied.title:
2035
- if final_name in wb_out.sheetnames and wb_out[final_name] is not copied:
2036
- raise ConflictError(f"Sheet name collision after merge: {final_name}")
2037
- copied.title = final_name
2038
- continue
2039
- if sheet.get("allRows") is not None and sheet.get("columns") is not None:
2040
- cache = _rebuild_structural_sheet(
2041
- wb_out, wb_base, wb_ours, wb_theirs, sheet, selection,
2042
- wb_base_v, wb_ours_v, wb_theirs_v,
2043
- )
2044
- formula_cache.update(cache)
2045
- continue
2046
- # Legacy coordinate-only reports are now also sourced from the
2047
- # literal snapshot. They should be rare (structural reports use
2048
- # _rebuild_structural_sheet), but must obey the same no-formula rule.
2049
- if name not in wb_ours.sheetnames:
2050
- raise ConflictError(f"Missing ours Sheet {name} in legacy merge report.")
2051
- # Start from the literal ours snapshot so unchanged formula cells
2052
- # on this affected Sheet cannot survive the legacy patch path.
2053
- _replace_sheet(wb_out, wb_ours[name], wb_ours.sheetnames)
2054
- ws_out = wb_out[name]
2055
- ws_theirs = wb_theirs[name]
2056
- cell_choices = selection.get("cells") or {}
2057
- for cell in sheet["cells"]:
2058
- side = cell_choices.get(cell["coordinate"], cell["resolution"])
2059
- if side == "conflict":
2060
- side = cell_choices[cell["coordinate"]]
2061
- if side == "theirs":
2062
- _copy_cell(ws_theirs[cell["coordinate"]], ws_out[cell["coordinate"]])
2063
- if not wb_out.sheetnames:
2064
- raise ConflictError(f"Cannot save a workbook with no sheets: {file_entry['path']}")
2065
- output_sheet_names = set(wb_out.sheetnames)
2066
- wb_out.save(temp_path)
2067
- except Exception:
2068
- temp_path.unlink(missing_ok=True)
2069
- raise
2070
- finally:
2071
- _close_workbook(wb_out)
2072
- _close_workbook(wb_base)
2073
- if wb_ours is not wb_out:
2074
- _close_workbook(wb_ours)
2075
- _close_workbook(wb_theirs)
2076
- _close_workbook(wb_base_v)
2077
- _close_workbook(wb_ours_v)
2078
- _close_workbook(wb_theirs_v)
2079
-
2080
- try:
2081
- _restore_untouched_formula_caches(
2082
- Path(file_entry['ours']), temp_path, output_sheet_names - affected_sheet_names,
2083
- )
2084
- _preserve_empty_inline_strings(temp_path)
2085
- check_wb = load_workbook(temp_path, read_only=True, data_only=False)
2086
- try:
2087
- for ws in check_wb.worksheets:
2088
- if ws.title not in affected_output_sheet_names:
2089
- continue
2090
- for row in ws.iter_rows():
2091
- for cell in row:
2092
- if cell.data_type == "f":
2093
- raise ConflictError(
2094
- f"Affected Sheet {ws.title} retained formula at {cell.coordinate}; output was not written."
2095
- )
2096
- if cell.data_type == "e":
2097
- raise ConflictError(f"Selected source contains an Excel error at {ws.title}!{cell.coordinate}; output was not written.")
2098
- finally:
2099
- check_wb.close()
2100
- if keep_vba:
2101
- macro_source = file_entry["theirs"] if macro_choice == "theirs" else file_entry["ours"]
2102
- if macro_choice == "theirs":
2103
- if not macro.get("canChooseTheirs", True):
2104
- raise ConflictError(
2105
- f"Cannot safely preserve the REMOTE macro payload for {file_entry['path']} because its package structure differs."
2106
- )
2107
- _replace_macro_payload(temp_path, macro_source)
2108
- expected_hash, expected_entries = _macro_payload_digest(macro_source)
2109
- actual_hash, actual_entries = _macro_payload_digest(temp_path)
2110
- if actual_hash != expected_hash or actual_entries != expected_entries:
2111
- raise ConflictError(f"Macro payload changed while saving {file_entry['path']}; output was not written.")
2112
- return temp_path
2113
- except Exception:
2114
- temp_path.unlink(missing_ok=True)
2115
- raise
2116
-
2117
-
2118
- def _git_step(repo: Path, args: list[str], label: str) -> dict[str, Any]:
2119
- result = _run_git(repo, args)
2120
- output = (result.stdout + result.stderr).strip()
2121
- return {"step": label, "success": result.returncode == 0, "output": output}
2122
-
2123
-
2124
- def _apply_auto_theirs(repo: Path, entries: list[dict[str, Any]]) -> list[Path]:
2125
- """Write auto-theirs workbooks byte-for-byte from Git index stage 3."""
2126
- outputs: list[Path] = []
2127
- for entry in entries:
2128
- relative_path = entry["path"]
2129
- output = (repo / Path(relative_path)).resolve()
2130
- if os.path.commonpath([str(repo), str(output)]) != str(repo):
2131
- raise ConflictError(f"Output escapes repository: {output}")
2132
- blob = _git_blob(repo, 3, relative_path)
2133
- if blob is None:
2134
- raise ConflictError(f"{relative_path} matches the auto-theirs rule, but Git stage 3 is missing.")
2135
- output.parent.mkdir(parents=True, exist_ok=True)
2136
- with open(output, "wb") as handle:
2137
- handle.write(blob)
2138
- outputs.append(output)
2139
- return outputs
2140
-
2141
-
2142
- def _build_commit_message(manifest: dict[str, Any], decisions: dict[str, Any]) -> str:
2143
- """生成结构化提交信息:每个已选择的冲突 Cell 一行。
2144
-
2145
- 格式:resolve: [表:path]-[sheet:name]-[单元格:A1]-[选择:远端/本地] [远端值:xxx 本地值:xxx]
2146
- 无冲突 Cell 时回退默认信息。
2147
- """
2148
- lines: list[str] = []
2149
- for entry in manifest.get("autoTheirs") or []:
2150
- lines.append(f"resolve(auto): [表:{entry['path']}]-[选择:远端全量]")
2151
- for file_entry in manifest["files"]:
2152
- file_choice = _file_decisions(decisions, file_entry["id"])
2153
- sheet_choices = file_choice.get("sheets") or {}
2154
- for sheet in file_entry["diff"]["sheets"]:
2155
- choice = sheet_choices.get(sheet["name"]) or {}
2156
- if choice.get('sheet') in ('ours', 'theirs'):
2157
- lines.append(f"resolve(sheet): [表:{file_entry['path']}]-[sheet:{sheet['name']}]-[选择:{choice['sheet']} 全量]")
2158
- for coordinate, value in _selected_repairs(sheet, choice).items():
2159
- lines.append(f"resolve(manual): [表:{file_entry['path']}]-[sheet:{sheet['name']}]-[来源:{choice['sheet']}]-[单元格:{coordinate}]-[值:{json.dumps(value, ensure_ascii=False)}]")
2160
- recorded = set()
2161
- for repair in sheet.get("replacements", []):
2162
- if sheet["action"].startswith("conflict_") and repair["side"] != choice.get("sheet"):
2163
- continue
2164
- key = (repair["side"], repair["coordinate"]) if repair.get("manual") else (repair["recordId"], repair["field"])
2165
- if key in recorded:
2166
- continue
2167
- recorded.add(key)
2168
- if repair.get("manual"):
2169
- lines.append(f"resolve(manual): [表:{file_entry['path']}]-[sheet:{sheet['name']}]-[来源:{repair['side']}]-[单元格:{repair['coordinate']}]-[字段:{repair['field']}]-[类型:{repair['type']}]-[值:{json.dumps(repair['value'], ensure_ascii=False)}]")
2170
- else:
2171
- lines.append(f"resolve(default): [表:{file_entry['path']}]-[sheet:{sheet['name']}]-[id:{repair['recordId']}]-[字段:{repair['field']}]-[类型:{repair['type']}]-[值:{json.dumps(repair['value'], ensure_ascii=False)}]")
2172
- cell_choices = choice.get("cells") or {}
2173
- if choice.get('sheet') in ('ours', 'theirs'):
2174
- continue
2175
- for cell in sheet["cells"]:
2176
- if cell.get("resolution") != "conflict":
2177
- continue
2178
- cell_choice = _cell_choice(cell_choices, cell)
2179
- if cell_choice not in ("ours", "theirs"):
2180
- continue
2181
- label = cell.get("coordinate") or cell.get("id") or ""
2182
- side = "远端" if cell_choice == "theirs" else "本地"
2183
- theirs_value = _message_value(cell.get("theirs"))
2184
- ours_value = _message_value(cell.get("ours"))
2185
- lines.append(
2186
- f"resolve: [表:{file_entry['path']}]-[sheet:{sheet['name']}]-[单元格:{label}]-[选择:{side}] "
2187
- f"[远端值:{theirs_value} 本地值:{ours_value}]"
2188
- )
2189
- if not lines:
2190
- return "resolve: merge xlsx conflicts"
2191
- message = "\n".join(lines)
2192
- # 防止超长消息撑爆 git commit 命令行(Windows 单条命令约 32K 字符)
2193
- if len(message) > MAX_COMMIT_MESSAGE_CHARS:
2194
- message = message[:MAX_COMMIT_MESSAGE_CHARS].rstrip() + "\n... (truncated)"
2195
- return message
2196
-
2197
-
2198
- MAX_COMMIT_MESSAGE_CHARS = 20000
2199
-
2200
-
2201
- def _message_value(value) -> str:
2202
- """Cell 显示值转提交信息字符串:None 转空,浮点去多余小数。"""
2203
- if value is None:
2204
- return ""
2205
- if isinstance(value, float):
2206
- return str(int(value)) if value == int(value) else str(value)
2207
- return str(value)
2208
-
2209
-
2210
- def _validate_manifest_sources(manifest: dict[str, Any], repo: Path) -> None:
2211
- """Preflight every input before preparing any output replacement.
2212
-
2213
- This deliberately validates both extracted files and their current index
2214
- stages. A user may keep the UI open while another process changes a
2215
- conflict, in which case applying the old choices would be data loss.
2216
- """
2217
- for entry in manifest.get("files") or []:
2218
- relative = entry["path"]
2219
- for side, stage in (("base", 1), ("ours", 2), ("theirs", 3)):
2220
- meta = (entry.get("valueSnapshots") or {}).get(side) or {}
2221
- source_path = entry.get(side)
2222
- if source_path is None:
2223
- if stage == 1 and _git_blob(repo, stage, relative) is None:
2224
- continue
2225
- raise ConflictError(f"Manifest source missing for {relative} ({side}).")
2226
- source = Path(source_path).resolve()
2227
- if not source.exists():
2228
- raise ConflictError(f"Manifest source missing for {relative} ({side}): {source}")
2229
- expected_source = meta.get("sourceSha256")
2230
- actual_source = _sha256_path(source)
2231
- if expected_source and actual_source != expected_source:
2232
- raise ConflictError(f"Manifest source changed for {relative} ({side}); refusing apply.")
2233
- indexed = _git_blob(repo, stage, relative)
2234
- if indexed is None:
2235
- raise ConflictError(f"Git index stage {stage} changed or disappeared for {relative} ({side}).")
2236
- expected_index = meta.get("gitIndexSha256") or expected_source
2237
- if expected_index and hashlib.sha256(indexed).hexdigest() != expected_index:
2238
- raise ConflictError(f"Git index source changed for {relative} ({side}); re-run prepare.")
2239
- value_path = meta.get("valuePath")
2240
- expected_value = meta.get("valueSha256")
2241
- if not value_path or not expected_value:
2242
- raise ConflictError(f"Manifest has no immutable value snapshot for {relative} ({side}).")
2243
- snapshot = Path(value_path).resolve()
2244
- if not snapshot.exists() or _sha256_path(snapshot) != expected_value:
2245
- raise ConflictError(f"Immutable value snapshot changed for {relative} ({side}); refusing apply.")
2246
- _validate_value_workbook(snapshot, allow_errors=True)
2247
- output = (repo / Path(relative)).resolve()
2248
- expected_output = entry.get("outputSha256")
2249
- if expected_output is None:
2250
- if output.exists():
2251
- raise ConflictError(f"Worktree output appeared after prepare for {relative}; refusing overwrite.")
2252
- elif not output.exists() or _sha256_path(output) != expected_output:
2253
- raise ConflictError(f"Worktree output changed for {relative}; re-run prepare before apply.")
2254
- for entry in manifest.get("autoTheirs") or []:
2255
- relative = entry["path"]
2256
- blob = _git_blob(repo, 3, relative)
2257
- if blob is None:
2258
- raise ConflictError(f"{relative} requires remote stage 3, but it is no longer available.")
2259
- expected = entry.get("theirsSha256")
2260
- if expected and hashlib.sha256(blob).hexdigest() != expected:
2261
- raise ConflictError(f"Remote source changed for automatic table {relative}; re-run prepare.")
2262
- output = (repo / Path(relative)).resolve()
2263
- expected_output = entry.get("outputSha256")
2264
- if expected_output is None:
2265
- if output.exists():
2266
- raise ConflictError(f"Worktree output appeared after prepare for {relative}; refusing overwrite.")
2267
- elif not output.exists() or _sha256_path(output) != expected_output:
2268
- raise ConflictError(f"Worktree output changed for {relative}; re-run prepare before apply.")
2269
-
2270
-
2271
- def _replace_prepared_outputs(prepared: list[tuple[Path, Path]]) -> None:
2272
- """Replace only after all outputs exist; roll back earlier swaps on failure."""
2273
- backups: dict[Path, Path | None] = {}
2274
- replaced: list[Path] = []
2275
- retained: set[Path] = set()
2276
- try:
2277
- for output, _ in prepared:
2278
- if output.exists():
2279
- fd, backup_name = tempfile.mkstemp(prefix=f".{output.stem}-backup-", suffix=output.suffix, dir=output.parent)
2280
- os.close(fd)
2281
- backup = Path(backup_name)
2282
- backups[output] = backup
2283
- shutil.copy2(output, backup)
2284
- else:
2285
- backups[output] = None
2286
- try:
2287
- for output, temporary in prepared:
2288
- os.replace(temporary, output)
2289
- replaced.append(output)
2290
- except Exception as exc:
2291
- errors = []
2292
- for output in reversed(replaced):
2293
- backup = backups[output]
2294
- try:
2295
- if backup is None:
2296
- output.unlink(missing_ok=True)
2297
- else:
2298
- os.replace(backup, output)
2299
- except Exception as restore_error:
2300
- if backup is not None:
2301
- retained.add(backup)
2302
- errors.append(f"{output}: {restore_error}; recovery copy: {backup}")
2303
- if errors:
2304
- raise ConflictError("Output replacement failed; recovery copies retained: " + "; ".join(errors)) from exc
2305
- raise ConflictError("Output replacement failed; earlier replacements rolled back; Git index unchanged.") from exc
2306
- finally:
2307
- for backup in backups.values():
2308
- if backup is not None and backup not in retained:
2309
- backup.unlink(missing_ok=True)
2310
-
2311
-
2312
- def apply_manifest(
2313
- manifest_path: Path | str,
2314
- decisions: dict[str, Any],
2315
- *,
2316
- commit: bool = True,
2317
- push: bool = False,
2318
- message: str | None = None,
2319
- ) -> dict[str, Any]:
2320
- manifest = load_manifest(manifest_path)
2321
- _validate_decisions(manifest, decisions)
2322
- repo = find_repo_root(manifest["repoRoot"])
2323
- # Validate every immutable source, calculated-value snapshot, and worktree
2324
- # output before creating any replacement. A failed preflight leaves both
2325
- # the worktree and Git index untouched.
2326
- _validate_manifest_sources(manifest, repo)
2327
- auto_entries = manifest.get("autoTheirs") or []
2328
- if not manifest["files"] and not auto_entries:
2329
- raise ConflictError("Manifest has no conflicts to resolve.")
2330
- prepared: list[tuple[Path, Path]] = []
2331
- manual_outputs: list[Path] = []
2332
- auto_outputs: list[Path] = []
2333
- try:
2334
- for file_entry in manifest["files"]:
2335
- output = Path(file_entry["output"]).resolve()
2336
- if os.path.commonpath([str(repo), str(output)]) != str(repo):
2337
- raise ConflictError(f"Output escapes repository: {output}")
2338
- prepared.append((output, _build_merged_file(file_entry, decisions)))
2339
- manual_outputs.append(output)
2340
- for entry in auto_entries:
2341
- output = (repo / entry["path"]).resolve()
2342
- if os.path.commonpath([str(repo), str(output)]) != str(repo):
2343
- raise ConflictError(f"Output escapes repository: {output}")
2344
- blob = _git_blob(repo, 3, entry["path"])
2345
- if blob is None or hashlib.sha256(blob).hexdigest() != entry.get("theirsSha256"):
2346
- raise ConflictError(f"Remote source changed for automatic table {entry['path']}.")
2347
- output.parent.mkdir(parents=True, exist_ok=True)
2348
- fd, temporary_name = tempfile.mkstemp(
2349
- prefix=f".{output.stem}-", suffix=output.suffix, dir=output.parent
2350
- )
2351
- temporary = Path(temporary_name)
2352
- prepared.append((output, temporary))
2353
- with os.fdopen(fd, "wb") as handle:
2354
- handle.write(blob)
2355
- auto_outputs.append(output)
2356
-
2357
- # Builds may be expensive, so check the inputs once more immediately
2358
- # before the atomic batch replacement.
2359
- _validate_manifest_sources(manifest, repo)
2360
- _replace_prepared_outputs(prepared)
2361
-
2362
- outputs = [output for output, _ in prepared]
2363
- relative_paths = [str(output.relative_to(repo)).replace("\\", "/") for output in outputs]
2364
- steps = [_git_step(repo, ["add", "--", *relative_paths], "git add")]
2365
- success = steps[-1]["success"]
2366
- if success and commit:
2367
- commit_message = message or _build_commit_message(manifest, decisions)
2368
- steps.append(_git_step(repo, ["commit", "-m", commit_message], "git commit"))
2369
- success = steps[-1]["success"]
2370
- if success and push:
2371
- steps.append(_git_step(repo, ["push"], "git push"))
2372
- success = steps[-1]["success"]
2373
- return {
2374
- "success": success,
2375
- "merged": [str(output) for output in manual_outputs],
2376
- "autoTheirs": [str(output.relative_to(repo)).replace("\\", "/") for output in auto_outputs],
2377
- "steps": steps,
2378
- }
2379
- finally:
2380
- for _, temp_path in prepared:
2381
- temp_path.unlink(missing_ok=True)
1
+ """Three-way, sheet-aware XLSX conflict detection and merge primitives."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import io
7
+ import json
8
+ import os
9
+ import re
10
+ import shutil
11
+ import subprocess
12
+ import sys
13
+ import tempfile
14
+ import zipfile
15
+ from copy import copy
16
+ from datetime import date, datetime, time
17
+ from pathlib import Path
18
+ from typing import Any, Iterable
19
+
20
+ from openpyxl import load_workbook
21
+ from openpyxl.cell.cell import MergedCell
22
+ from openpyxl.utils import column_index_from_string, get_column_letter
23
+ from openpyxl.utils.datetime import to_excel
24
+
25
+ # 兼容嵌入式 Python(._pth 忽略 PYTHONPATH):包内自举,将包根加入 sys.path
26
+ _PKG_ROOT = Path(__file__).resolve().parents[1]
27
+ if str(_PKG_ROOT) not in sys.path:
28
+ sys.path.insert(0, str(_PKG_ROOT))
29
+
30
+ from xlsx_merge_engine.xlsx_git_merge_bridge import analyze_workbooks as analyze_structural_workbooks
31
+ from prepare_progress import checkpoint, PreparationCancelled
32
+
33
+
34
+ class ConflictError(RuntimeError):
35
+ """Raised when a conflict cannot be prepared or resolved safely."""
36
+
37
+
38
+ WORKBOOK_EXTENSIONS = {".xlsx", ".xlsm"}
39
+
40
+
41
+ def _is_supported_workbook(path: str | Path) -> bool:
42
+ return Path(path).suffix.lower() in WORKBOOK_EXTENSIONS
43
+
44
+
45
+ def _is_macro_workbook(path: str | Path) -> bool:
46
+ return Path(path).suffix.lower() == ".xlsm"
47
+
48
+
49
+ CONFIG_FILENAME = ".xlmerge.json"
50
+
51
+
52
+ def _normalize_filter_path(pattern: str) -> str:
53
+ normalized = pattern.replace("\\", "/").strip()
54
+ while normalized.startswith("./"):
55
+ normalized = normalized[2:]
56
+ parts = normalized.split("/")
57
+ if (
58
+ not normalized
59
+ or Path(normalized).is_absolute()
60
+ or any(part in ("", ".", "..") for part in parts)
61
+ or not _is_supported_workbook(normalized)
62
+ ):
63
+ raise ConflictError("Filter must be a relative .xlsx/.xlsm path without empty, '.' or '..' segments.")
64
+ return normalized
65
+
66
+
67
+ def load_auto_theirs_filters(repo: Path | str) -> list[str]:
68
+ """Load repository-scoped auto-theirs suffix filters; missing config means no filters."""
69
+ repo_root = find_repo_root(repo)
70
+ config_path = repo_root / CONFIG_FILENAME
71
+ if not config_path.exists():
72
+ return []
73
+ try:
74
+ data = json.loads(config_path.read_text(encoding="utf-8"))
75
+ except (OSError, json.JSONDecodeError) as exc:
76
+ raise ConflictError(f"Invalid {CONFIG_FILENAME}: {exc}") from exc
77
+ if not isinstance(data, dict) or not isinstance(data.get("autoTheirs", []), list):
78
+ raise ConflictError(f"Invalid {CONFIG_FILENAME}: 'autoTheirs' must be an array.")
79
+ filters: list[str] = []
80
+ for value in data.get("autoTheirs", []):
81
+ if not isinstance(value, str):
82
+ raise ConflictError(f"Invalid {CONFIG_FILENAME}: every autoTheirs entry must be a string.")
83
+ filters.append(_normalize_filter_path(value))
84
+ return filters
85
+
86
+
87
+ def add_auto_theirs_filter(repo: Path | str, pattern: str) -> dict[str, Any]:
88
+ """Persist one repository-scoped auto-theirs suffix filter atomically."""
89
+ repo_root = find_repo_root(repo)
90
+ normalized = _normalize_filter_path(pattern)
91
+ config_path = repo_root / CONFIG_FILENAME
92
+ data: dict[str, Any] = {}
93
+ if config_path.exists():
94
+ try:
95
+ loaded = json.loads(config_path.read_text(encoding="utf-8"))
96
+ except (OSError, json.JSONDecodeError) as exc:
97
+ raise ConflictError(f"Invalid {CONFIG_FILENAME}: {exc}") from exc
98
+ if not isinstance(loaded, dict):
99
+ raise ConflictError(f"Invalid {CONFIG_FILENAME}: root must be an object.")
100
+ data = loaded
101
+ filters = load_auto_theirs_filters(repo_root)
102
+ existing = {value.lower() for value in filters}
103
+ added = normalized.lower() not in existing
104
+ if added:
105
+ filters.append(normalized)
106
+ data["autoTheirs"] = filters
107
+ temp_path = config_path.with_name(f".{config_path.name}.{os.getpid()}.tmp")
108
+ try:
109
+ temp_path.write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
110
+ os.replace(temp_path, config_path)
111
+ finally:
112
+ temp_path.unlink(missing_ok=True)
113
+ return {
114
+ "config": str(config_path),
115
+ "filter": normalized,
116
+ "added": added,
117
+ "filters": filters,
118
+ }
119
+
120
+
121
+ def auto_theirs_path(relative_path: str, filters: Iterable[str]) -> str | None:
122
+ """Return the canonical filter for a case-insensitive path-suffix match."""
123
+ parts = relative_path.replace("\\", "/").lower().split("/")
124
+ for pattern in filters:
125
+ expected = pattern.lower().split("/")
126
+ if len(parts) >= len(expected) and parts[-len(expected):] == expected:
127
+ return pattern
128
+ return None
129
+
130
+
131
+ def _is_macro_payload_entry(name: str) -> bool:
132
+ lowered = name.lower()
133
+ return (
134
+ lowered.startswith(("xl/vba", "xl/ctrlprops/", "customui/", "xl/activex/"))
135
+ or (lowered.startswith("xl/drawings/") and "vmldrawing" in lowered and lowered.endswith(".vml"))
136
+ or (lowered.startswith("xl/media/") and lowered.endswith(".emf"))
137
+ )
138
+
139
+
140
+ def _macro_payload_digest(source: bytes | Path | str) -> tuple[str, list[str]]:
141
+ raw = source if isinstance(source, bytes) else Path(source).read_bytes()
142
+ try:
143
+ with zipfile.ZipFile(io.BytesIO(raw)) as archive:
144
+ entries = sorted(name for name in archive.namelist() if _is_macro_payload_entry(name))
145
+ digest = hashlib.sha256()
146
+ for name in entries:
147
+ digest.update(name.encode("utf-8"))
148
+ digest.update(b"\0")
149
+ digest.update(archive.read(name))
150
+ return digest.hexdigest(), entries
151
+ except (OSError, zipfile.BadZipFile) as exc:
152
+ raise ConflictError(f"Invalid macro-enabled workbook package: {exc}") from exc
153
+
154
+
155
+ def _macro_payload_info(base_blob: bytes | None, ours_blob: bytes, theirs_blob: bytes) -> dict[str, Any]:
156
+ base_hash, base_entries = _macro_payload_digest(base_blob) if base_blob is not None else (None, [])
157
+ ours_hash, ours_entries = _macro_payload_digest(ours_blob)
158
+ theirs_hash, theirs_entries = _macro_payload_digest(theirs_blob)
159
+ ours_key = (ours_hash, ours_entries)
160
+ theirs_key = (theirs_hash, theirs_entries)
161
+ base_key = (base_hash, base_entries) if base_hash is not None else None
162
+ compatible = ours_entries == theirs_entries
163
+ if ours_key == theirs_key:
164
+ status, default = "same", "ours"
165
+ elif not compatible:
166
+ status, default = "incompatible", "ours"
167
+ elif base_key is not None and ours_key == base_key:
168
+ status, default = "auto_theirs", "theirs"
169
+ elif base_key is not None and theirs_key == base_key:
170
+ status, default = "auto_ours", "ours"
171
+ else:
172
+ status, default = "conflict", "ours"
173
+ return {
174
+ "status": status,
175
+ "default": default,
176
+ "canChooseTheirs": compatible,
177
+ "baseHash": base_hash,
178
+ "oursHash": ours_hash,
179
+ "theirsHash": theirs_hash,
180
+ "baseEntries": base_entries,
181
+ "oursEntries": ours_entries,
182
+ "theirsEntries": theirs_entries,
183
+ }
184
+
185
+
186
+ def _replace_macro_payload(target: Path, source: Path | str) -> None:
187
+ source_path = Path(source)
188
+ with zipfile.ZipFile(target) as target_archive, zipfile.ZipFile(source_path) as source_archive:
189
+ target_parts = [
190
+ (info, target_archive.read(info.filename))
191
+ for info in target_archive.infolist()
192
+ if not _is_macro_payload_entry(info.filename)
193
+ ]
194
+ source_parts = [
195
+ (info, source_archive.read(info.filename))
196
+ for info in source_archive.infolist()
197
+ if _is_macro_payload_entry(info.filename)
198
+ ]
199
+ fd, replacement_name = tempfile.mkstemp(prefix=f".{target.stem}-macro-", suffix=target.suffix, dir=target.parent)
200
+ os.close(fd)
201
+ replacement = Path(replacement_name)
202
+ try:
203
+ with zipfile.ZipFile(replacement, "w") as output_archive:
204
+ for info, payload in [*target_parts, *source_parts]:
205
+ output_archive.writestr(info, payload)
206
+ os.replace(replacement, target)
207
+ finally:
208
+ replacement.unlink(missing_ok=True)
209
+
210
+
211
+ def _close_workbook(workbook) -> None:
212
+ if workbook is None:
213
+ return
214
+ vba_archive = getattr(workbook, "vba_archive", None)
215
+ workbook.close()
216
+ if vba_archive is not None:
217
+ vba_archive.close()
218
+
219
+
220
+ def _run_git(repo: Path, args: list[str], *, binary: bool = False, check: bool = False):
221
+ result = subprocess.run(
222
+ ["git", "-C", str(repo), "-c", "core.quotepath=false", *args],
223
+ capture_output=True,
224
+ text=not binary,
225
+ encoding=None if binary else "utf-8",
226
+ errors=None if binary else "replace",
227
+ timeout=60,
228
+ )
229
+ if check and result.returncode != 0:
230
+ stderr = result.stderr.decode("utf-8", "replace") if binary else result.stderr
231
+ raise ConflictError(f"git {' '.join(args)} failed: {stderr.strip()}")
232
+ return result
233
+
234
+
235
+ def find_repo_root(repo: Path | str) -> Path:
236
+ candidate = Path(repo).resolve()
237
+ result = _run_git(candidate, ["rev-parse", "--show-toplevel"])
238
+ if result.returncode != 0:
239
+ raise ConflictError(f"Not a Git repository: {candidate}")
240
+ return Path(result.stdout.strip()).resolve()
241
+
242
+
243
+ def detect_conflicts(repo: Path | str) -> list[dict[str, Any]]:
244
+ repo_root = find_repo_root(repo)
245
+ result = _run_git(repo_root, ["diff", "--name-only", "--diff-filter=U", "-z"], binary=True, check=True)
246
+ paths = result.stdout.decode("utf-8", "surrogateescape").split("\0")
247
+ conflicts: list[dict[str, Any]] = []
248
+ for relative_path in paths:
249
+ if not relative_path or not _is_supported_workbook(relative_path):
250
+ continue
251
+ stages_result = _run_git(repo_root, ["ls-files", "-u", "--", relative_path], check=True)
252
+ stages: list[int] = []
253
+ for line in stages_result.stdout.splitlines():
254
+ prefix = line.split("\t", 1)[0].split()
255
+ if len(prefix) >= 3:
256
+ stages.append(int(prefix[2]))
257
+ conflicts.append({"path": relative_path.replace("\\", "/"), "stages": sorted(set(stages))})
258
+ return conflicts
259
+
260
+
261
+ def _git_blob(repo: Path, stage: int, relative_path: str) -> bytes | None:
262
+ result = _run_git(repo, ["show", f":{stage}:{relative_path}"], binary=True)
263
+ return result.stdout if result.returncode == 0 else None
264
+
265
+
266
+ def _safe_runtime_dir(repo: Path, runtime_dir: Path | str | None) -> Path:
267
+ if runtime_dir:
268
+ target = Path(runtime_dir).resolve()
269
+ else:
270
+ repo_key = str(abs(hash(str(repo).lower())))
271
+ target = Path(tempfile.gettempdir()) / "xlmerge" / repo_key
272
+ target.mkdir(parents=True, exist_ok=True)
273
+ return target
274
+
275
+
276
+ def _slug(relative_path: str) -> str:
277
+ safe = "".join(ch if ch.isalnum() or ch in "-_." else "_" for ch in relative_path)
278
+ return safe[-120:] or "workbook"
279
+
280
+
281
+ def _repair_invalid_dimension_styles(path: Path) -> None:
282
+ """Remove row or column style ids missing from an extracted style table."""
283
+ with zipfile.ZipFile(path, "r") as source:
284
+ try:
285
+ styles = source.read("xl/styles.xml")
286
+ except KeyError:
287
+ return
288
+ cell_xfs = re.search(rb"<cellXfs\b[^>]*>(.*?)</cellXfs>", styles, re.DOTALL)
289
+ if cell_xfs is None:
290
+ return
291
+ style_count = len(re.findall(rb"<xf\b", cell_xfs.group(1)))
292
+ replacements: dict[str, bytes] = {}
293
+ for name in source.namelist():
294
+ if not name.startswith("xl/worksheets/") or not name.endswith(".xml"):
295
+ continue
296
+ payload = source.read(name)
297
+
298
+ def repair_row(match: re.Match[bytes]) -> bytes:
299
+ tag = match.group(0)
300
+ style = re.search(rb'\bs="(\d+)"', tag)
301
+ if style is None or int(style.group(1)) < style_count:
302
+ return tag
303
+ tag = re.sub(rb'\s+s="\d+"', b"", tag, count=1)
304
+ return re.sub(rb'\s+customFormat="[01]"', b"", tag, count=1)
305
+
306
+ repaired = re.sub(rb"<row\b[^>]*>", repair_row, payload)
307
+ def repair_column(match: re.Match[bytes]) -> bytes:
308
+ tag = match.group(0)
309
+ style = re.search(rb'\bstyle="(\d+)"', tag)
310
+ if style is None or int(style.group(1)) < style_count:
311
+ return tag
312
+ return re.sub(rb'\s+style="\d+"', b"", tag, count=1)
313
+
314
+ repaired = re.sub(rb"<col\b[^>]*/?>", repair_column, repaired)
315
+ if repaired != payload:
316
+ replacements[name] = repaired
317
+ if not replacements:
318
+ return
319
+ entries = [(info, replacements.get(info.filename, source.read(info.filename))) for info in source.infolist()]
320
+
321
+ temporary = path.with_name(f".{path.name}.row-styles.tmp")
322
+ try:
323
+ with zipfile.ZipFile(temporary, "w") as output:
324
+ for info, payload in entries:
325
+ output.writestr(info, payload)
326
+ os.replace(temporary, path)
327
+ finally:
328
+ if temporary.exists():
329
+ temporary.unlink()
330
+
331
+
332
+ def _json_value(value: Any) -> Any:
333
+ if value is None or isinstance(value, (bool, int, float, str)):
334
+ return value
335
+ if isinstance(value, (datetime, date, time)):
336
+ return value.isoformat()
337
+ return str(value)
338
+
339
+
340
+ def _sha256_path(path: Path | str) -> str:
341
+ """Return a content digest without loading large workbook into memory."""
342
+ digest = hashlib.sha256()
343
+ with Path(path).open("rb") as handle:
344
+ for block in iter(lambda: handle.read(1024 * 1024), b""):
345
+ digest.update(block)
346
+ return digest.hexdigest()
347
+
348
+
349
+ def _workbook_has_formula(path: Path | str) -> bool:
350
+ workbook = load_workbook(path, data_only=False, keep_links=True, read_only=True)
351
+ try:
352
+ return any(
353
+ cell.data_type == "f"
354
+ for ws in workbook.worksheets
355
+ for row in ws.iter_rows()
356
+ for cell in row
357
+ )
358
+ finally:
359
+ workbook.close()
360
+
361
+
362
+ def _validate_value_workbook(path: Path | str, *, allow_errors: bool = False) -> list[dict[str, Any]]:
363
+ """Validate literal snapshots; only history can contain typed unknowns."""
364
+ from formula_values import _ERROR_VALUES
365
+ errors = []
366
+ workbook = load_workbook(path, data_only=False, keep_links=True, read_only=True)
367
+ try:
368
+ for ws in workbook.worksheets:
369
+ for row in ws.iter_rows():
370
+ for cell in row:
371
+ if cell.data_type == "f":
372
+ raise ConflictError(
373
+ f"Formula materialization produced a formula in {path} ({ws.title}!{cell.coordinate})."
374
+ )
375
+ if cell.data_type == "e":
376
+ if not isinstance(cell.value, str) or cell.value not in _ERROR_VALUES:
377
+ raise ConflictError(f"Invalid Excel error at {ws.title}!{cell.coordinate}: {cell.value}")
378
+ if not allow_errors:
379
+ raise ConflictError(
380
+ f"Formula materialization produced an Excel error in {path} ({ws.title}!{cell.coordinate})."
381
+ )
382
+ errors.append({"sheet": ws.title, "coordinate": cell.coordinate, "error": cell.value})
383
+ finally:
384
+ workbook.close()
385
+ return errors
386
+
387
+
388
+ def _materialize_value_snapshot(source_path: Path | str, output_path: Path | str | None, *, allow_errors: bool = False) -> Path:
389
+ """Calculate one complete source workbook and return its literal snapshot.
390
+
391
+ The implementation lives in formula_values.py so Excel/LibreOffice policy is
392
+ kept in one place. This wrapper intentionally validates its contract at the
393
+ boundary: a successful return that still contains formulas is unsafe.
394
+ """
395
+ source = Path(source_path).resolve()
396
+ if output_path is None:
397
+ output_path = source.with_name(f"{source.stem}.values{source.suffix}")
398
+ destination = Path(output_path).resolve()
399
+ destination.parent.mkdir(parents=True, exist_ok=True)
400
+ try:
401
+ from formula_values import materialize_values
402
+ except ImportError as exc:
403
+ raise ConflictError("Formula materialization is unavailable; refusing to compare formula workbooks.") from exc
404
+ try:
405
+ result = materialize_values(source, destination, allow_errors=allow_errors)
406
+ except PreparationCancelled:
407
+ raise
408
+ except Exception as exc:
409
+ raise ConflictError(f"Failed to calculate workbook {source}: {exc}") from exc
410
+ value_path = Path(result) if result is not None else destination
411
+ if not value_path.is_absolute():
412
+ value_path = (destination.parent / value_path).resolve()
413
+ if not value_path.exists():
414
+ raise ConflictError(f"Formula materialization did not produce a workbook for {source}.")
415
+ _validate_value_workbook(value_path, allow_errors=allow_errors)
416
+ return value_path
417
+
418
+
419
+ def _snapshot_workbooks(
420
+ base_path: Path | str | None,
421
+ ours_path: Path | str,
422
+ theirs_path: Path | str,
423
+ analysis_dir: Path,
424
+ ) -> tuple[dict[str, Path | None], dict[str, dict[str, Any]]]:
425
+ """Create and describe immutable value snapshots for all three sides."""
426
+ analysis_dir.mkdir(parents=True, exist_ok=True)
427
+ sources = {"base": Path(base_path).resolve() if base_path else None,
428
+ "ours": Path(ours_path).resolve(), "theirs": Path(theirs_path).resolve()}
429
+ snapshots: dict[str, Path | None] = {}
430
+ metadata: dict[str, dict[str, Any]] = {}
431
+ for side, source in sources.items():
432
+ checkpoint(phase='计算公式并验证', side=side, sheet='', sheetDone=0, sheetTotal=0)
433
+ if source is None:
434
+ snapshots[side] = None
435
+ continue
436
+ source_hash = _sha256_path(source)
437
+ # No-formula workbooks are already valid value snapshots. Avoid a
438
+ # needless package rewrite (and preserve exact zip bytes for safety).
439
+ if _workbook_has_formula(source):
440
+ output = analysis_dir / f"{side}.values{source.suffix.lower()}"
441
+ value_path = _materialize_value_snapshot(source, output, allow_errors=True)
442
+ else:
443
+ value_path = source
444
+ _validate_value_workbook(value_path, allow_errors=True)
445
+ snapshots[side] = value_path
446
+ metadata[side] = {
447
+ "sourcePath": str(source),
448
+ "sourceSha256": source_hash,
449
+ "valuePath": str(value_path),
450
+ "valueSha256": _sha256_path(value_path),
451
+ }
452
+ errors = _validate_value_workbook(value_path, allow_errors=True)
453
+ metadata[side]["errors"] = errors
454
+ if errors:
455
+ source_book = load_workbook(source, data_only=False, keep_links=False)
456
+ try:
457
+ for error in errors:
458
+ error["formula"] = source_book[error["sheet"]][error["coordinate"]].value
459
+ error.update(_repair_field_info(source_book[error['sheet']], error['coordinate']))
460
+ finally:
461
+ source_book.close()
462
+ _replace_common_errors(snapshots, metadata, analysis_dir)
463
+ return snapshots, metadata
464
+
465
+
466
+ def _repair_field_info(ws, coordinate):
467
+ column = ws[coordinate].column
468
+ var = next((r for r in range(1, min(ws.max_row, 40) + 1) if ws.cell(r, 1).value == '##var'), None)
469
+ typ = next((r for r in range(1, min(ws.max_row, 80) + 1) if ws.cell(r, 1).value == '##type'), None)
470
+ if var is None or typ is None:
471
+ return {}
472
+ field = str(ws.cell(var, column).value or '')
473
+ kind = str(ws.cell(typ, column).value or '').strip().casefold()
474
+ info = {'field': field, 'type': kind}
475
+ default = '' if kind == 'string' else False if kind == 'bool' else 0
476
+ try:
477
+ _validate_repair_value(kind, default)
478
+ except ConflictError:
479
+ return info
480
+ guarded = field.casefold().endswith('id') or 'ref' in field.casefold() or any(
481
+ ws.cell(r, 1).value in ('##ref', '##refs', '##key', '##index', '##validator', '##validate', '##validation', '##min', '##max', '##range', '##constraint')
482
+ and ws.cell(r, column).value not in (None, '') for r in range(var, typ + 10))
483
+ if not guarded:
484
+ info['defaultValue'] = default
485
+ return info
486
+
487
+
488
+ def _validate_repair_value(kind, value):
489
+ import math
490
+ if not kind and type(value) in (int, float) and math.isfinite(value):
491
+ return
492
+ if kind == 'string' and isinstance(value, str):
493
+ return
494
+ if kind == 'bool' and isinstance(value, bool):
495
+ return
496
+ if kind in ('float', 'double', 'decimal') and type(value) in (int, float) and math.isfinite(value):
497
+ return
498
+ match = re.fullmatch(r'(u?int)(8|16|32|64)?|(s?byte|u?short|u?long)', kind)
499
+ if match and type(value) is int:
500
+ bits = int(match.group(2) or 32) if match.group(1) else {'byte': 8, 'sbyte': 8, 'short': 16, 'ushort': 16, 'long': 64, 'ulong': 64}[kind]
501
+ unsigned = kind.startswith('u') or kind == 'byte'
502
+ if (0 if unsigned else -(2 ** (bits - 1))) <= value <= 2 ** (bits if unsigned else bits - 1) - 1:
503
+ return
504
+ raise ConflictError(f'修复值不符合声明类型 {kind!r};ID/引用值还需人工核对业务有效性。')
505
+
506
+
507
+ def _selected_repairs(sheet, selection):
508
+ side = selection.get('sheet')
509
+ errors = [e for e in sheet.get('calculationErrors', []) if e['side'] == side]
510
+ values = (selection.get('repairs') or {}).get(side, {})
511
+ if not isinstance(values, dict):
512
+ raise ConflictError('修复值必须按单元格提供。')
513
+ allowed = {e['coordinate']: e for e in errors}
514
+ if set(values) - set(allowed):
515
+ raise ConflictError('修复包含未经审阅的单元格。')
516
+ for coordinate, value in values.items():
517
+ _validate_repair_value(allowed[coordinate].get('type', ''), value)
518
+ for error in errors:
519
+ if error['coordinate'] not in values:
520
+ raise ConflictError(f"请修复所选 {side} 来源的 {sheet['name']}!{error['coordinate']}: {error['error']}")
521
+ return values
522
+
523
+
524
+ def _error_replacement_schema(ws):
525
+ """Only explicit primitive Luban fields with unique, valid IDs qualify."""
526
+ var_row = next((row for row in range(1, min(ws.max_row, 40) + 1)
527
+ if ws.cell(row, 1).value == "##var"), None)
528
+ if var_row is None:
529
+ return None
530
+ type_row = next((row for row in range(var_row + 1, min(ws.max_row, var_row + 40) + 1)
531
+ if ws.cell(row, 1).value == "##type"), None)
532
+ if type_row is None:
533
+ return None
534
+ fields = {}
535
+ duplicates = set()
536
+ for cell in list(ws._cells.values()):
537
+ if cell.row != var_row or cell.column == 1 or not isinstance(cell.value, str) or not cell.value.strip():
538
+ continue
539
+ field = cell.value.strip()
540
+ if field in fields:
541
+ duplicates.add(field)
542
+ fields[field] = cell.column
543
+ fields = {field: column for field, column in fields.items() if field not in duplicates}
544
+ ids = [column for field, column in fields.items() if field.casefold() == "id"]
545
+ if len(ids) != 1:
546
+ return None
547
+ start = var_row
548
+ while start <= ws.max_row and isinstance(ws.cell(start, 1).value, str) and ws.cell(start, 1).value.startswith("##"):
549
+ start += 1
550
+ records, duplicate_ids = {}, set()
551
+ for cell in list(ws._cells.values()):
552
+ if cell.column != ids[0] or cell.row < start:
553
+ continue
554
+ if cell.data_type == "e" or cell.value in (None, "") or not isinstance(cell.value, (str, int, float)) or isinstance(cell.value, bool):
555
+ continue
556
+ key = (cell.data_type, cell.value)
557
+ if key in records:
558
+ duplicate_ids.add(key)
559
+ records[key] = cell.row
560
+ records = {key: row for key, row in records.items() if key not in duplicate_ids}
561
+ defaults = {}
562
+ for field, column in fields.items():
563
+ if not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", field) or field.casefold().endswith("id") or "ref" in field.casefold():
564
+ continue
565
+ if any(ws.cell(row, 1).value in ("##ref", "##refs", "##key", "##index", "##validator", "##validate", "##validation", "##min", "##max", "##range", "##constraint")
566
+ and ws.cell(row, column).value not in (None, "") for row in range(var_row, start)):
567
+ continue
568
+ kind = str(ws.cell(type_row, column).value or "").strip().casefold()
569
+ if kind == "string":
570
+ defaults[field] = (column, kind, "")
571
+ elif kind == "bool":
572
+ defaults[field] = (column, kind, False)
573
+ elif re.fullmatch(r"(?:s?byte|u?short|u?int|u?long|float|double|decimal|u?int(?:8|16|32|64))", kind):
574
+ defaults[field] = (column, kind, 0)
575
+ return records, defaults
576
+
577
+
578
+ def _replace_common_errors(paths, metadata, analysis_dir):
579
+ """Apply authorized defaults only to corresponding errors on both sides.
580
+
581
+ Use declared fields and unique IDs before structural alignment. Never
582
+ guess types from number formats, errors, or adjacent cells, and never
583
+ modify an extracted Git source or the repository working tree.
584
+ """
585
+ if not all(metadata.get(side, {}).get("errors") for side in ("ours", "theirs")):
586
+ return
587
+ from formula_values import _set_literal
588
+ books = {side: load_workbook(paths[side], keep_vba=paths[side].suffix.lower() == ".xlsm")
589
+ for side in ("ours", "theirs")}
590
+ replacements = {side: [] for side in books}
591
+ try:
592
+ errors = {side: {(error["sheet"], error["coordinate"]): error for error in metadata[side]["errors"]}
593
+ for side in books}
594
+ for name in set(books["ours"].sheetnames) & set(books["theirs"].sheetnames):
595
+ schemas = {side: _error_replacement_schema(book[name]) for side, book in books.items()}
596
+ if not all(schemas.values()):
597
+ continue
598
+ ours_rows, ours_fields = schemas["ours"]
599
+ theirs_rows, theirs_fields = schemas["theirs"]
600
+ by_row = {row: key for key, row in ours_rows.items()}
601
+ by_column = {info[0]: field for field, info in ours_fields.items()}
602
+ for error in metadata["ours"]["errors"]:
603
+ if error["sheet"] != name:
604
+ continue
605
+ own = books["ours"][name][error["coordinate"]]
606
+ key, field = by_row.get(own.row), by_column.get(own.column)
607
+ if key not in theirs_rows or field not in theirs_fields or ours_fields[field][1] != theirs_fields[field][1]:
608
+ continue
609
+ cells = {"ours": own, "theirs": books["theirs"][name].cell(theirs_rows[key], theirs_fields[field][0])}
610
+ if not all(cell.data_type == "e" for cell in cells.values()):
611
+ continue
612
+ kind, value = ours_fields[field][1:]
613
+ for side, cell in cells.items():
614
+ issue = errors[side][(name, cell.coordinate)]
615
+ replacements[side].append({**issue, "field": field, "recordId": key[1], "type": kind, "value": value})
616
+ _set_literal(cell, value)
617
+ for side, repairs in replacements.items():
618
+ if not repairs:
619
+ continue
620
+ output = analysis_dir / f"{side}.review.values{paths[side].suffix}"
621
+ books[side].save(output)
622
+ paths[side] = output
623
+ removed = {(repair["sheet"], repair["coordinate"]) for repair in repairs}
624
+ metadata[side].update(valuePath=str(output), valueSha256=_sha256_path(output), replacements=repairs,
625
+ errors=[error for error in metadata[side]["errors"] if (error["sheet"], error["coordinate"]) not in removed])
626
+ finally:
627
+ for book in books.values():
628
+ book.close()
629
+
630
+
631
+ def _cell_token(cell, cached_cell=None) -> tuple[Any, str] | None:
632
+ if cell is None or isinstance(cell, MergedCell):
633
+ return None
634
+ # 公式 cell 按缓存值参与比较,避免公式不变但引用值变了被误判为 same
635
+ if cell.data_type == 'f' and cached_cell is not None and not isinstance(cached_cell, MergedCell):
636
+ return cached_cell.value, cached_cell.data_type
637
+ return cell.value, cell.data_type
638
+
639
+
640
+ def _cell_display_value(cell, cached_cell) -> Any:
641
+ """UI 展示值:公式 cell 取缓存值,其余取原始值。"""
642
+ if cell is None or isinstance(cell, MergedCell):
643
+ return None
644
+ if cell.data_type == 'f' and cached_cell is not None and not isinstance(cached_cell, MergedCell):
645
+ return cached_cell.value
646
+ return cell.value
647
+
648
+
649
+ def _value_cells(ws) -> dict[tuple[int, int], Any]:
650
+ if ws is None:
651
+ return {}
652
+ result = {}
653
+ for key, cell in ws._cells.items():
654
+ if isinstance(cell, MergedCell):
655
+ continue
656
+ if cell.value is not None:
657
+ result[key] = cell
658
+ return result
659
+
660
+
661
+ def _sheet_values(ws) -> dict[tuple[int, int], tuple[Any, str] | None]:
662
+ return {key: _cell_token(cell) for key, cell in _value_cells(ws).items()}
663
+
664
+
665
+ def _sheet_equal(left, right) -> bool:
666
+ return _sheet_values(left) == _sheet_values(right)
667
+
668
+
669
+ def _ordered_sheet_names(*workbooks) -> list[str]:
670
+ names: list[str] = []
671
+ for workbook in workbooks:
672
+ if workbook is None:
673
+ continue
674
+ for name in workbook.sheetnames:
675
+ if name not in names:
676
+ names.append(name)
677
+ return names
678
+
679
+
680
+ def _context_rows(ws, ws_v, rows: set[int], max_col: int) -> dict[str, list[Any]]:
681
+ if ws is None or max_col <= 0:
682
+ return {}
683
+ header_rows: set[int] = set()
684
+ for row in range(1, min(max(ws.max_row or 1, 1), 20) + 1):
685
+ value = ws.cell(row, 1).value
686
+ if isinstance(value, str) and value.startswith("##"):
687
+ header_rows.add(row)
688
+ elif header_rows:
689
+ break
690
+ wanted = sorted(rows | header_rows)
691
+ return {
692
+ str(row): [_json_value(_cell_display_value(
693
+ ws.cell(row, col),
694
+ ws_v.cell(row, col) if ws_v is not None else None
695
+ )) for col in range(1, max_col + 1)]
696
+ for row in wanted
697
+ }
698
+
699
+
700
+ def _modified_sheet_diff(name, ws_base, ws_ours, ws_theirs,
701
+ ws_base_v=None, ws_ours_v=None, ws_theirs_v=None) -> dict[str, Any]:
702
+ base_cells = _value_cells(ws_base)
703
+ ours_cells = _value_cells(ws_ours)
704
+ theirs_cells = _value_cells(ws_theirs)
705
+ coordinates = sorted(set(base_cells) | set(ours_cells) | set(theirs_cells))
706
+ cells: list[dict[str, Any]] = []
707
+ changed_rows: set[int] = set()
708
+
709
+ for row, col in coordinates:
710
+ base_cell = base_cells.get((row, col))
711
+ ours_cell = ours_cells.get((row, col))
712
+ theirs_cell = theirs_cells.get((row, col))
713
+ base_cached = ws_base_v.cell(row, col) if ws_base_v is not None else None
714
+ ours_cached = ws_ours_v.cell(row, col) if ws_ours_v is not None else None
715
+ theirs_cached = ws_theirs_v.cell(row, col) if ws_theirs_v is not None else None
716
+ base_token = _cell_token(base_cell, base_cached)
717
+ ours_token = _cell_token(ours_cell, ours_cached)
718
+ theirs_token = _cell_token(theirs_cell, theirs_cached)
719
+ if ours_token == theirs_token:
720
+ continue
721
+ if ours_token == base_token:
722
+ resolution = "theirs"
723
+ elif theirs_token == base_token:
724
+ resolution = "ours"
725
+ else:
726
+ resolution = "conflict"
727
+ changed_rows.add(row)
728
+ cells.append({
729
+ "row": row,
730
+ "col": col,
731
+ "coordinate": f"{get_column_letter(col)}{row}",
732
+ "base": _json_value(_cell_display_value(base_cell, base_cached)),
733
+ "ours": _json_value(_cell_display_value(ours_cell, ours_cached)),
734
+ "theirs": _json_value(_cell_display_value(theirs_cell, theirs_cached)),
735
+ "resolution": resolution,
736
+ })
737
+
738
+ preferred_ws = ws_ours or ws_theirs or ws_base
739
+ preferred_ws_v = ws_ours_v or ws_theirs_v or ws_base_v
740
+ max_col = max([col for _, col in coordinates] or [1])
741
+ return {
742
+ "name": name,
743
+ "action": "merge",
744
+ "cells": cells,
745
+ "contextRows": _context_rows(preferred_ws, preferred_ws_v, changed_rows, max_col),
746
+ "maxCol": max_col,
747
+ "changedCount": len(cells),
748
+ "conflictCount": sum(cell["resolution"] == "conflict" for cell in cells),
749
+ }
750
+
751
+
752
+ def _axis_state(status: str, *, ours_present: bool) -> dict[str, Any]:
753
+ if status.startswith("added_"):
754
+ return {
755
+ "state": "added",
756
+ "locked": True,
757
+ "incoming": status == "added_theirs",
758
+ "default": "keep",
759
+ }
760
+ if status.startswith("delete_modify_"):
761
+ return {
762
+ "state": "delete_modify",
763
+ "locked": False,
764
+ "incoming": False,
765
+ "default": "keep" if ours_present else "delete",
766
+ }
767
+ if status.startswith("deleted_"):
768
+ return {
769
+ "state": "deleted",
770
+ "locked": True,
771
+ "incoming": False,
772
+ "default": "delete",
773
+ }
774
+ return {"state": "common", "locked": False, "incoming": False, "default": "keep"}
775
+
776
+
777
+ def _side_cell(workbook, sheet_name: str | None, row: int | None, column: int | None):
778
+ if workbook is None or sheet_name is None or row is None or column is None:
779
+ return None
780
+ return workbook[sheet_name].cell(row, column)
781
+
782
+
783
+ def _cell_resolution(base_cell, ours_cell, theirs_cell, *, has_base: bool,
784
+ base_cached=None, ours_cached=None, theirs_cached=None) -> str:
785
+ base_token = _cell_token(base_cell, base_cached)
786
+ ours_token = _cell_token(ours_cell, ours_cached)
787
+ theirs_token = _cell_token(theirs_cell, theirs_cached)
788
+ if not has_base:
789
+ return "theirs" if theirs_cell is not None else "ours"
790
+ if ours_token == theirs_token:
791
+ return "same"
792
+ if ours_token == base_token:
793
+ return "theirs"
794
+ if theirs_token == base_token:
795
+ return "ours"
796
+ return "conflict"
797
+
798
+
799
+ def _header_rows(ws) -> list[int]:
800
+ if ws is None:
801
+ return []
802
+ rows = []
803
+ for row in range(1, min(ws.max_row or 0, 40) + 1):
804
+ marker = ws.cell(row, 1).value
805
+ if isinstance(marker, str) and marker.startswith("##"):
806
+ rows.append(row)
807
+ elif rows:
808
+ break
809
+ return rows
810
+
811
+
812
+ def _merged_region_key(region: dict[str, Any]) -> tuple[tuple[str, ...], tuple[str, ...]]:
813
+ return tuple(region["rows"]), tuple(region["columns"])
814
+
815
+
816
+ def _canonical_merged_regions(ws, side: str, rows, columns) -> list[dict[str, Any]]:
817
+ if ws is None:
818
+ return []
819
+ header_rows = set(_header_rows(ws))
820
+ row_lookup = {
821
+ row.get(f"{side}Row"): row["id"]
822
+ for row in rows
823
+ if row.get(f"{side}Row") is not None
824
+ }
825
+ column_lookup = {
826
+ column.get(f"{side}Col"): column["id"]
827
+ for column in columns
828
+ if column.get(f"{side}Col") is not None
829
+ }
830
+ regions = []
831
+ for merged_range in ws.merged_cells.ranges:
832
+ row_ids = []
833
+ for row_number in range(merged_range.min_row, merged_range.max_row + 1):
834
+ row_id = f"header:{row_number}" if row_number in header_rows else row_lookup.get(row_number)
835
+ if row_id is None:
836
+ break
837
+ row_ids.append(row_id)
838
+ else:
839
+ column_ids = []
840
+ for column_number in range(merged_range.min_col, merged_range.max_col + 1):
841
+ column_id = column_lookup.get(column_number)
842
+ if column_id is None:
843
+ break
844
+ column_ids.append(column_id)
845
+ else:
846
+ regions.append({"rows": row_ids, "columns": column_ids})
847
+ return sorted(regions, key=_merged_region_key)
848
+
849
+
850
+ def _regions_overlap(regions: list[dict[str, Any]]) -> bool:
851
+ occupied: set[tuple[str, str]] = set()
852
+ for region in regions:
853
+ cells = {(row, column) for row in region["rows"] for column in region["columns"]}
854
+ if occupied & cells:
855
+ return True
856
+ occupied.update(cells)
857
+ return False
858
+
859
+
860
+ def _merged_cells_diff(names, rows, columns, wb_base, wb_ours, wb_theirs) -> dict[str, Any]:
861
+ workbooks = {"base": wb_base, "ours": wb_ours, "theirs": wb_theirs}
862
+ regions = {}
863
+ for side, workbook in workbooks.items():
864
+ sheet_name = names.get(side)
865
+ ws = workbook[sheet_name] if workbook is not None and sheet_name in workbook.sheetnames else None
866
+ regions[side] = _canonical_merged_regions(ws, side, rows, columns)
867
+
868
+ keyed = {side: {_merged_region_key(item): item for item in items} for side, items in regions.items()}
869
+ base_keys, ours_keys, theirs_keys = (set(keyed[side]) for side in ("base", "ours", "theirs"))
870
+ if ours_keys == theirs_keys:
871
+ status, resolved = "same", regions["ours"]
872
+ elif ours_keys == base_keys:
873
+ status, resolved = "auto_theirs", regions["theirs"]
874
+ elif theirs_keys == base_keys:
875
+ status, resolved = "auto_ours", regions["ours"]
876
+ else:
877
+ all_keys = base_keys | ours_keys | theirs_keys
878
+ resolved_keys = set()
879
+ for key in all_keys:
880
+ base_present = key in base_keys
881
+ ours_present = key in ours_keys
882
+ theirs_present = key in theirs_keys
883
+ if ours_present == theirs_present:
884
+ keep = ours_present
885
+ elif ours_present == base_present:
886
+ keep = theirs_present
887
+ else:
888
+ keep = ours_present
889
+ if keep:
890
+ resolved_keys.add(key)
891
+ source_items = {**keyed["base"], **keyed["ours"], **keyed["theirs"]}
892
+ candidate = [source_items[key] for key in sorted(resolved_keys)]
893
+ if _regions_overlap(candidate):
894
+ status, resolved = "conflict", []
895
+ else:
896
+ status, resolved = "auto_merge", candidate
897
+ return {
898
+ "status": status,
899
+ "default": "ours" if status == "conflict" else None,
900
+ "base": regions["base"],
901
+ "ours": regions["ours"],
902
+ "theirs": regions["theirs"],
903
+ "resolved": resolved,
904
+ }
905
+
906
+
907
+ def _structural_sheet_diff(report_sheet, wb_base, wb_ours, wb_theirs,
908
+ wb_base_v=None, wb_ours_v=None, wb_theirs_v=None) -> dict[str, Any]:
909
+ names = report_sheet.get("names") or {
910
+ "base": report_sheet["name"], "ours": report_sheet["name"], "theirs": report_sheet["name"]
911
+ }
912
+ rows = []
913
+ for index, entry in enumerate(report_sheet.get("rowAlignment") or [], 1):
914
+ item = dict(entry)
915
+ item.update(_axis_state(entry["status"], ours_present=entry.get("oursRow") is not None))
916
+ item["display"] = entry.get("oursRow") or entry.get("baseRow") or entry.get("theirsRow") or index
917
+ rows.append(item)
918
+ columns = []
919
+ for index, entry in enumerate(report_sheet.get("columnAlignment") or [], 1):
920
+ item = dict(entry)
921
+ item["id"] = entry["field"]
922
+ item.update(_axis_state(entry["status"], ours_present=entry.get("oursColumn") is not None))
923
+ item["baseCol"] = column_index_from_string(entry["baseColumn"]) if entry.get("baseColumn") else None
924
+ item["oursCol"] = column_index_from_string(entry["oursColumn"]) if entry.get("oursColumn") else None
925
+ item["theirsCol"] = column_index_from_string(entry["theirsColumn"]) if entry.get("theirsColumn") else None
926
+ item["display"] = entry.get("oursColumn") or entry.get("baseColumn") or entry.get("theirsColumn") or get_column_letter(index)
927
+ columns.append(item)
928
+
929
+ all_cells: list[dict[str, Any]] = []
930
+ changed_row_ids: set[str] = set()
931
+ row_attention: set[str] = set()
932
+ for row in rows:
933
+ for column in columns:
934
+ base_cell = _side_cell(wb_base, names.get("base"), row.get("baseRow"), column.get("baseCol"))
935
+ ours_cell = _side_cell(wb_ours, names.get("ours"), row.get("oursRow"), column.get("oursCol"))
936
+ theirs_cell = _side_cell(wb_theirs, names.get("theirs"), row.get("theirsRow"), column.get("theirsCol"))
937
+ base_cached = _side_cell(wb_base_v, names.get("base"), row.get("baseRow"), column.get("baseCol")) if wb_base_v else None
938
+ ours_cached = _side_cell(wb_ours_v, names.get("ours"), row.get("oursRow"), column.get("oursCol")) if wb_ours_v else None
939
+ theirs_cached = _side_cell(wb_theirs_v, names.get("theirs"), row.get("theirsRow"), column.get("theirsCol")) if wb_theirs_v else None
940
+ base_token = _cell_token(base_cell, base_cached)
941
+ ours_token = _cell_token(ours_cell, ours_cached)
942
+ theirs_token = _cell_token(theirs_cell, theirs_cached)
943
+ has_base = row.get("baseRow") is not None and column.get("baseCol") is not None
944
+ error_sides = {side: cell.value for side, cell in
945
+ (("base", base_cell), ("ours", ours_cell), ("theirs", theirs_cell))
946
+ if cell is not None and cell.data_type == "e"}
947
+ changed = bool(error_sides) or not (ours_token == theirs_token == base_token)
948
+ structural = row["state"] != "common" or column["state"] != "common"
949
+ selectable = (
950
+ row["state"] in ("common", "delete_modify")
951
+ and column["state"] in ("common", "delete_modify")
952
+ )
953
+ if changed or structural:
954
+ changed_row_ids.add(row["id"])
955
+ resolution = _cell_resolution(base_cell, ours_cell, theirs_cell, has_base=has_base,
956
+ base_cached=base_cached, ours_cached=ours_cached, theirs_cached=theirs_cached)
957
+ if error_sides:
958
+ resolution = "conflict"
959
+ if changed and resolution != "same":
960
+ row_attention.add(row["id"])
961
+ stable_id = f'{row["id"]}|{column["id"]}'
962
+ display_coordinate = (
963
+ f'{get_column_letter(column["oursCol"])}{row["oursRow"]}'
964
+ if row.get("oursRow") is not None and column.get("oursCol") is not None
965
+ else stable_id
966
+ )
967
+ all_cells.append({
968
+ "id": stable_id,
969
+ "coordinate": display_coordinate,
970
+ "rowId": row["id"],
971
+ "colId": column["id"],
972
+ "base": _json_value(_cell_display_value(base_cell, base_cached)),
973
+ "ours": _json_value(_cell_display_value(ours_cell, ours_cached)),
974
+ "theirs": _json_value(_cell_display_value(theirs_cell, theirs_cached)),
975
+ "basePresent": base_cell is not None,
976
+ "oursPresent": ours_cell is not None,
977
+ "theirsPresent": theirs_cell is not None,
978
+ "resolution": resolution,
979
+ "changed": changed,
980
+ "structural": structural,
981
+ "selectable": selectable,
982
+ "requiresChoice": bool(error_sides),
983
+ "errorSides": error_sides,
984
+ })
985
+
986
+ # 只显示需要关注的行:结构变化行 + 含非 same(需决策/有变化信息)cell 的行
987
+ visible_rows = [
988
+ row for row in rows
989
+ if row["state"] != "common" or row["id"] in row_attention
990
+ ]
991
+ visible_ids = {row["id"] for row in visible_rows}
992
+ grid_cells = [cell for cell in all_cells if cell["rowId"] in visible_ids]
993
+ cells = [cell for cell in grid_cells if cell["changed"]]
994
+ decision_cell_count = sum(cell["changed"] and cell["selectable"] for cell in cells)
995
+ preferred_ws = None
996
+ for workbook, key in ((wb_ours, "ours"), (wb_theirs, "theirs"), (wb_base, "base")):
997
+ if workbook is not None and names.get(key) in workbook.sheetnames:
998
+ preferred_ws = workbook[names[key]]
999
+ break
1000
+ header_rows = []
1001
+ for row_number in _header_rows(preferred_ws):
1002
+ header_rows.append({
1003
+ "row": row_number,
1004
+ "cells": [
1005
+ _json_value(preferred_ws.cell(row_number, column.get("oursCol") or column.get("theirsCol") or column.get("baseCol")).value)
1006
+ for column in columns
1007
+ ],
1008
+ })
1009
+ merged_cells = _merged_cells_diff(names, rows, columns, wb_base, wb_ours, wb_theirs)
1010
+ merged_cells_conflict = merged_cells["status"] == "conflict"
1011
+ structural_conflicts = (
1012
+ sum(axis["state"] == "delete_modify" for axis in [*rows, *columns])
1013
+ + int(merged_cells_conflict)
1014
+ )
1015
+ rebuild_required = (
1016
+ any(axis["state"] != "common" for axis in [*rows, *columns])
1017
+ or any(cell["changed"] for cell in all_cells)
1018
+ or merged_cells["status"] != "same"
1019
+ )
1020
+ selectable_cells = [
1021
+ cell for cell in cells
1022
+ if cell["changed"] and cell["resolution"] == "conflict"
1023
+ and next(row for row in rows if row["id"] == cell["rowId"])["state"] == "common"
1024
+ and next(column for column in columns if column["id"] == cell["colId"])["state"] == "common"
1025
+ ]
1026
+ return {
1027
+ "name": report_sheet["name"],
1028
+ "names": names,
1029
+ "renameStatus": report_sheet.get("renameStatus", "unchanged"),
1030
+ "action": "merge",
1031
+ "rows": visible_rows,
1032
+ "allRows": rows,
1033
+ "columns": columns,
1034
+ "cells": cells,
1035
+ "gridCells": grid_cells,
1036
+ "allCells": all_cells,
1037
+ "headerRows": header_rows,
1038
+ "mergedCells": merged_cells,
1039
+ "rebuildRequired": rebuild_required,
1040
+ "maxCol": len(columns),
1041
+ "changedCount": decision_cell_count,
1042
+ "decisionCellCount": decision_cell_count,
1043
+ "rawChangedCellCount": sum(cell["changed"] for cell in cells),
1044
+ "conflictCount": len(selectable_cells),
1045
+ "structuralConflictCount": structural_conflicts,
1046
+ "needsAttention": decision_cell_count > 0 or structural_conflicts > 0
1047
+ or report_sheet.get("renameStatus") == "rename_conflict",
1048
+ }
1049
+
1050
+
1051
+ def _require_error_review(sheet: dict[str, Any], snapshots: dict[str, Any]) -> None:
1052
+ """Unknown values may never justify alignment or automatic resolution."""
1053
+ names = sheet.get("names") or {side: sheet["name"] for side in ("base", "ours", "theirs")}
1054
+ relevant = [{**error, "side": side} for side, meta in snapshots.items()
1055
+ for error in meta.get("errors", []) if error["sheet"] == names.get(side)]
1056
+ repairs = [{**repair, "side": side} for side, meta in snapshots.items()
1057
+ for repair in meta.get("replacements", []) if repair["sheet"] == names.get(side)]
1058
+ if repairs:
1059
+ sheet.update(replacements=repairs, needsAttention=True, rebuildRequired=True)
1060
+ lookup = {(repair["side"], repair["coordinate"]): repair for repair in repairs}
1061
+ rows = {row["id"]: row for row in sheet.get("allRows", [])}
1062
+ columns = {column["id"]: column for column in sheet.get("columns", [])}
1063
+ corrected_rows, excluded = set(), set()
1064
+ for cell in sheet.get("allCells", []):
1065
+ row, column = rows[cell["rowId"]], columns[cell["colId"]]
1066
+ pair = {}
1067
+ for side in ("ours", "theirs"):
1068
+ if row.get(f"{side}Row") is not None and column.get(f"{side}Col") is not None:
1069
+ coordinate = f'{get_column_letter(column[f"{side}Col"])}{row[f"{side}Row"]}'
1070
+ if (side, coordinate) in lookup:
1071
+ pair[side] = lookup[(side, coordinate)]
1072
+ if len(pair) != 2 or pair["ours"]["recordId"] != pair["theirs"]["recordId"] or pair["ours"]["field"] != pair["theirs"]["field"]:
1073
+ continue
1074
+ cell.update(replacement=pair, requiresChoice=False, selectable=False, resolution="replacement", changed=True)
1075
+ corrected_rows.add(row["id"])
1076
+ if row.get("baseRow") is not None and column.get("baseCol") is not None:
1077
+ excluded.add(("base", f'{get_column_letter(column["baseCol"])}{row["baseRow"]}'))
1078
+ relevant = [error for error in relevant if (error["side"], error["coordinate"]) not in excluded]
1079
+ visible = {row["id"] for row in sheet.get("rows", [])} | corrected_rows
1080
+ sheet["rows"] = [row for row in sheet.get("allRows", []) if row["id"] in visible]
1081
+ sheet["gridCells"] = [cell for cell in sheet.get("allCells", []) if cell["rowId"] in visible]
1082
+ sheet["cells"] = [cell for cell in sheet["gridCells"] if cell["changed"]]
1083
+ sheet["changedCount"] = sheet["decisionCellCount"] = sum(cell["selectable"] for cell in sheet["cells"])
1084
+ sheet["conflictCount"] = sum(cell["resolution"] == "conflict" for cell in sheet["cells"])
1085
+ if not relevant:
1086
+ return
1087
+ sheet["calculationErrors"] = relevant
1088
+ sheet["needsAttention"] = True
1089
+ if sheet["action"] == "merge":
1090
+ represented = sum(len(cell.get("errorSides", {})) for cell in sheet.get("allCells", []) if cell.get("requiresChoice"))
1091
+ structural = any(axis["state"] != "common"
1092
+ for axis in [*sheet.get("allRows", []), *sheet.get("columns", [])])
1093
+ id_columns = [column for column in sheet.get("columns", []) if column["id"].casefold() == "id"]
1094
+ identity_cells = [cell for cell in sheet.get("allCells", [])
1095
+ if id_columns and cell["colId"] == id_columns[0]["id"]]
1096
+ uncertain_rows = {cell["rowId"] for cell in sheet.get("allCells", []) if cell.get("requiresChoice")}
1097
+ reliable = bool(id_columns) and all(
1098
+ any(cell["rowId"] == row_id and not cell.get("requiresChoice")
1099
+ and cell["base"] is not None and cell["base"] == cell["ours"] == cell["theirs"]
1100
+ and all(sum(other[side] == cell[side] for other in identity_cells) == 1
1101
+ for side in ("base", "ours", "theirs")) for cell in identity_cells)
1102
+ for row_id in uncertain_rows
1103
+ )
1104
+ if not structural and represented == len(relevant) and reliable:
1105
+ by_coordinate = {(error["side"], error["coordinate"]): error for error in relevant}
1106
+ rows = {row["id"]: row for row in sheet["allRows"]}
1107
+ columns = {column["id"]: column for column in sheet["columns"]}
1108
+ for cell in sheet["allCells"]:
1109
+ if cell.get("requiresChoice"):
1110
+ cell["calculationErrors"] = {}
1111
+ for side in cell["errorSides"]:
1112
+ coordinate = f'{get_column_letter(columns[cell["colId"]][f"{side}Col"])}{rows[cell["rowId"]][f"{side}Row"]}'
1113
+ cell["calculationErrors"][side] = by_coordinate[(side, coordinate)]
1114
+ return
1115
+ # Errors in headers, unmatched/deleted rows, or changing axes undermine
1116
+ # structural evidence. Require a whole-sheet choice instead of guessing
1117
+ # row/column correspondence or interpreting an unknown as "unchanged".
1118
+ sheet.update(action="conflict_calculation_errors", requiresChoice=True,
1119
+ cells=[], gridCells=[], allCells=[], rows=[], allRows=[], columns=[],
1120
+ headerRows=[], changedCount=0, conflictCount=0,
1121
+ structuralConflictCount=1, renameStatus="unchanged", mergedCells=None)
1122
+
1123
+
1124
+ def diff_workbooks(
1125
+ base_path: Path | str | None,
1126
+ ours_path: Path | str,
1127
+ theirs_path: Path | str,
1128
+ *,
1129
+ analysis_dir: Path | str | None = None,
1130
+ skip_hidden_sheets: bool = True,
1131
+ ) -> dict[str, Any]:
1132
+ structural_dir = Path(analysis_dir) if analysis_dir else Path(tempfile.mkdtemp(prefix="xlsx-merge-analysis-"))
1133
+ snapshot_paths, value_snapshots = _snapshot_workbooks(
1134
+ base_path, ours_path, theirs_path, structural_dir,
1135
+ )
1136
+ # These workbooks are complete, calculated snapshots with typed errors
1137
+ # represented as unknowns requiring review. Keeping the
1138
+ # three sides separate is important for cross-sheet formulas: each side is
1139
+ # calculated against its own original workbook before alignment/merge.
1140
+ wb_base = load_workbook(snapshot_paths["base"], data_only=False, keep_links=True) if snapshot_paths["base"] else None
1141
+ wb_ours = load_workbook(snapshot_paths["ours"], data_only=False, keep_links=True)
1142
+ wb_theirs = load_workbook(snapshot_paths["theirs"], data_only=False, keep_links=True)
1143
+ wb_base_v = wb_ours_v = wb_theirs_v = None
1144
+ try:
1145
+ if any(meta.get("errors") or meta.get("replacements") for meta in value_snapshots.values()):
1146
+ skip_hidden_sheets = False
1147
+ if base_path is not None:
1148
+ structural = analyze_structural_workbooks(
1149
+ snapshot_paths["base"], snapshot_paths["ours"], snapshot_paths["theirs"], structural_dir,
1150
+ write_sidecars=False, skip_hidden_sheets=skip_hidden_sheets,
1151
+ progress=lambda **p: checkpoint(phase='对齐 Sheet / 行 / 列', **p),
1152
+ )
1153
+ sheets = []
1154
+ for index, report_sheet in enumerate(structural["sheets"]):
1155
+ checkpoint(phase='生成审阅数据', sheet=report_sheet['name'], sheetDone=index, sheetTotal=len(structural['sheets']))
1156
+ if report_sheet["action"] == "merge":
1157
+ sheets.append(_structural_sheet_diff(
1158
+ report_sheet, wb_base, wb_ours, wb_theirs,
1159
+ wb_base_v, wb_ours_v, wb_theirs_v,
1160
+ ))
1161
+ continue
1162
+ names = report_sheet.get("names") or {}
1163
+ if not names.get("base"):
1164
+ if names.get("ours") and names.get("theirs"):
1165
+ action = "auto_add_theirs"
1166
+ else:
1167
+ action = "auto_add_ours" if names.get("ours") else "auto_add_theirs"
1168
+ elif report_sheet.get("status") == "conflict":
1169
+ conflict_kind = (report_sheet.get("sheetConflict") or {}).get("kind", "")
1170
+ if conflict_kind.startswith("delete_modify_"):
1171
+ action = f'conflict_delete_{conflict_kind.rsplit("_", 1)[-1]}'
1172
+ else:
1173
+ action = "conflict_sheet_structure"
1174
+ else:
1175
+ action = "auto_delete"
1176
+ sheets.append({
1177
+ "name": report_sheet["name"],
1178
+ "names": names,
1179
+ "renameStatus": report_sheet.get("renameStatus", "unchanged"),
1180
+ "action": action,
1181
+ "sheetConflict": report_sheet.get("sheetConflict"),
1182
+ "cells": [],
1183
+ "rows": [],
1184
+ "allRows": [],
1185
+ "columns": [],
1186
+ "headerRows": [],
1187
+ "maxCol": 0,
1188
+ "changedCount": 0,
1189
+ "conflictCount": 0,
1190
+ "structuralConflictCount": int(action.startswith("conflict_")),
1191
+ "needsAttention": action.startswith("conflict_"),
1192
+ })
1193
+ for sheet in sheets:
1194
+ _require_error_review(sheet, value_snapshots)
1195
+ return {
1196
+ "engineVersion": structural["version"],
1197
+ "valueSnapshots": value_snapshots,
1198
+ "sheets": sheets,
1199
+ "summary": {
1200
+ "sheetCount": len(sheets),
1201
+ "changedCellCount": sum(sheet["changedCount"] for sheet in sheets),
1202
+ "cellConflictCount": sum(sheet["conflictCount"] for sheet in sheets),
1203
+ "structuralConflictCount": sum(sheet.get("structuralConflictCount", 0) for sheet in sheets),
1204
+ "sheetConflictCount": sum(sheet["action"].startswith("conflict_") for sheet in sheets),
1205
+ },
1206
+ }
1207
+
1208
+ sheets: list[dict[str, Any]] = []
1209
+ ordered_names = _ordered_sheet_names(wb_base, wb_ours, wb_theirs)
1210
+ for index, name in enumerate(ordered_names):
1211
+ checkpoint(phase='生成审阅数据', sheet=name, sheetDone=index, sheetTotal=len(ordered_names))
1212
+ base_exists = wb_base is not None and name in wb_base.sheetnames
1213
+ ours_exists = name in wb_ours.sheetnames
1214
+ theirs_exists = name in wb_theirs.sheetnames
1215
+ ws_base = wb_base[name] if base_exists else None
1216
+ ws_ours = wb_ours[name] if ours_exists else None
1217
+ ws_theirs = wb_theirs[name] if theirs_exists else None
1218
+ ws_base_v = wb_base_v[name] if base_exists and wb_base_v is not None else None
1219
+ ws_ours_v = wb_ours_v[name] if ours_exists and wb_ours_v is not None else None
1220
+ ws_theirs_v = wb_theirs_v[name] if theirs_exists and wb_theirs_v is not None else None
1221
+
1222
+ if ours_exists and theirs_exists:
1223
+ sheet = _modified_sheet_diff(name, ws_base, ws_ours, ws_theirs,
1224
+ ws_base_v, ws_ours_v, ws_theirs_v)
1225
+ if sheet["changedCount"]:
1226
+ sheets.append(sheet)
1227
+ continue
1228
+ if not base_exists:
1229
+ source = "ours" if ours_exists else "theirs"
1230
+ sheets.append({
1231
+ "name": name,
1232
+ "action": f"auto_add_{source}",
1233
+ "cells": [],
1234
+ "contextRows": {},
1235
+ "maxCol": 0,
1236
+ "changedCount": 0,
1237
+ "conflictCount": 0,
1238
+ })
1239
+ continue
1240
+ if not ours_exists and not theirs_exists:
1241
+ sheets.append({
1242
+ "name": name,
1243
+ "action": "auto_delete",
1244
+ "cells": [],
1245
+ "contextRows": {},
1246
+ "maxCol": 0,
1247
+ "changedCount": 0,
1248
+ "conflictCount": 0,
1249
+ })
1250
+ continue
1251
+
1252
+ existing_ws = ws_ours or ws_theirs
1253
+ missing_side = "theirs" if ours_exists else "ours"
1254
+ if _sheet_equal(ws_base, existing_ws):
1255
+ action = "auto_delete"
1256
+ conflict_count = 0
1257
+ else:
1258
+ action = f"conflict_delete_{missing_side}"
1259
+ conflict_count = 1
1260
+ sheets.append({
1261
+ "name": name,
1262
+ "action": action,
1263
+ "cells": [],
1264
+ "contextRows": {},
1265
+ "maxCol": 0,
1266
+ "changedCount": 0,
1267
+ "conflictCount": conflict_count,
1268
+ })
1269
+
1270
+ for sheet in sheets:
1271
+ _require_error_review(sheet, value_snapshots)
1272
+ return {
1273
+ "valueSnapshots": value_snapshots,
1274
+ "sheets": sheets,
1275
+ "summary": {
1276
+ "sheetCount": len(sheets),
1277
+ "changedCellCount": sum(sheet["changedCount"] for sheet in sheets),
1278
+ "cellConflictCount": sum(
1279
+ sum(cell["resolution"] == "conflict" for cell in sheet["cells"])
1280
+ for sheet in sheets
1281
+ ),
1282
+ "sheetConflictCount": sum(sheet["action"].startswith("conflict_") for sheet in sheets),
1283
+ },
1284
+ }
1285
+ finally:
1286
+ if wb_base is not None:
1287
+ wb_base.close()
1288
+ wb_ours.close()
1289
+ wb_theirs.close()
1290
+ if wb_base_v is not None:
1291
+ wb_base_v.close()
1292
+ if wb_ours_v is not None:
1293
+ wb_ours_v.close()
1294
+ if wb_theirs_v is not None:
1295
+ wb_theirs_v.close()
1296
+
1297
+
1298
+ def _author_and_date(repo: Path, relative_path: str, ref: str) -> tuple[str, str]:
1299
+ verify = _run_git(repo, ["rev-parse", "--verify", "--quiet", ref])
1300
+ if verify.returncode != 0:
1301
+ return "", ""
1302
+ result = _run_git(repo, ["log", "-1", "--format=%an|%cI", ref, "--", relative_path])
1303
+ if result.returncode != 0 or not result.stdout.strip():
1304
+ return "", ""
1305
+ parts = result.stdout.strip().split("|", 1)
1306
+ if len(parts) != 2:
1307
+ return parts[0], ""
1308
+ author, iso_date = parts
1309
+ # ISO 8601 -> "2000-1-1 8:24"
1310
+ try:
1311
+ from datetime import datetime
1312
+ dt = datetime.fromisoformat(iso_date)
1313
+ date_str = f"{dt.year}-{dt.month}-{dt.day} {dt.hour}:{dt.minute:02d}"
1314
+ except (ValueError, TypeError):
1315
+ date_str = ""
1316
+ return author, date_str
1317
+
1318
+
1319
+ def _author(repo: Path, relative_path: str, ref: str) -> str:
1320
+ author, _ = _author_and_date(repo, relative_path, ref)
1321
+ return author
1322
+
1323
+
1324
+ def _theirs_author(repo: Path, relative_path: str) -> str:
1325
+ for ref in ("MERGE_HEAD", "CHERRY_PICK_HEAD", "REBASE_HEAD"):
1326
+ author = _author(repo, relative_path, ref)
1327
+ if author:
1328
+ return author
1329
+ return ""
1330
+
1331
+
1332
+ def _ours_date(repo: Path, relative_path: str) -> str:
1333
+ _, date_str = _author_and_date(repo, relative_path, "HEAD")
1334
+ return date_str
1335
+
1336
+
1337
+ def _theirs_date(repo: Path, relative_path: str) -> str:
1338
+ for ref in ("MERGE_HEAD", "CHERRY_PICK_HEAD", "REBASE_HEAD"):
1339
+ _, date_str = _author_and_date(repo, relative_path, ref)
1340
+ if date_str:
1341
+ return date_str
1342
+ return ""
1343
+
1344
+
1345
+ def prepare_conflicts(
1346
+ repo: Path | str,
1347
+ *,
1348
+ relative_path: str | None = None,
1349
+ runtime_dir: Path | str | None = None,
1350
+ ) -> Path:
1351
+ repo_root = find_repo_root(repo)
1352
+ conflicts = detect_conflicts(repo_root)
1353
+ if relative_path:
1354
+ normalized = relative_path.replace("\\", "/")
1355
+ conflicts = [item for item in conflicts if item["path"] == normalized]
1356
+ if not conflicts:
1357
+ raise ConflictError("No unresolved .xlsx/.xlsm conflicts were found.")
1358
+
1359
+ target_dir = _safe_runtime_dir(repo_root, runtime_dir)
1360
+ auto_filters = load_auto_theirs_filters(repo_root)
1361
+ prepared_files = []
1362
+ auto_entries: list[dict[str, Any]] = []
1363
+ for index, item in enumerate(conflicts):
1364
+ checkpoint(file=item['path'], fileDone=index, fileTotal=len(conflicts), phase='提取三方版本', sheet='', sheetDone=0, sheetTotal=0, side='')
1365
+ path = item["path"]
1366
+ if auto_theirs_path(path, auto_filters):
1367
+ if 3 not in item["stages"]:
1368
+ raise ConflictError(
1369
+ f"{path} matches the auto-theirs rule, but Git stage 3 is missing."
1370
+ )
1371
+ auto_entries.append({
1372
+ "path": path,
1373
+ "theirsAuthor": _theirs_author(repo_root, path),
1374
+ "theirsDate": _theirs_date(repo_root, path),
1375
+ "theirsSha256": hashlib.sha256(_git_blob(repo_root, 3, path)).hexdigest(),
1376
+ "outputSha256": _sha256_path(repo_root / Path(path)) if (repo_root / Path(path)).exists() else None,
1377
+ })
1378
+ continue
1379
+ ours_blob = _git_blob(repo_root, 2, path)
1380
+ theirs_blob = _git_blob(repo_root, 3, path)
1381
+ if ours_blob is None or theirs_blob is None:
1382
+ raise ConflictError(
1383
+ f"{path} is a delete/modify conflict. This resolver currently requires both workbook versions."
1384
+ )
1385
+ base_blob = _git_blob(repo_root, 1, path)
1386
+ extension = Path(path).suffix.lower()
1387
+ macro = None
1388
+ if extension == ".xlsm":
1389
+ macro = _macro_payload_info(base_blob, ours_blob, theirs_blob)
1390
+ work_dir = target_dir / _slug(path)
1391
+ work_dir.mkdir(parents=True, exist_ok=True)
1392
+ ours_path = work_dir / f"ours{extension}"
1393
+ theirs_path = work_dir / f"theirs{extension}"
1394
+ base_path = work_dir / f"base{extension}"
1395
+ ours_path.write_bytes(ours_blob)
1396
+ theirs_path.write_bytes(theirs_blob)
1397
+ if base_blob is not None:
1398
+ base_path.write_bytes(base_blob)
1399
+ elif base_path.exists():
1400
+ base_path.unlink()
1401
+ for extracted_path in (base_path if base_blob is not None else None, ours_path, theirs_path):
1402
+ if extracted_path is not None:
1403
+ _repair_invalid_dimension_styles(extracted_path)
1404
+ workbook_diff = diff_workbooks(
1405
+ base_path if base_blob is not None else None,
1406
+ ours_path,
1407
+ theirs_path,
1408
+ analysis_dir=work_dir / "analysis",
1409
+ )
1410
+ value_snapshots = workbook_diff.get("valueSnapshots") or {}
1411
+ index_hashes = {
1412
+ "base": hashlib.sha256(base_blob).hexdigest() if base_blob is not None else None,
1413
+ "ours": hashlib.sha256(ours_blob).hexdigest(),
1414
+ "theirs": hashlib.sha256(theirs_blob).hexdigest(),
1415
+ }
1416
+ for side, snapshot_meta in value_snapshots.items():
1417
+ snapshot_meta["gitIndexSha256"] = index_hashes.get(side)
1418
+ prepared_files.append({
1419
+ "id": path,
1420
+ "path": path,
1421
+ "base": str(base_path) if base_blob is not None else None,
1422
+ "ours": str(ours_path),
1423
+ "theirs": str(theirs_path),
1424
+ "output": str((repo_root / Path(path)).resolve()),
1425
+ "oursAuthor": _author(repo_root, path, "HEAD"),
1426
+ "theirsAuthor": _theirs_author(repo_root, path),
1427
+ "oursDate": _ours_date(repo_root, path),
1428
+ "theirsDate": _theirs_date(repo_root, path),
1429
+ "macro": macro,
1430
+ # Keep both source and value digests in the manifest. apply must
1431
+ # reuse exactly what the user saw, never silently recalculate.
1432
+ "valueSnapshots": value_snapshots,
1433
+ "outputSha256": _sha256_path(repo_root / Path(path)) if (repo_root / Path(path)).exists() else None,
1434
+ "diff": workbook_diff,
1435
+ })
1436
+
1437
+ manifest = {
1438
+ "version": 4,
1439
+ "repoRoot": str(repo_root),
1440
+ "files": prepared_files,
1441
+ "autoTheirs": auto_entries,
1442
+ "summary": {
1443
+ "fileCount": len(prepared_files),
1444
+ "cellConflictCount": sum(f["diff"]["summary"]["cellConflictCount"] for f in prepared_files),
1445
+ "sheetConflictCount": sum(f["diff"]["summary"]["sheetConflictCount"] for f in prepared_files),
1446
+ "structuralConflictCount": sum(f["diff"]["summary"].get("structuralConflictCount", 0) for f in prepared_files),
1447
+ "autoTheirsCount": len(auto_entries),
1448
+ },
1449
+ }
1450
+ checkpoint(phase='完成解析', fileDone=len(conflicts), sheet='', sheetDone=0, sheetTotal=0)
1451
+ manifest_path = target_dir / "manifest.json"
1452
+ manifest_path.write_text(json.dumps(manifest, ensure_ascii=False, indent=2), encoding="utf-8")
1453
+ return manifest_path
1454
+
1455
+
1456
+ def load_manifest(path: Path | str) -> dict[str, Any]:
1457
+ manifest_path = Path(path).resolve()
1458
+ data = json.loads(manifest_path.read_text(encoding="utf-8"))
1459
+ if data.get("version") != 4 or not isinstance(data.get("files"), list):
1460
+ if data.get("version") == 3:
1461
+ raise ConflictError(
1462
+ f"Manifest {manifest_path} was created by the pre-materialization resolver; "
1463
+ "re-run prepare so formula values can be calculated safely."
1464
+ )
1465
+ raise ConflictError(f"Unsupported manifest: {manifest_path}")
1466
+ for entry in data["files"]:
1467
+ if not isinstance(entry.get("valueSnapshots"), dict):
1468
+ raise ConflictError(f"Manifest {manifest_path} has no immutable formula value snapshots.")
1469
+ return data
1470
+
1471
+
1472
+ def _copy_cell(source, target) -> None:
1473
+ if getattr(source, "data_type", None) == "s" and source.value == "":
1474
+ # Formula snapshots may legitimately contain an empty-string result.
1475
+ # Copy the typed rich-text payload so openpyxl does not serialize it as
1476
+ # an absent cell (None) on the next save.
1477
+ target.data_type = "s"
1478
+ target._value = copy(getattr(source, "_value", ""))
1479
+ else:
1480
+ target.value = source.value
1481
+ # openpyxl infers a string beginning with '=' as a formula. Snapshot
1482
+ # cells are literals, so restore the source type after assigning value;
1483
+ # otherwise a calculated string could become executable formula syntax.
1484
+ if getattr(source, "data_type", None) not in (None, "f"):
1485
+ target.data_type = source.data_type
1486
+ if source.has_style:
1487
+ if source.parent is not None and source.parent.parent is target.parent.parent:
1488
+ # 同 workbook:样式表索引通用,浅拷贝 StyleArray 避免对象复制(大表 40 万+ 格)
1489
+ target._style = copy(source._style)
1490
+ else:
1491
+ target.font = copy(source.font)
1492
+ target.fill = copy(source.fill)
1493
+ target.border = copy(source.border)
1494
+ target.alignment = copy(source.alignment)
1495
+ target.number_format = source.number_format
1496
+ target.protection = copy(source.protection)
1497
+ target.hyperlink = source.hyperlink
1498
+ target.comment = source.comment
1499
+
1500
+
1501
+ def _copy_sheet(source_ws, target_wb, *, index: int | None = None):
1502
+ target_ws = target_wb.create_sheet(source_ws.title, index=index)
1503
+ for row in source_ws.iter_rows():
1504
+ for source_cell in row:
1505
+ if isinstance(source_cell, MergedCell):
1506
+ continue
1507
+ _copy_cell(source_cell, target_ws.cell(source_cell.row, source_cell.column))
1508
+ for key, dimension in source_ws.column_dimensions.items():
1509
+ target_ws.column_dimensions[key] = copy(dimension)
1510
+ target_ws.column_dimensions[key].worksheet = target_ws
1511
+ for key, dimension in source_ws.row_dimensions.items():
1512
+ target_ws.row_dimensions[key] = copy(dimension)
1513
+ target_ws.row_dimensions[key].worksheet = target_ws
1514
+ for merged_range in source_ws.merged_cells.ranges:
1515
+ target_ws.merge_cells(str(merged_range))
1516
+ target_ws.views = copy(source_ws.views)
1517
+ target_ws.sheet_format = copy(source_ws.sheet_format)
1518
+ target_ws.sheet_properties = copy(source_ws.sheet_properties)
1519
+ target_ws.page_margins = copy(source_ws.page_margins)
1520
+ target_ws.page_setup = copy(source_ws.page_setup)
1521
+ target_ws.print_options = copy(source_ws.print_options)
1522
+ target_ws.auto_filter.ref = source_ws.auto_filter.ref
1523
+ target_ws.sheet_state = source_ws.sheet_state
1524
+ return target_ws
1525
+
1526
+
1527
+ def _replace_sheet(target_wb, source_ws, order: list[str]) -> None:
1528
+ if source_ws.title in target_wb.sheetnames:
1529
+ index = target_wb.sheetnames.index(source_ws.title)
1530
+ target_wb.remove(target_wb[source_ws.title])
1531
+ else:
1532
+ desired = order.index(source_ws.title) if source_ws.title in order else len(target_wb.sheetnames)
1533
+ index = min(desired, len(target_wb.sheetnames))
1534
+ _copy_sheet(source_ws, target_wb, index=index)
1535
+
1536
+
1537
+ def _file_decisions(decisions: dict[str, Any], file_id: str) -> dict[str, Any]:
1538
+ return ((decisions.get("files") or {}).get(file_id) or {})
1539
+
1540
+
1541
+ def _cell_choice(cell_choices: dict[str, Any], cell: dict[str, Any]) -> Any:
1542
+ return cell_choices.get(cell.get("id"), cell_choices.get(cell.get("coordinate")))
1543
+
1544
+
1545
+ def _validate_decisions(manifest: dict[str, Any], decisions: dict[str, Any]) -> None:
1546
+ missing: list[str] = []
1547
+ for file_entry in manifest["files"]:
1548
+ file_choice = _file_decisions(decisions, file_entry["id"])
1549
+ macro = file_entry.get("macro") or {}
1550
+ macro_choice = file_choice.get("macro", macro.get("default"))
1551
+ if macro.get("status") == "conflict" and macro_choice not in ("ours", "theirs"):
1552
+ missing.append(f"{file_entry['path']} / <VBA/ActiveX>")
1553
+ if macro_choice == "theirs" and not macro.get("canChooseTheirs", True):
1554
+ raise ConflictError(
1555
+ f"{file_entry['path']} has incompatible LOCAL and REMOTE VBA/ActiveX package structures; "
1556
+ "only the LOCAL macro payload can be preserved safely."
1557
+ )
1558
+ sheet_choices = file_choice.get("sheets") or {}
1559
+ for sheet in file_entry["diff"]["sheets"]:
1560
+ choice = sheet_choices.get(sheet["name"]) or {}
1561
+ if choice.get('sheet') in ('ours', 'theirs'):
1562
+ if sheet['action'] != 'merge' and not sheet['action'].startswith('conflict_'):
1563
+ raise ConflictError('自动处理 Sheet 不支持额外整表覆盖。')
1564
+ _selected_repairs(sheet, choice)
1565
+ continue
1566
+ if sheet["action"].startswith("conflict_") and choice.get("sheet") not in ("ours", "theirs"):
1567
+ missing.append(f"{file_entry['path']} / {sheet['name']} / <sheet>")
1568
+ if sheet["action"].startswith("conflict_"):
1569
+ selected_errors = [error for error in sheet.get("calculationErrors", [])
1570
+ if error["side"] == choice.get("sheet")]
1571
+ if selected_errors:
1572
+ error = selected_errors[0]
1573
+ raise ConflictError(f"Selected {error['side']} source has an Excel error at {file_entry['path']} / {error['sheet']}!{error['coordinate']}: {error['error']}")
1574
+ if sheet.get("renameStatus") == "rename_conflict" and choice.get("rename") not in ("ours", "theirs"):
1575
+ missing.append(f"{file_entry['path']} / {sheet['name']} / <rename>")
1576
+ if (sheet.get("mergedCells") or {}).get("status") == "conflict" and choice.get("mergedCells") not in ("ours", "theirs"):
1577
+ missing.append(f"{file_entry['path']} / {sheet['name']} / <merged-cells>")
1578
+ row_choices = choice.get("rows") or {}
1579
+ for row in sheet.get("allRows") or sheet.get("rows") or []:
1580
+ if row.get("state") == "delete_modify" and row_choices.get(row["id"]) not in ("keep", "delete"):
1581
+ missing.append(f"{file_entry['path']} / {sheet['name']} / {row['id']}")
1582
+ column_choices = choice.get("columns") or {}
1583
+ for column in sheet.get("columns") or []:
1584
+ if column.get("state") == "delete_modify" and column_choices.get(column["id"]) not in ("keep", "delete"):
1585
+ missing.append(f"{file_entry['path']} / {sheet['name']} / {column['id']}")
1586
+ cell_choices = choice.get("cells") or {}
1587
+ for cell in sheet["cells"]:
1588
+ side = _cell_choice(cell_choices, cell)
1589
+ if side in cell.get("errorSides", {}):
1590
+ raise ConflictError(f"Selected {side} source has an Excel error at {file_entry['path']} / {sheet['name']} / {cell['coordinate']}: {cell['errorSides'][side]}")
1591
+ if cell["resolution"] == "conflict" and side not in ("ours", "theirs"):
1592
+ missing.append(f"{file_entry['path']} / {sheet['name']} / {cell['coordinate']}")
1593
+ if missing:
1594
+ preview = "\n".join(f"- {item}" for item in missing[:20])
1595
+ suffix = f"\n... and {len(missing) - 20} more" if len(missing) > 20 else ""
1596
+ raise ConflictError(f"Unresolved choices remain:\n{preview}{suffix}")
1597
+
1598
+
1599
+ def _copy_sheet_properties(source_ws, target_ws) -> None:
1600
+ # freeze_panes only exposes topLeftCell. Reassigning it turns a scrolled
1601
+ # viewport such as topLeftCell=D857/ySplit=4 into a 856-row freeze.
1602
+ target_ws.views = copy(source_ws.views)
1603
+ target_ws.sheet_format = copy(source_ws.sheet_format)
1604
+ target_ws.sheet_properties = copy(source_ws.sheet_properties)
1605
+ target_ws.page_margins = copy(source_ws.page_margins)
1606
+ target_ws.page_setup = copy(source_ws.page_setup)
1607
+ target_ws.print_options = copy(source_ws.print_options)
1608
+ target_ws.auto_filter.ref = source_ws.auto_filter.ref
1609
+ target_ws.sheet_state = source_ws.sheet_state
1610
+
1611
+
1612
+ def _restore_merged_cells(target_ws, sheet, selection, active_rows, active_columns, header_count) -> None:
1613
+ model = sheet.get("mergedCells") or {}
1614
+ if model.get("status") == "conflict":
1615
+ regions = model.get(selection.get("mergedCells")) or []
1616
+ else:
1617
+ regions = model.get("resolved") or []
1618
+ row_positions = {f"header:{row}": row for row in range(1, header_count + 1)}
1619
+ row_positions.update({row["id"]: header_count + index for index, row in enumerate(active_rows, 1)})
1620
+ column_positions = {column["id"]: index for index, column in enumerate(active_columns, 1)}
1621
+ occupied: set[tuple[int, int]] = set()
1622
+ for region in regions:
1623
+ output_rows = sorted({row_positions[row] for row in region["rows"] if row in row_positions})
1624
+ output_columns = sorted({column_positions[column] for column in region["columns"] if column in column_positions})
1625
+ if not output_rows or not output_columns or len(output_rows) * len(output_columns) < 2:
1626
+ continue
1627
+ if output_rows != list(range(output_rows[0], output_rows[-1] + 1)):
1628
+ raise ConflictError(f"Merged rows are no longer contiguous in {sheet['name']}")
1629
+ if output_columns != list(range(output_columns[0], output_columns[-1] + 1)):
1630
+ raise ConflictError(f"Merged columns are no longer contiguous in {sheet['name']}")
1631
+ cells = {(row, column) for row in output_rows for column in output_columns}
1632
+ if occupied & cells:
1633
+ raise ConflictError(f"Merged regions overlap after alignment in {sheet['name']}")
1634
+ occupied.update(cells)
1635
+ target_ws.merge_cells(
1636
+ start_row=output_rows[0], end_row=output_rows[-1],
1637
+ start_column=output_columns[0], end_column=output_columns[-1],
1638
+ )
1639
+
1640
+
1641
+ def _axis_kept(axis: dict[str, Any], choices: dict[str, Any]) -> bool:
1642
+ if axis.get("state") == "deleted":
1643
+ return False
1644
+ if axis.get("state") == "delete_modify":
1645
+ return choices.get(axis["id"], axis.get("default", "keep")) == "keep"
1646
+ return True
1647
+
1648
+
1649
+ def _source_cell(workbooks, names, row, column, side: str):
1650
+ workbook = workbooks.get(side)
1651
+ sheet_name = names.get(side)
1652
+ row_number = row.get(f"{side}Row")
1653
+ column_number = column.get(f"{side}Col")
1654
+ if workbook is None or sheet_name is None or row_number is None or column_number is None:
1655
+ return None
1656
+ return workbook[sheet_name].cell(row_number, column_number)
1657
+
1658
+
1659
+ def _selected_source_cell(workbooks, names, row, column, cell, choice: str | None):
1660
+ preferred = []
1661
+ if choice in ("ours", "theirs"):
1662
+ preferred.append(choice)
1663
+ elif cell.get("resolution") == "theirs":
1664
+ preferred.append("theirs")
1665
+ elif cell.get("resolution") == "ours":
1666
+ preferred.append("ours")
1667
+ elif cell.get("resolution") == "same":
1668
+ preferred.extend(("ours", "theirs"))
1669
+ else:
1670
+ preferred.append("theirs")
1671
+ preferred.extend(side for side in ("ours", "theirs", "base") if side not in preferred)
1672
+ for side in preferred:
1673
+ source = _source_cell(workbooks, names, row, column, side)
1674
+ if source is not None:
1675
+ return source
1676
+ return None
1677
+
1678
+
1679
+ def _selected_sheet_name(sheet: dict[str, Any], selection: dict[str, Any]) -> str:
1680
+ names = sheet.get("names") or {}
1681
+ if sheet.get("renameStatus") == "rename_conflict":
1682
+ return names[selection["rename"]]
1683
+ return names.get("ours") or names.get("theirs") or names.get("base") or sheet["name"]
1684
+
1685
+
1686
+ _FORMULA_CACHE_NS = '{http://schemas.openxmlformats.org/spreadsheetml/2006/main}'
1687
+ _FORMULA_CACHE_RNS = '{http://schemas.openxmlformats.org/officeDocument/2006/relationships}'
1688
+
1689
+
1690
+
1691
+
1692
+ def _restore_untouched_formula_caches(source: Path, target: Path, sheet_names: set[str]) -> None:
1693
+ """Copy raw cache types/values, avoiding date-epoch and empty/error coercion."""
1694
+ import xml.etree.ElementTree as ET
1695
+
1696
+ def sheet_files(parts):
1697
+ relationships = ET.fromstring(parts['xl/_rels/workbook.xml.rels'])
1698
+ targets = {rel.get('Id'): rel.get('Target') for rel in relationships}
1699
+ result = {}
1700
+ for sheet in ET.fromstring(parts['xl/workbook.xml']).iter(f'{_FORMULA_CACHE_NS}sheet'):
1701
+ value = targets.get(sheet.get(f'{_FORMULA_CACHE_RNS}id'), '')
1702
+ if value:
1703
+ result[sheet.get('name')] = value.lstrip('/') if value.startswith('/') else 'xl/' + value
1704
+ return result
1705
+
1706
+ with zipfile.ZipFile(source) as archive:
1707
+ original = {item.filename: archive.read(item.filename) for item in archive.infolist()}
1708
+ with zipfile.ZipFile(target) as archive:
1709
+ infos = archive.infolist()
1710
+ parts = {item.filename: archive.read(item.filename) for item in infos}
1711
+ original_files, output_files = sheet_files(original), sheet_files(parts)
1712
+ for name in sheet_names:
1713
+ if name not in original_files or name not in output_files:
1714
+ continue
1715
+ original_tree = ET.fromstring(original[original_files[name]])
1716
+ caches = {cell.get('r'): cell for cell in original_tree.iter(f'{_FORMULA_CACHE_NS}c')
1717
+ if cell.find(f'{_FORMULA_CACHE_NS}f') is not None}
1718
+ if not caches:
1719
+ continue
1720
+ output_tree = ET.fromstring(parts[output_files[name]])
1721
+ for cell in output_tree.iter(f'{_FORMULA_CACHE_NS}c'):
1722
+ old = caches.get(cell.get('r'))
1723
+ if old is None or cell.find(f'{_FORMULA_CACHE_NS}f') is None:
1724
+ continue
1725
+ cell.attrib.pop('t', None)
1726
+ if 't' in old.attrib:
1727
+ cell.set('t', old.get('t'))
1728
+ for value in list(cell.findall(f'{_FORMULA_CACHE_NS}v')):
1729
+ cell.remove(value)
1730
+ old_value = old.find(f'{_FORMULA_CACHE_NS}v')
1731
+ if old_value is not None:
1732
+ cell.append(copy(old_value))
1733
+ parts[output_files[name]] = ET.tostring(output_tree, encoding='utf-8')
1734
+ with zipfile.ZipFile(target, 'w', zipfile.ZIP_DEFLATED) as archive:
1735
+ for info in infos:
1736
+ archive.writestr(info, parts[info.filename])
1737
+
1738
+
1739
+ def _preserve_empty_inline_strings(path: Path) -> None:
1740
+ """Make zero-length literal strings round-trip as ``''`` rather than None."""
1741
+ import xml.etree.ElementTree as ET
1742
+ namespace = "http://schemas.openxmlformats.org/spreadsheetml/2006/main"
1743
+ ET.register_namespace("", namespace)
1744
+ with zipfile.ZipFile(path) as source:
1745
+ infos = source.infolist()
1746
+ parts = {info.filename: source.read(info.filename) for info in infos}
1747
+ changed = False
1748
+ for name, payload in list(parts.items()):
1749
+ if not name.startswith("xl/worksheets/") or not name.endswith(".xml"):
1750
+ continue
1751
+ tree = ET.fromstring(payload)
1752
+ modified = False
1753
+ for cell in tree.iter(f"{{{namespace}}}c"):
1754
+ if cell.get("t") != "inlineStr" or cell.find(f"{{{namespace}}}is") is not None:
1755
+ continue
1756
+ inline = ET.SubElement(cell, f"{{{namespace}}}is")
1757
+ ET.SubElement(inline, f"{{{namespace}}}t").text = ""
1758
+ modified = True
1759
+ if modified:
1760
+ parts[name] = ET.tostring(tree, encoding="UTF-8")
1761
+ changed = True
1762
+ if not changed:
1763
+ return
1764
+ replacement = path.with_name(f".{path.name}.empty-strings")
1765
+ try:
1766
+ with zipfile.ZipFile(replacement, "w", zipfile.ZIP_DEFLATED) as output:
1767
+ for info in infos:
1768
+ output.writestr(info, parts[info.filename])
1769
+ os.replace(replacement, path)
1770
+ finally:
1771
+ replacement.unlink(missing_ok=True)
1772
+
1773
+
1774
+
1775
+
1776
+ def _rebuild_structural_sheet(wb_out, wb_base, wb_ours, wb_theirs, sheet, selection,
1777
+ wb_base_v=None, wb_ours_v=None, wb_theirs_v=None) -> dict[str, Any]:
1778
+ names = sheet.get("names") or {"base": sheet["name"], "ours": sheet["name"], "theirs": sheet["name"]}
1779
+ source_ws = None
1780
+ for workbook, side in ((wb_ours, "ours"), (wb_theirs, "theirs"), (wb_base, "base")):
1781
+ if workbook is not None and names.get(side) in workbook.sheetnames:
1782
+ source_ws = workbook[names[side]]
1783
+ break
1784
+ if source_ws is None:
1785
+ raise ConflictError(f"No source sheet is available for {sheet['name']}")
1786
+
1787
+ existing_name = names.get("ours")
1788
+ index = wb_out.sheetnames.index(existing_name) if existing_name in wb_out.sheetnames else len(wb_out.sheetnames)
1789
+ temp_title = f"__merge_{len(wb_out.sheetnames)}__"
1790
+ while temp_title in wb_out.sheetnames:
1791
+ temp_title += "_"
1792
+ target_ws = wb_out.create_sheet(temp_title, index=index)
1793
+ _copy_sheet_properties(source_ws, target_ws)
1794
+
1795
+ row_choices = selection.get("rows") or {}
1796
+ column_choices = selection.get("columns") or {}
1797
+ active_rows = [row for row in sheet.get("allRows") or [] if _axis_kept(row, row_choices)]
1798
+ active_columns = [column for column in sheet.get("columns") or [] if _axis_kept(column, column_choices)]
1799
+ workbooks = {"base": wb_base, "ours": wb_ours, "theirs": wb_theirs}
1800
+ workbooks_v = {"base": wb_base_v, "ours": wb_ours_v, "theirs": wb_theirs_v}
1801
+ cell_map = {cell["id"]: cell for cell in sheet.get("allCells") or sheet.get("cells") or []}
1802
+ cell_choices = selection.get("cells") or {}
1803
+ formula_cache: dict[str, Any] = {}
1804
+
1805
+ header_count = max(
1806
+ [max(_header_rows(workbook[names[side]]) or [0])
1807
+ for workbook, side in ((wb_base, "base"), (wb_ours, "ours"), (wb_theirs, "theirs"))
1808
+ if workbook is not None and names.get(side) in workbook.sheetnames]
1809
+ or [0]
1810
+ )
1811
+ for output_col, column in enumerate(active_columns, 1):
1812
+ dimension_source = None
1813
+ for workbook, side in ((wb_ours, "ours"), (wb_theirs, "theirs"), (wb_base, "base")):
1814
+ source_col = column.get(f"{side}Col")
1815
+ if workbook is not None and names.get(side) in workbook.sheetnames and source_col is not None:
1816
+ dimension_source = workbook[names[side]].column_dimensions[get_column_letter(source_col)]
1817
+ break
1818
+ if dimension_source is not None:
1819
+ target_ws.column_dimensions[get_column_letter(output_col)] = copy(dimension_source)
1820
+ target_ws.column_dimensions[get_column_letter(output_col)].worksheet = target_ws
1821
+ # 表头行高:ours 优先,回退 theirs/base
1822
+ for header_row in range(1, header_count + 1):
1823
+ for workbook, side in ((wb_ours, "ours"), (wb_theirs, "theirs"), (wb_base, "base")):
1824
+ if workbook is not None and names.get(side) in workbook.sheetnames:
1825
+ dim = workbook[names[side]].row_dimensions[header_row]
1826
+ if dim.height is not None:
1827
+ target_ws.row_dimensions[header_row] = copy(dim)
1828
+ target_ws.row_dimensions[header_row].worksheet = target_ws
1829
+ break
1830
+ for header_row in range(1, header_count + 1):
1831
+ for output_col, column in enumerate(active_columns, 1):
1832
+ source = None
1833
+ for side in ("theirs", "ours", "base"):
1834
+ workbook = workbooks[side]
1835
+ source_col = column.get(f"{side}Col")
1836
+ if workbook is not None and names.get(side) in workbook.sheetnames and source_col is not None:
1837
+ source = workbook[names[side]].cell(header_row, source_col)
1838
+ if source.value is not None:
1839
+ break
1840
+ if source is not None:
1841
+ _copy_cell(source, target_ws.cell(header_row, output_col))
1842
+
1843
+ for output_offset, row in enumerate(active_rows, 1):
1844
+ output_row = header_count + output_offset
1845
+ dimension_source = None
1846
+ for workbook, side in ((wb_ours, "ours"), (wb_theirs, "theirs"), (wb_base, "base")):
1847
+ source_row = row.get(f"{side}Row")
1848
+ if workbook is not None and names.get(side) in workbook.sheetnames and source_row is not None:
1849
+ dimension_source = workbook[names[side]].row_dimensions[source_row]
1850
+ break
1851
+ if dimension_source is not None:
1852
+ target_ws.row_dimensions[output_row] = copy(dimension_source)
1853
+ target_ws.row_dimensions[output_row].worksheet = target_ws
1854
+ for output_col, column in enumerate(active_columns, 1):
1855
+ cell = cell_map.get(f'{row["id"]}|{column["id"]}') or {
1856
+ "resolution": "same", "id": f'{row["id"]}|{column["id"]}', "coordinate": ""
1857
+ }
1858
+ choice = _cell_choice(cell_choices, cell)
1859
+ source = _selected_source_cell(workbooks, names, row, column, cell, choice)
1860
+ if source is not None:
1861
+ # 空且无格式的 cell 跳过写入:目标默认状态即空,输出等价
1862
+ if (
1863
+ source.value is None
1864
+ and not source.has_style
1865
+ and source.hyperlink is None
1866
+ and source.comment is None
1867
+ ):
1868
+ continue
1869
+ _copy_cell(source, target_ws.cell(output_row, output_col))
1870
+ # 公式 cell:记录输出坐标 -> 缓存值,保存后注入 XML
1871
+ if source.data_type == 'f':
1872
+ cached_source = _selected_source_cell(workbooks_v, names, row, column, cell, choice)
1873
+ cached_val = cached_source.value if cached_source is not None else None
1874
+ if cached_val is not None:
1875
+ formula_cache[f'{get_column_letter(output_col)}{output_row}'] = cached_val
1876
+
1877
+ _restore_merged_cells(target_ws, sheet, selection, active_rows, active_columns, header_count)
1878
+
1879
+ if existing_name in wb_out.sheetnames:
1880
+ wb_out.remove(wb_out[existing_name])
1881
+ final_name = _selected_sheet_name(sheet, selection)
1882
+ if final_name in wb_out.sheetnames and wb_out[final_name] is not target_ws:
1883
+ raise ConflictError(f"Sheet name collision after merge: {final_name}")
1884
+ target_ws.title = final_name
1885
+ return {final_name: formula_cache}
1886
+
1887
+
1888
+ def _build_merged_file(file_entry: dict[str, Any], decisions: dict[str, Any]) -> Path:
1889
+ output = Path(file_entry["output"]).resolve()
1890
+ output.parent.mkdir(parents=True, exist_ok=True)
1891
+ extension = output.suffix.lower()
1892
+ keep_vba = extension == ".xlsm"
1893
+ file_choice = _file_decisions(decisions, file_entry["id"])
1894
+ macro = file_entry.get("macro") or {}
1895
+ macro_choice = file_choice.get("macro", macro.get("default", "ours"))
1896
+ snapshot_meta = file_entry.get("valueSnapshots") or (file_entry.get("diff") or {}).get("valueSnapshots") or {}
1897
+ if not snapshot_meta:
1898
+ # Direct callers from older integrations may still build a workbook
1899
+ # without a manifest. Permit that only when there are no formulas;
1900
+ # a formula-bearing old input must never fall back to stale caches.
1901
+ if any(_workbook_has_formula(file_entry[side]) for side in ("base", "ours", "theirs") if file_entry.get(side)):
1902
+ raise ConflictError(
1903
+ f"{file_entry['path']} has formulas but no immutable value snapshot; re-run prepare."
1904
+ )
1905
+ snapshot_meta = {
1906
+ side: {"valuePath": file_entry.get(side)}
1907
+ for side in ("base", "ours", "theirs") if file_entry.get(side)
1908
+ }
1909
+ value_paths: dict[str, Path | None] = {}
1910
+ for side in ("base", "ours", "theirs"):
1911
+ meta = snapshot_meta.get(side) or {}
1912
+ path = meta.get("valuePath")
1913
+ if path is None:
1914
+ value_paths[side] = None
1915
+ continue
1916
+ value_path = Path(path).resolve()
1917
+ if not value_path.exists():
1918
+ raise ConflictError(f"Missing immutable {side} value snapshot for {file_entry['path']}: {value_path}")
1919
+ expected = meta.get("valueSha256")
1920
+ if expected and _sha256_path(value_path) != expected:
1921
+ raise ConflictError(f"Immutable {side} value snapshot changed for {file_entry['path']}; refusing apply.")
1922
+ _validate_value_workbook(value_path, allow_errors=True)
1923
+ value_paths[side] = value_path
1924
+ fd, temp_name = tempfile.mkstemp(prefix=f".{output.stem}-", suffix=extension, dir=output.parent)
1925
+ os.close(fd)
1926
+ temp_path = Path(temp_name)
1927
+ wb_out = load_workbook(file_entry["ours"], data_only=False, keep_links=True, keep_vba=keep_vba)
1928
+ # Original ours is the package/style/macro base. All sources used to
1929
+ # rebuild an affected Sheet are the calculated literal snapshots.
1930
+ wb_base = load_workbook(value_paths["base"], data_only=False, keep_links=True, keep_vba=keep_vba) if value_paths["base"] else None
1931
+ wb_ours = load_workbook(value_paths["ours"], data_only=False, keep_links=True, keep_vba=keep_vba)
1932
+ wb_theirs = load_workbook(value_paths["theirs"], data_only=False, keep_links=True, keep_vba=keep_vba)
1933
+ wb_base_v = wb_ours_v = wb_theirs_v = None
1934
+ sheet_choices = file_choice.get("sheets") or {}
1935
+ formula_cache: dict[str, dict[str, Any]] = {}
1936
+ affected_sheet_names: set[str] = set()
1937
+ affected_output_sheet_names: set[str] = set()
1938
+ output_sheet_names: set[str] = set()
1939
+ try:
1940
+ theirs_order = wb_theirs.sheetnames
1941
+ for sheet in file_entry["diff"]["sheets"]:
1942
+ name = sheet["name"]
1943
+ action = sheet["action"]
1944
+ selection = sheet_choices.get(name) or {}
1945
+ whole_source = selection.get('sheet') in ('ours', 'theirs')
1946
+ original_name = (sheet.get("names") or {}).get("ours") or name
1947
+ is_affected = (
1948
+ whole_source or action.startswith("conflict_")
1949
+ or action in ("auto_add_ours", "auto_add_theirs")
1950
+ or (
1951
+ action == "merge"
1952
+ and (
1953
+ sheet.get("rebuildRequired", True)
1954
+ or sheet.get("renameStatus") != "unchanged"
1955
+ or (sheet.get("mergedCells") or {}).get("status") != "same"
1956
+ )
1957
+ )
1958
+ )
1959
+ if is_affected:
1960
+ affected_sheet_names.add(original_name)
1961
+ if whole_source:
1962
+ affected_output_sheet_names.add((sheet.get('names') or {}).get(selection['sheet']) or name)
1963
+ elif action == "merge":
1964
+ affected_output_sheet_names.add(_selected_sheet_name(sheet, selection))
1965
+ elif action.startswith("conflict_"):
1966
+ affected_output_sheet_names.add((sheet.get("names") or {}).get(selection.get("sheet")) or name)
1967
+ elif action == "auto_add_ours":
1968
+ affected_output_sheet_names.add((sheet.get("names") or {}).get("ours") or name)
1969
+ elif action == "auto_add_theirs":
1970
+ affected_output_sheet_names.add((sheet.get("names") or {}).get("theirs") or name)
1971
+ if action == "auto_delete":
1972
+ if name in wb_out.sheetnames:
1973
+ wb_out.remove(wb_out[name])
1974
+ continue
1975
+ if action == "auto_add_theirs":
1976
+ theirs_name = (sheet.get("names") or {}).get("theirs") or name
1977
+ ours_name = (sheet.get("names") or {}).get("ours")
1978
+ if ours_name in wb_out.sheetnames:
1979
+ wb_out.remove(wb_out[ours_name])
1980
+ if theirs_name not in wb_out.sheetnames:
1981
+ _copy_sheet(wb_theirs[theirs_name], wb_out, index=min(theirs_order.index(theirs_name), len(wb_out.sheetnames)))
1982
+ continue
1983
+ if action == "auto_add_ours":
1984
+ ours_name = (sheet.get("names") or {}).get("ours") or name
1985
+ if ours_name in wb_out.sheetnames:
1986
+ wb_out.remove(wb_out[ours_name])
1987
+ if ours_name in wb_ours.sheetnames:
1988
+ _copy_sheet(
1989
+ wb_ours[ours_name], wb_out,
1990
+ index=min(wb_ours.sheetnames.index(ours_name), len(wb_out.sheetnames)),
1991
+ )
1992
+ continue
1993
+ if whole_source or action.startswith("conflict_"):
1994
+ side = selection["sheet"]
1995
+ if side == "ours":
1996
+ source_wb = wb_ours
1997
+ else:
1998
+ source_wb = wb_theirs
1999
+ source_name = (sheet.get("names") or {}).get(side) or name
2000
+ if source_name in source_wb.sheetnames:
2001
+ from formula_values import _set_literal
2002
+ for coordinate, value in _selected_repairs(sheet, selection).items():
2003
+ _set_literal(source_wb[source_name][coordinate], value)
2004
+ ours_name = (sheet.get("names") or {}).get("ours") or name
2005
+ if ours_name != source_name and ours_name in wb_out.sheetnames:
2006
+ wb_out.remove(wb_out[ours_name])
2007
+ if source_name in source_wb.sheetnames:
2008
+ _replace_sheet(wb_out, source_wb[source_name], source_wb.sheetnames)
2009
+ elif name in wb_out.sheetnames:
2010
+ wb_out.remove(wb_out[name])
2011
+ continue
2012
+ if action != "merge":
2013
+ continue
2014
+ if not is_affected:
2015
+ # Formula text may differ while final values are equal. This
2016
+ # is intentionally an untouched Sheet: preserve ours exactly.
2017
+ continue
2018
+ if not sheet.get("rebuildRequired", True):
2019
+ existing_name = (sheet.get("names") or {}).get("ours") or name
2020
+ final_name = _selected_sheet_name(sheet, selection)
2021
+ # A rename-only/metadata-only changed Sheet is still affected;
2022
+ # replace it from the selected calculated value snapshot so no
2023
+ # formula survives through this fast path.
2024
+ source_side = selection.get("rename", "ours") if sheet.get("renameStatus") == "rename_conflict" else "ours"
2025
+ source_name = (sheet.get("names") or {}).get(source_side) or existing_name
2026
+ source_wb = wb_theirs if source_side == "theirs" else wb_ours
2027
+ if source_name in source_wb.sheetnames:
2028
+ if existing_name in wb_out.sheetnames:
2029
+ old_index = wb_out.sheetnames.index(existing_name)
2030
+ wb_out.remove(wb_out[existing_name])
2031
+ else:
2032
+ old_index = len(wb_out.sheetnames)
2033
+ copied = _copy_sheet(source_wb[source_name], wb_out, index=old_index)
2034
+ if final_name != copied.title:
2035
+ if final_name in wb_out.sheetnames and wb_out[final_name] is not copied:
2036
+ raise ConflictError(f"Sheet name collision after merge: {final_name}")
2037
+ copied.title = final_name
2038
+ continue
2039
+ if sheet.get("allRows") is not None and sheet.get("columns") is not None:
2040
+ cache = _rebuild_structural_sheet(
2041
+ wb_out, wb_base, wb_ours, wb_theirs, sheet, selection,
2042
+ wb_base_v, wb_ours_v, wb_theirs_v,
2043
+ )
2044
+ formula_cache.update(cache)
2045
+ continue
2046
+ # Legacy coordinate-only reports are now also sourced from the
2047
+ # literal snapshot. They should be rare (structural reports use
2048
+ # _rebuild_structural_sheet), but must obey the same no-formula rule.
2049
+ if name not in wb_ours.sheetnames:
2050
+ raise ConflictError(f"Missing ours Sheet {name} in legacy merge report.")
2051
+ # Start from the literal ours snapshot so unchanged formula cells
2052
+ # on this affected Sheet cannot survive the legacy patch path.
2053
+ _replace_sheet(wb_out, wb_ours[name], wb_ours.sheetnames)
2054
+ ws_out = wb_out[name]
2055
+ ws_theirs = wb_theirs[name]
2056
+ cell_choices = selection.get("cells") or {}
2057
+ for cell in sheet["cells"]:
2058
+ side = cell_choices.get(cell["coordinate"], cell["resolution"])
2059
+ if side == "conflict":
2060
+ side = cell_choices[cell["coordinate"]]
2061
+ if side == "theirs":
2062
+ _copy_cell(ws_theirs[cell["coordinate"]], ws_out[cell["coordinate"]])
2063
+ if not wb_out.sheetnames:
2064
+ raise ConflictError(f"Cannot save a workbook with no sheets: {file_entry['path']}")
2065
+ output_sheet_names = set(wb_out.sheetnames)
2066
+ wb_out.save(temp_path)
2067
+ except Exception:
2068
+ temp_path.unlink(missing_ok=True)
2069
+ raise
2070
+ finally:
2071
+ _close_workbook(wb_out)
2072
+ _close_workbook(wb_base)
2073
+ if wb_ours is not wb_out:
2074
+ _close_workbook(wb_ours)
2075
+ _close_workbook(wb_theirs)
2076
+ _close_workbook(wb_base_v)
2077
+ _close_workbook(wb_ours_v)
2078
+ _close_workbook(wb_theirs_v)
2079
+
2080
+ try:
2081
+ _restore_untouched_formula_caches(
2082
+ Path(file_entry['ours']), temp_path, output_sheet_names - affected_sheet_names,
2083
+ )
2084
+ _preserve_empty_inline_strings(temp_path)
2085
+ check_wb = load_workbook(temp_path, read_only=True, data_only=False)
2086
+ try:
2087
+ for ws in check_wb.worksheets:
2088
+ if ws.title not in affected_output_sheet_names:
2089
+ continue
2090
+ for row in ws.iter_rows():
2091
+ for cell in row:
2092
+ if cell.data_type == "f":
2093
+ raise ConflictError(
2094
+ f"Affected Sheet {ws.title} retained formula at {cell.coordinate}; output was not written."
2095
+ )
2096
+ if cell.data_type == "e":
2097
+ raise ConflictError(f"Selected source contains an Excel error at {ws.title}!{cell.coordinate}; output was not written.")
2098
+ finally:
2099
+ check_wb.close()
2100
+ if keep_vba:
2101
+ macro_source = file_entry["theirs"] if macro_choice == "theirs" else file_entry["ours"]
2102
+ if macro_choice == "theirs":
2103
+ if not macro.get("canChooseTheirs", True):
2104
+ raise ConflictError(
2105
+ f"Cannot safely preserve the REMOTE macro payload for {file_entry['path']} because its package structure differs."
2106
+ )
2107
+ _replace_macro_payload(temp_path, macro_source)
2108
+ expected_hash, expected_entries = _macro_payload_digest(macro_source)
2109
+ actual_hash, actual_entries = _macro_payload_digest(temp_path)
2110
+ if actual_hash != expected_hash or actual_entries != expected_entries:
2111
+ raise ConflictError(f"Macro payload changed while saving {file_entry['path']}; output was not written.")
2112
+ return temp_path
2113
+ except Exception:
2114
+ temp_path.unlink(missing_ok=True)
2115
+ raise
2116
+
2117
+
2118
+ def _git_step(repo: Path, args: list[str], label: str) -> dict[str, Any]:
2119
+ result = _run_git(repo, args)
2120
+ output = (result.stdout + result.stderr).strip()
2121
+ return {"step": label, "success": result.returncode == 0, "output": output}
2122
+
2123
+
2124
+ def _apply_auto_theirs(repo: Path, entries: list[dict[str, Any]]) -> list[Path]:
2125
+ """Write auto-theirs workbooks byte-for-byte from Git index stage 3."""
2126
+ outputs: list[Path] = []
2127
+ for entry in entries:
2128
+ relative_path = entry["path"]
2129
+ output = (repo / Path(relative_path)).resolve()
2130
+ if os.path.commonpath([str(repo), str(output)]) != str(repo):
2131
+ raise ConflictError(f"Output escapes repository: {output}")
2132
+ blob = _git_blob(repo, 3, relative_path)
2133
+ if blob is None:
2134
+ raise ConflictError(f"{relative_path} matches the auto-theirs rule, but Git stage 3 is missing.")
2135
+ output.parent.mkdir(parents=True, exist_ok=True)
2136
+ with open(output, "wb") as handle:
2137
+ handle.write(blob)
2138
+ outputs.append(output)
2139
+ return outputs
2140
+
2141
+
2142
+ def _build_commit_message(manifest: dict[str, Any], decisions: dict[str, Any]) -> str:
2143
+ """生成结构化提交信息:每个已选择的冲突 Cell 一行。
2144
+
2145
+ 格式:resolve: [表:path]-[sheet:name]-[单元格:A1]-[选择:远端/本地] [远端值:xxx 本地值:xxx]
2146
+ 无冲突 Cell 时回退默认信息。
2147
+ """
2148
+ lines: list[str] = []
2149
+ for entry in manifest.get("autoTheirs") or []:
2150
+ lines.append(f"resolve(auto): [表:{entry['path']}]-[选择:远端全量]")
2151
+ for file_entry in manifest["files"]:
2152
+ file_choice = _file_decisions(decisions, file_entry["id"])
2153
+ sheet_choices = file_choice.get("sheets") or {}
2154
+ for sheet in file_entry["diff"]["sheets"]:
2155
+ choice = sheet_choices.get(sheet["name"]) or {}
2156
+ if choice.get('sheet') in ('ours', 'theirs'):
2157
+ lines.append(f"resolve(sheet): [表:{file_entry['path']}]-[sheet:{sheet['name']}]-[选择:{choice['sheet']} 全量]")
2158
+ for coordinate, value in _selected_repairs(sheet, choice).items():
2159
+ lines.append(f"resolve(manual): [表:{file_entry['path']}]-[sheet:{sheet['name']}]-[来源:{choice['sheet']}]-[单元格:{coordinate}]-[值:{json.dumps(value, ensure_ascii=False)}]")
2160
+ recorded = set()
2161
+ for repair in sheet.get("replacements", []):
2162
+ if sheet["action"].startswith("conflict_") and repair["side"] != choice.get("sheet"):
2163
+ continue
2164
+ key = (repair["side"], repair["coordinate"]) if repair.get("manual") else (repair["recordId"], repair["field"])
2165
+ if key in recorded:
2166
+ continue
2167
+ recorded.add(key)
2168
+ if repair.get("manual"):
2169
+ lines.append(f"resolve(manual): [表:{file_entry['path']}]-[sheet:{sheet['name']}]-[来源:{repair['side']}]-[单元格:{repair['coordinate']}]-[字段:{repair['field']}]-[类型:{repair['type']}]-[值:{json.dumps(repair['value'], ensure_ascii=False)}]")
2170
+ else:
2171
+ lines.append(f"resolve(default): [表:{file_entry['path']}]-[sheet:{sheet['name']}]-[id:{repair['recordId']}]-[字段:{repair['field']}]-[类型:{repair['type']}]-[值:{json.dumps(repair['value'], ensure_ascii=False)}]")
2172
+ cell_choices = choice.get("cells") or {}
2173
+ if choice.get('sheet') in ('ours', 'theirs'):
2174
+ continue
2175
+ for cell in sheet["cells"]:
2176
+ if cell.get("resolution") != "conflict":
2177
+ continue
2178
+ cell_choice = _cell_choice(cell_choices, cell)
2179
+ if cell_choice not in ("ours", "theirs"):
2180
+ continue
2181
+ label = cell.get("coordinate") or cell.get("id") or ""
2182
+ side = "远端" if cell_choice == "theirs" else "本地"
2183
+ theirs_value = _message_value(cell.get("theirs"))
2184
+ ours_value = _message_value(cell.get("ours"))
2185
+ lines.append(
2186
+ f"resolve: [表:{file_entry['path']}]-[sheet:{sheet['name']}]-[单元格:{label}]-[选择:{side}] "
2187
+ f"[远端值:{theirs_value} 本地值:{ours_value}]"
2188
+ )
2189
+ if not lines:
2190
+ return "resolve: merge xlsx conflicts"
2191
+ message = "\n".join(lines)
2192
+ # 防止超长消息撑爆 git commit 命令行(Windows 单条命令约 32K 字符)
2193
+ if len(message) > MAX_COMMIT_MESSAGE_CHARS:
2194
+ message = message[:MAX_COMMIT_MESSAGE_CHARS].rstrip() + "\n... (truncated)"
2195
+ return message
2196
+
2197
+
2198
+ MAX_COMMIT_MESSAGE_CHARS = 20000
2199
+
2200
+
2201
+ def _message_value(value) -> str:
2202
+ """Cell 显示值转提交信息字符串:None 转空,浮点去多余小数。"""
2203
+ if value is None:
2204
+ return ""
2205
+ if isinstance(value, float):
2206
+ return str(int(value)) if value == int(value) else str(value)
2207
+ return str(value)
2208
+
2209
+
2210
+ def _validate_manifest_sources(manifest: dict[str, Any], repo: Path) -> None:
2211
+ """Preflight every input before preparing any output replacement.
2212
+
2213
+ This deliberately validates both extracted files and their current index
2214
+ stages. A user may keep the UI open while another process changes a
2215
+ conflict, in which case applying the old choices would be data loss.
2216
+ """
2217
+ for entry in manifest.get("files") or []:
2218
+ relative = entry["path"]
2219
+ for side, stage in (("base", 1), ("ours", 2), ("theirs", 3)):
2220
+ meta = (entry.get("valueSnapshots") or {}).get(side) or {}
2221
+ source_path = entry.get(side)
2222
+ if source_path is None:
2223
+ if stage == 1 and _git_blob(repo, stage, relative) is None:
2224
+ continue
2225
+ raise ConflictError(f"Manifest source missing for {relative} ({side}).")
2226
+ source = Path(source_path).resolve()
2227
+ if not source.exists():
2228
+ raise ConflictError(f"Manifest source missing for {relative} ({side}): {source}")
2229
+ expected_source = meta.get("sourceSha256")
2230
+ actual_source = _sha256_path(source)
2231
+ if expected_source and actual_source != expected_source:
2232
+ raise ConflictError(f"Manifest source changed for {relative} ({side}); refusing apply.")
2233
+ indexed = _git_blob(repo, stage, relative)
2234
+ if indexed is None:
2235
+ raise ConflictError(f"Git index stage {stage} changed or disappeared for {relative} ({side}).")
2236
+ expected_index = meta.get("gitIndexSha256") or expected_source
2237
+ if expected_index and hashlib.sha256(indexed).hexdigest() != expected_index:
2238
+ raise ConflictError(f"Git index source changed for {relative} ({side}); re-run prepare.")
2239
+ value_path = meta.get("valuePath")
2240
+ expected_value = meta.get("valueSha256")
2241
+ if not value_path or not expected_value:
2242
+ raise ConflictError(f"Manifest has no immutable value snapshot for {relative} ({side}).")
2243
+ snapshot = Path(value_path).resolve()
2244
+ if not snapshot.exists() or _sha256_path(snapshot) != expected_value:
2245
+ raise ConflictError(f"Immutable value snapshot changed for {relative} ({side}); refusing apply.")
2246
+ _validate_value_workbook(snapshot, allow_errors=True)
2247
+ output = (repo / Path(relative)).resolve()
2248
+ expected_output = entry.get("outputSha256")
2249
+ if expected_output is None:
2250
+ if output.exists():
2251
+ raise ConflictError(f"Worktree output appeared after prepare for {relative}; refusing overwrite.")
2252
+ elif not output.exists() or _sha256_path(output) != expected_output:
2253
+ raise ConflictError(f"Worktree output changed for {relative}; re-run prepare before apply.")
2254
+ for entry in manifest.get("autoTheirs") or []:
2255
+ relative = entry["path"]
2256
+ blob = _git_blob(repo, 3, relative)
2257
+ if blob is None:
2258
+ raise ConflictError(f"{relative} requires remote stage 3, but it is no longer available.")
2259
+ expected = entry.get("theirsSha256")
2260
+ if expected and hashlib.sha256(blob).hexdigest() != expected:
2261
+ raise ConflictError(f"Remote source changed for automatic table {relative}; re-run prepare.")
2262
+ output = (repo / Path(relative)).resolve()
2263
+ expected_output = entry.get("outputSha256")
2264
+ if expected_output is None:
2265
+ if output.exists():
2266
+ raise ConflictError(f"Worktree output appeared after prepare for {relative}; refusing overwrite.")
2267
+ elif not output.exists() or _sha256_path(output) != expected_output:
2268
+ raise ConflictError(f"Worktree output changed for {relative}; re-run prepare before apply.")
2269
+
2270
+
2271
+ def _replace_prepared_outputs(prepared: list[tuple[Path, Path]]) -> None:
2272
+ """Replace only after all outputs exist; roll back earlier swaps on failure."""
2273
+ backups: dict[Path, Path | None] = {}
2274
+ replaced: list[Path] = []
2275
+ retained: set[Path] = set()
2276
+ try:
2277
+ for output, _ in prepared:
2278
+ if output.exists():
2279
+ fd, backup_name = tempfile.mkstemp(prefix=f".{output.stem}-backup-", suffix=output.suffix, dir=output.parent)
2280
+ os.close(fd)
2281
+ backup = Path(backup_name)
2282
+ backups[output] = backup
2283
+ shutil.copy2(output, backup)
2284
+ else:
2285
+ backups[output] = None
2286
+ try:
2287
+ for output, temporary in prepared:
2288
+ os.replace(temporary, output)
2289
+ replaced.append(output)
2290
+ except Exception as exc:
2291
+ errors = []
2292
+ for output in reversed(replaced):
2293
+ backup = backups[output]
2294
+ try:
2295
+ if backup is None:
2296
+ output.unlink(missing_ok=True)
2297
+ else:
2298
+ os.replace(backup, output)
2299
+ except Exception as restore_error:
2300
+ if backup is not None:
2301
+ retained.add(backup)
2302
+ errors.append(f"{output}: {restore_error}; recovery copy: {backup}")
2303
+ if errors:
2304
+ raise ConflictError("Output replacement failed; recovery copies retained: " + "; ".join(errors)) from exc
2305
+ raise ConflictError("Output replacement failed; earlier replacements rolled back; Git index unchanged.") from exc
2306
+ finally:
2307
+ for backup in backups.values():
2308
+ if backup is not None and backup not in retained:
2309
+ backup.unlink(missing_ok=True)
2310
+
2311
+
2312
+ def apply_manifest(
2313
+ manifest_path: Path | str,
2314
+ decisions: dict[str, Any],
2315
+ *,
2316
+ commit: bool = True,
2317
+ push: bool = False,
2318
+ message: str | None = None,
2319
+ ) -> dict[str, Any]:
2320
+ manifest = load_manifest(manifest_path)
2321
+ _validate_decisions(manifest, decisions)
2322
+ repo = find_repo_root(manifest["repoRoot"])
2323
+ # Validate every immutable source, calculated-value snapshot, and worktree
2324
+ # output before creating any replacement. A failed preflight leaves both
2325
+ # the worktree and Git index untouched.
2326
+ _validate_manifest_sources(manifest, repo)
2327
+ auto_entries = manifest.get("autoTheirs") or []
2328
+ if not manifest["files"] and not auto_entries:
2329
+ raise ConflictError("Manifest has no conflicts to resolve.")
2330
+ prepared: list[tuple[Path, Path]] = []
2331
+ manual_outputs: list[Path] = []
2332
+ auto_outputs: list[Path] = []
2333
+ try:
2334
+ for file_entry in manifest["files"]:
2335
+ output = Path(file_entry["output"]).resolve()
2336
+ if os.path.commonpath([str(repo), str(output)]) != str(repo):
2337
+ raise ConflictError(f"Output escapes repository: {output}")
2338
+ prepared.append((output, _build_merged_file(file_entry, decisions)))
2339
+ manual_outputs.append(output)
2340
+ for entry in auto_entries:
2341
+ output = (repo / entry["path"]).resolve()
2342
+ if os.path.commonpath([str(repo), str(output)]) != str(repo):
2343
+ raise ConflictError(f"Output escapes repository: {output}")
2344
+ blob = _git_blob(repo, 3, entry["path"])
2345
+ if blob is None or hashlib.sha256(blob).hexdigest() != entry.get("theirsSha256"):
2346
+ raise ConflictError(f"Remote source changed for automatic table {entry['path']}.")
2347
+ output.parent.mkdir(parents=True, exist_ok=True)
2348
+ fd, temporary_name = tempfile.mkstemp(
2349
+ prefix=f".{output.stem}-", suffix=output.suffix, dir=output.parent
2350
+ )
2351
+ temporary = Path(temporary_name)
2352
+ prepared.append((output, temporary))
2353
+ with os.fdopen(fd, "wb") as handle:
2354
+ handle.write(blob)
2355
+ auto_outputs.append(output)
2356
+
2357
+ # Builds may be expensive, so check the inputs once more immediately
2358
+ # before the atomic batch replacement.
2359
+ _validate_manifest_sources(manifest, repo)
2360
+ _replace_prepared_outputs(prepared)
2361
+
2362
+ outputs = [output for output, _ in prepared]
2363
+ relative_paths = [str(output.relative_to(repo)).replace("\\", "/") for output in outputs]
2364
+ steps = [_git_step(repo, ["add", "--", *relative_paths], "git add")]
2365
+ success = steps[-1]["success"]
2366
+ if success and commit:
2367
+ commit_message = message or _build_commit_message(manifest, decisions)
2368
+ steps.append(_git_step(repo, ["commit", "-m", commit_message], "git commit"))
2369
+ success = steps[-1]["success"]
2370
+ if success and push:
2371
+ steps.append(_git_step(repo, ["push"], "git push"))
2372
+ success = steps[-1]["success"]
2373
+ return {
2374
+ "success": success,
2375
+ "merged": [str(output) for output in manual_outputs],
2376
+ "autoTheirs": [str(output.relative_to(repo)).replace("\\", "/") for output in auto_outputs],
2377
+ "steps": steps,
2378
+ }
2379
+ finally:
2380
+ for _, temp_path in prepared:
2381
+ temp_path.unlink(missing_ok=True)