@kevlns/xlmerge 2.0.1 → 2.0.2

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