@kevlns/xlmerge 1.2.1-beta.1

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.
@@ -0,0 +1,1478 @@
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
+
23
+ # 兼容嵌入式 Python(._pth 忽略 PYTHONPATH):包内自举,将包根加入 sys.path
24
+ _PKG_ROOT = Path(__file__).resolve().parents[1]
25
+ if str(_PKG_ROOT) not in sys.path:
26
+ sys.path.insert(0, str(_PKG_ROOT))
27
+
28
+ from xlsx_merge_engine.xlsx_git_merge_bridge import analyze_workbooks as analyze_structural_workbooks
29
+
30
+
31
+ class ConflictError(RuntimeError):
32
+ """Raised when a conflict cannot be prepared or resolved safely."""
33
+
34
+
35
+ WORKBOOK_EXTENSIONS = {".xlsx", ".xlsm"}
36
+
37
+
38
+ def _is_supported_workbook(path: str | Path) -> bool:
39
+ return Path(path).suffix.lower() in WORKBOOK_EXTENSIONS
40
+
41
+
42
+ def _is_macro_workbook(path: str | Path) -> bool:
43
+ return Path(path).suffix.lower() == ".xlsm"
44
+
45
+
46
+ def _is_macro_payload_entry(name: str) -> bool:
47
+ lowered = name.lower()
48
+ return (
49
+ lowered.startswith(("xl/vba", "xl/ctrlprops/", "customui/", "xl/activex/"))
50
+ or (lowered.startswith("xl/drawings/") and "vmldrawing" in lowered and lowered.endswith(".vml"))
51
+ or (lowered.startswith("xl/media/") and lowered.endswith(".emf"))
52
+ )
53
+
54
+
55
+ def _macro_payload_digest(source: bytes | Path | str) -> tuple[str, list[str]]:
56
+ raw = source if isinstance(source, bytes) else Path(source).read_bytes()
57
+ try:
58
+ with zipfile.ZipFile(io.BytesIO(raw)) as archive:
59
+ entries = sorted(name for name in archive.namelist() if _is_macro_payload_entry(name))
60
+ digest = hashlib.sha256()
61
+ for name in entries:
62
+ digest.update(name.encode("utf-8"))
63
+ digest.update(b"\0")
64
+ digest.update(archive.read(name))
65
+ return digest.hexdigest(), entries
66
+ except (OSError, zipfile.BadZipFile) as exc:
67
+ raise ConflictError(f"Invalid macro-enabled workbook package: {exc}") from exc
68
+
69
+
70
+ def _macro_payload_info(base_blob: bytes | None, ours_blob: bytes, theirs_blob: bytes) -> dict[str, Any]:
71
+ base_hash, base_entries = _macro_payload_digest(base_blob) if base_blob is not None else (None, [])
72
+ ours_hash, ours_entries = _macro_payload_digest(ours_blob)
73
+ theirs_hash, theirs_entries = _macro_payload_digest(theirs_blob)
74
+ ours_key = (ours_hash, ours_entries)
75
+ theirs_key = (theirs_hash, theirs_entries)
76
+ base_key = (base_hash, base_entries) if base_hash is not None else None
77
+ compatible = ours_entries == theirs_entries
78
+ if ours_key == theirs_key:
79
+ status, default = "same", "ours"
80
+ elif not compatible:
81
+ status, default = "incompatible", "ours"
82
+ elif base_key is not None and ours_key == base_key:
83
+ status, default = "auto_theirs", "theirs"
84
+ elif base_key is not None and theirs_key == base_key:
85
+ status, default = "auto_ours", "ours"
86
+ else:
87
+ status, default = "conflict", "ours"
88
+ return {
89
+ "status": status,
90
+ "default": default,
91
+ "canChooseTheirs": compatible,
92
+ "baseHash": base_hash,
93
+ "oursHash": ours_hash,
94
+ "theirsHash": theirs_hash,
95
+ "baseEntries": base_entries,
96
+ "oursEntries": ours_entries,
97
+ "theirsEntries": theirs_entries,
98
+ }
99
+
100
+
101
+ def _replace_macro_payload(target: Path, source: Path | str) -> None:
102
+ source_path = Path(source)
103
+ with zipfile.ZipFile(target) as target_archive, zipfile.ZipFile(source_path) as source_archive:
104
+ target_parts = [
105
+ (info, target_archive.read(info.filename))
106
+ for info in target_archive.infolist()
107
+ if not _is_macro_payload_entry(info.filename)
108
+ ]
109
+ source_parts = [
110
+ (info, source_archive.read(info.filename))
111
+ for info in source_archive.infolist()
112
+ if _is_macro_payload_entry(info.filename)
113
+ ]
114
+ fd, replacement_name = tempfile.mkstemp(prefix=f".{target.stem}-macro-", suffix=target.suffix, dir=target.parent)
115
+ os.close(fd)
116
+ replacement = Path(replacement_name)
117
+ try:
118
+ with zipfile.ZipFile(replacement, "w") as output_archive:
119
+ for info, payload in [*target_parts, *source_parts]:
120
+ output_archive.writestr(info, payload)
121
+ os.replace(replacement, target)
122
+ finally:
123
+ replacement.unlink(missing_ok=True)
124
+
125
+
126
+ def _close_workbook(workbook) -> None:
127
+ if workbook is None:
128
+ return
129
+ vba_archive = getattr(workbook, "vba_archive", None)
130
+ workbook.close()
131
+ if vba_archive is not None:
132
+ vba_archive.close()
133
+
134
+
135
+ def _run_git(repo: Path, args: list[str], *, binary: bool = False, check: bool = False):
136
+ result = subprocess.run(
137
+ ["git", "-C", str(repo), "-c", "core.quotepath=false", *args],
138
+ capture_output=True,
139
+ text=not binary,
140
+ encoding=None if binary else "utf-8",
141
+ errors=None if binary else "replace",
142
+ timeout=60,
143
+ )
144
+ if check and result.returncode != 0:
145
+ stderr = result.stderr.decode("utf-8", "replace") if binary else result.stderr
146
+ raise ConflictError(f"git {' '.join(args)} failed: {stderr.strip()}")
147
+ return result
148
+
149
+
150
+ def find_repo_root(repo: Path | str) -> Path:
151
+ candidate = Path(repo).resolve()
152
+ result = _run_git(candidate, ["rev-parse", "--show-toplevel"])
153
+ if result.returncode != 0:
154
+ raise ConflictError(f"Not a Git repository: {candidate}")
155
+ return Path(result.stdout.strip()).resolve()
156
+
157
+
158
+ def detect_conflicts(repo: Path | str) -> list[dict[str, Any]]:
159
+ repo_root = find_repo_root(repo)
160
+ result = _run_git(repo_root, ["diff", "--name-only", "--diff-filter=U", "-z"], binary=True, check=True)
161
+ paths = result.stdout.decode("utf-8", "surrogateescape").split("\0")
162
+ conflicts: list[dict[str, Any]] = []
163
+ for relative_path in paths:
164
+ if not relative_path or not _is_supported_workbook(relative_path):
165
+ continue
166
+ stages_result = _run_git(repo_root, ["ls-files", "-u", "--", relative_path], check=True)
167
+ stages: list[int] = []
168
+ for line in stages_result.stdout.splitlines():
169
+ prefix = line.split("\t", 1)[0].split()
170
+ if len(prefix) >= 3:
171
+ stages.append(int(prefix[2]))
172
+ conflicts.append({"path": relative_path.replace("\\", "/"), "stages": sorted(set(stages))})
173
+ return conflicts
174
+
175
+
176
+ def _git_blob(repo: Path, stage: int, relative_path: str) -> bytes | None:
177
+ result = _run_git(repo, ["show", f":{stage}:{relative_path}"], binary=True)
178
+ return result.stdout if result.returncode == 0 else None
179
+
180
+
181
+ def _safe_runtime_dir(repo: Path, runtime_dir: Path | str | None) -> Path:
182
+ if runtime_dir:
183
+ target = Path(runtime_dir).resolve()
184
+ else:
185
+ repo_key = str(abs(hash(str(repo).lower())))
186
+ target = Path(tempfile.gettempdir()) / "xlmerge" / repo_key
187
+ target.mkdir(parents=True, exist_ok=True)
188
+ return target
189
+
190
+
191
+ def _slug(relative_path: str) -> str:
192
+ safe = "".join(ch if ch.isalnum() or ch in "-_." else "_" for ch in relative_path)
193
+ return safe[-120:] or "workbook"
194
+
195
+
196
+ def _json_value(value: Any) -> Any:
197
+ if value is None or isinstance(value, (bool, int, float, str)):
198
+ return value
199
+ if isinstance(value, (datetime, date, time)):
200
+ return value.isoformat()
201
+ return str(value)
202
+
203
+
204
+ def _cell_token(cell, cached_cell=None) -> tuple[Any, str] | None:
205
+ if cell is None or isinstance(cell, MergedCell):
206
+ return None
207
+ # 公式 cell 按缓存值参与比较,避免公式不变但引用值变了被误判为 same
208
+ if cell.data_type == 'f' and cached_cell is not None and not isinstance(cached_cell, MergedCell):
209
+ return cached_cell.value, cached_cell.data_type
210
+ return cell.value, cell.data_type
211
+
212
+
213
+ def _cell_display_value(cell, cached_cell) -> Any:
214
+ """UI 展示值:公式 cell 取缓存值,其余取原始值。"""
215
+ if cell is None or isinstance(cell, MergedCell):
216
+ return None
217
+ if cell.data_type == 'f' and cached_cell is not None and not isinstance(cached_cell, MergedCell):
218
+ return cached_cell.value
219
+ return cell.value
220
+
221
+
222
+ def _value_cells(ws) -> dict[tuple[int, int], Any]:
223
+ if ws is None:
224
+ return {}
225
+ result = {}
226
+ for key, cell in ws._cells.items():
227
+ if isinstance(cell, MergedCell):
228
+ continue
229
+ if cell.value is not None:
230
+ result[key] = cell
231
+ return result
232
+
233
+
234
+ def _sheet_values(ws) -> dict[tuple[int, int], tuple[Any, str] | None]:
235
+ return {key: _cell_token(cell) for key, cell in _value_cells(ws).items()}
236
+
237
+
238
+ def _sheet_equal(left, right) -> bool:
239
+ return _sheet_values(left) == _sheet_values(right)
240
+
241
+
242
+ def _ordered_sheet_names(*workbooks) -> list[str]:
243
+ names: list[str] = []
244
+ for workbook in workbooks:
245
+ if workbook is None:
246
+ continue
247
+ for name in workbook.sheetnames:
248
+ if name not in names:
249
+ names.append(name)
250
+ return names
251
+
252
+
253
+ def _context_rows(ws, ws_v, rows: set[int], max_col: int) -> dict[str, list[Any]]:
254
+ if ws is None or max_col <= 0:
255
+ return {}
256
+ header_rows: set[int] = set()
257
+ for row in range(1, min(max(ws.max_row or 1, 1), 20) + 1):
258
+ value = ws.cell(row, 1).value
259
+ if isinstance(value, str) and value.startswith("##"):
260
+ header_rows.add(row)
261
+ elif header_rows:
262
+ break
263
+ wanted = sorted(rows | header_rows)
264
+ return {
265
+ str(row): [_json_value(_cell_display_value(
266
+ ws.cell(row, col),
267
+ ws_v.cell(row, col) if ws_v is not None else None
268
+ )) for col in range(1, max_col + 1)]
269
+ for row in wanted
270
+ }
271
+
272
+
273
+ def _modified_sheet_diff(name, ws_base, ws_ours, ws_theirs,
274
+ ws_base_v=None, ws_ours_v=None, ws_theirs_v=None) -> dict[str, Any]:
275
+ base_cells = _value_cells(ws_base)
276
+ ours_cells = _value_cells(ws_ours)
277
+ theirs_cells = _value_cells(ws_theirs)
278
+ coordinates = sorted(set(base_cells) | set(ours_cells) | set(theirs_cells))
279
+ cells: list[dict[str, Any]] = []
280
+ changed_rows: set[int] = set()
281
+
282
+ for row, col in coordinates:
283
+ base_cell = base_cells.get((row, col))
284
+ ours_cell = ours_cells.get((row, col))
285
+ theirs_cell = theirs_cells.get((row, col))
286
+ base_cached = ws_base_v.cell(row, col) if ws_base_v is not None else None
287
+ ours_cached = ws_ours_v.cell(row, col) if ws_ours_v is not None else None
288
+ theirs_cached = ws_theirs_v.cell(row, col) if ws_theirs_v is not None else None
289
+ base_token = _cell_token(base_cell, base_cached)
290
+ ours_token = _cell_token(ours_cell, ours_cached)
291
+ theirs_token = _cell_token(theirs_cell, theirs_cached)
292
+ if ours_token == theirs_token:
293
+ continue
294
+ if ours_token == base_token:
295
+ resolution = "theirs"
296
+ elif theirs_token == base_token:
297
+ resolution = "ours"
298
+ else:
299
+ resolution = "conflict"
300
+ changed_rows.add(row)
301
+ cells.append({
302
+ "row": row,
303
+ "col": col,
304
+ "coordinate": f"{get_column_letter(col)}{row}",
305
+ "base": _json_value(_cell_display_value(base_cell, base_cached)),
306
+ "ours": _json_value(_cell_display_value(ours_cell, ours_cached)),
307
+ "theirs": _json_value(_cell_display_value(theirs_cell, theirs_cached)),
308
+ "resolution": resolution,
309
+ })
310
+
311
+ preferred_ws = ws_ours or ws_theirs or ws_base
312
+ preferred_ws_v = ws_ours_v or ws_theirs_v or ws_base_v
313
+ max_col = max([col for _, col in coordinates] or [1])
314
+ return {
315
+ "name": name,
316
+ "action": "merge",
317
+ "cells": cells,
318
+ "contextRows": _context_rows(preferred_ws, preferred_ws_v, changed_rows, max_col),
319
+ "maxCol": max_col,
320
+ "changedCount": len(cells),
321
+ "conflictCount": sum(cell["resolution"] == "conflict" for cell in cells),
322
+ }
323
+
324
+
325
+ def _axis_state(status: str, *, ours_present: bool) -> dict[str, Any]:
326
+ if status.startswith("added_"):
327
+ return {
328
+ "state": "added",
329
+ "locked": True,
330
+ "incoming": status == "added_theirs",
331
+ "default": "keep",
332
+ }
333
+ if status.startswith("delete_modify_"):
334
+ return {
335
+ "state": "delete_modify",
336
+ "locked": False,
337
+ "incoming": False,
338
+ "default": "keep" if ours_present else "delete",
339
+ }
340
+ if status.startswith("deleted_"):
341
+ return {
342
+ "state": "deleted",
343
+ "locked": True,
344
+ "incoming": False,
345
+ "default": "delete",
346
+ }
347
+ return {"state": "common", "locked": False, "incoming": False, "default": "keep"}
348
+
349
+
350
+ def _side_cell(workbook, sheet_name: str | None, row: int | None, column: int | None):
351
+ if workbook is None or sheet_name is None or row is None or column is None:
352
+ return None
353
+ return workbook[sheet_name].cell(row, column)
354
+
355
+
356
+ def _cell_resolution(base_cell, ours_cell, theirs_cell, *, has_base: bool,
357
+ base_cached=None, ours_cached=None, theirs_cached=None) -> str:
358
+ base_token = _cell_token(base_cell, base_cached)
359
+ ours_token = _cell_token(ours_cell, ours_cached)
360
+ theirs_token = _cell_token(theirs_cell, theirs_cached)
361
+ if not has_base:
362
+ return "theirs" if theirs_cell is not None else "ours"
363
+ if ours_token == theirs_token:
364
+ return "same"
365
+ if ours_token == base_token:
366
+ return "theirs"
367
+ if theirs_token == base_token:
368
+ return "ours"
369
+ return "conflict"
370
+
371
+
372
+ def _header_rows(ws) -> list[int]:
373
+ if ws is None:
374
+ return []
375
+ rows = []
376
+ for row in range(1, min(ws.max_row or 0, 40) + 1):
377
+ marker = ws.cell(row, 1).value
378
+ if isinstance(marker, str) and marker.startswith("##"):
379
+ rows.append(row)
380
+ elif rows:
381
+ break
382
+ return rows
383
+
384
+
385
+ def _merged_region_key(region: dict[str, Any]) -> tuple[tuple[str, ...], tuple[str, ...]]:
386
+ return tuple(region["rows"]), tuple(region["columns"])
387
+
388
+
389
+ def _canonical_merged_regions(ws, side: str, rows, columns) -> list[dict[str, Any]]:
390
+ if ws is None:
391
+ return []
392
+ header_rows = set(_header_rows(ws))
393
+ row_lookup = {
394
+ row.get(f"{side}Row"): row["id"]
395
+ for row in rows
396
+ if row.get(f"{side}Row") is not None
397
+ }
398
+ column_lookup = {
399
+ column.get(f"{side}Col"): column["id"]
400
+ for column in columns
401
+ if column.get(f"{side}Col") is not None
402
+ }
403
+ regions = []
404
+ for merged_range in ws.merged_cells.ranges:
405
+ row_ids = []
406
+ for row_number in range(merged_range.min_row, merged_range.max_row + 1):
407
+ row_id = f"header:{row_number}" if row_number in header_rows else row_lookup.get(row_number)
408
+ if row_id is None:
409
+ break
410
+ row_ids.append(row_id)
411
+ else:
412
+ column_ids = []
413
+ for column_number in range(merged_range.min_col, merged_range.max_col + 1):
414
+ column_id = column_lookup.get(column_number)
415
+ if column_id is None:
416
+ break
417
+ column_ids.append(column_id)
418
+ else:
419
+ regions.append({"rows": row_ids, "columns": column_ids})
420
+ return sorted(regions, key=_merged_region_key)
421
+
422
+
423
+ def _regions_overlap(regions: list[dict[str, Any]]) -> bool:
424
+ occupied: set[tuple[str, str]] = set()
425
+ for region in regions:
426
+ cells = {(row, column) for row in region["rows"] for column in region["columns"]}
427
+ if occupied & cells:
428
+ return True
429
+ occupied.update(cells)
430
+ return False
431
+
432
+
433
+ def _merged_cells_diff(names, rows, columns, wb_base, wb_ours, wb_theirs) -> dict[str, Any]:
434
+ workbooks = {"base": wb_base, "ours": wb_ours, "theirs": wb_theirs}
435
+ regions = {}
436
+ for side, workbook in workbooks.items():
437
+ sheet_name = names.get(side)
438
+ ws = workbook[sheet_name] if workbook is not None and sheet_name in workbook.sheetnames else None
439
+ regions[side] = _canonical_merged_regions(ws, side, rows, columns)
440
+
441
+ keyed = {side: {_merged_region_key(item): item for item in items} for side, items in regions.items()}
442
+ base_keys, ours_keys, theirs_keys = (set(keyed[side]) for side in ("base", "ours", "theirs"))
443
+ if ours_keys == theirs_keys:
444
+ status, resolved = "same", regions["ours"]
445
+ elif ours_keys == base_keys:
446
+ status, resolved = "auto_theirs", regions["theirs"]
447
+ elif theirs_keys == base_keys:
448
+ status, resolved = "auto_ours", regions["ours"]
449
+ else:
450
+ all_keys = base_keys | ours_keys | theirs_keys
451
+ resolved_keys = set()
452
+ for key in all_keys:
453
+ base_present = key in base_keys
454
+ ours_present = key in ours_keys
455
+ theirs_present = key in theirs_keys
456
+ if ours_present == theirs_present:
457
+ keep = ours_present
458
+ elif ours_present == base_present:
459
+ keep = theirs_present
460
+ else:
461
+ keep = ours_present
462
+ if keep:
463
+ resolved_keys.add(key)
464
+ source_items = {**keyed["base"], **keyed["ours"], **keyed["theirs"]}
465
+ candidate = [source_items[key] for key in sorted(resolved_keys)]
466
+ if _regions_overlap(candidate):
467
+ status, resolved = "conflict", []
468
+ else:
469
+ status, resolved = "auto_merge", candidate
470
+ return {
471
+ "status": status,
472
+ "default": "ours" if status == "conflict" else None,
473
+ "base": regions["base"],
474
+ "ours": regions["ours"],
475
+ "theirs": regions["theirs"],
476
+ "resolved": resolved,
477
+ }
478
+
479
+
480
+ def _structural_sheet_diff(report_sheet, wb_base, wb_ours, wb_theirs,
481
+ wb_base_v=None, wb_ours_v=None, wb_theirs_v=None) -> dict[str, Any]:
482
+ names = report_sheet.get("names") or {
483
+ "base": report_sheet["name"], "ours": report_sheet["name"], "theirs": report_sheet["name"]
484
+ }
485
+ rows = []
486
+ for index, entry in enumerate(report_sheet.get("rowAlignment") or [], 1):
487
+ item = dict(entry)
488
+ item.update(_axis_state(entry["status"], ours_present=entry.get("oursRow") is not None))
489
+ item["display"] = entry.get("oursRow") or entry.get("baseRow") or entry.get("theirsRow") or index
490
+ rows.append(item)
491
+ columns = []
492
+ for index, entry in enumerate(report_sheet.get("columnAlignment") or [], 1):
493
+ item = dict(entry)
494
+ item["id"] = entry["field"]
495
+ item.update(_axis_state(entry["status"], ours_present=entry.get("oursColumn") is not None))
496
+ item["baseCol"] = column_index_from_string(entry["baseColumn"]) if entry.get("baseColumn") else None
497
+ item["oursCol"] = column_index_from_string(entry["oursColumn"]) if entry.get("oursColumn") else None
498
+ item["theirsCol"] = column_index_from_string(entry["theirsColumn"]) if entry.get("theirsColumn") else None
499
+ item["display"] = entry.get("oursColumn") or entry.get("baseColumn") or entry.get("theirsColumn") or get_column_letter(index)
500
+ columns.append(item)
501
+
502
+ all_cells: list[dict[str, Any]] = []
503
+ changed_row_ids: set[str] = set()
504
+ row_attention: set[str] = set()
505
+ for row in rows:
506
+ for column in columns:
507
+ base_cell = _side_cell(wb_base, names.get("base"), row.get("baseRow"), column.get("baseCol"))
508
+ ours_cell = _side_cell(wb_ours, names.get("ours"), row.get("oursRow"), column.get("oursCol"))
509
+ theirs_cell = _side_cell(wb_theirs, names.get("theirs"), row.get("theirsRow"), column.get("theirsCol"))
510
+ base_cached = _side_cell(wb_base_v, names.get("base"), row.get("baseRow"), column.get("baseCol")) if wb_base_v else None
511
+ ours_cached = _side_cell(wb_ours_v, names.get("ours"), row.get("oursRow"), column.get("oursCol")) if wb_ours_v else None
512
+ theirs_cached = _side_cell(wb_theirs_v, names.get("theirs"), row.get("theirsRow"), column.get("theirsCol")) if wb_theirs_v else None
513
+ base_token = _cell_token(base_cell, base_cached)
514
+ ours_token = _cell_token(ours_cell, ours_cached)
515
+ theirs_token = _cell_token(theirs_cell, theirs_cached)
516
+ has_base = row.get("baseRow") is not None and column.get("baseCol") is not None
517
+ changed = not (ours_token == theirs_token == base_token)
518
+ structural = row["state"] != "common" or column["state"] != "common"
519
+ selectable = (
520
+ row["state"] in ("common", "delete_modify")
521
+ and column["state"] in ("common", "delete_modify")
522
+ )
523
+ if changed or structural:
524
+ changed_row_ids.add(row["id"])
525
+ resolution = _cell_resolution(base_cell, ours_cell, theirs_cell, has_base=has_base,
526
+ base_cached=base_cached, ours_cached=ours_cached, theirs_cached=theirs_cached)
527
+ if changed and resolution != "same":
528
+ row_attention.add(row["id"])
529
+ stable_id = f'{row["id"]}|{column["id"]}'
530
+ display_coordinate = (
531
+ f'{get_column_letter(column["oursCol"])}{row["oursRow"]}'
532
+ if row.get("oursRow") is not None and column.get("oursCol") is not None
533
+ else stable_id
534
+ )
535
+ all_cells.append({
536
+ "id": stable_id,
537
+ "coordinate": display_coordinate,
538
+ "rowId": row["id"],
539
+ "colId": column["id"],
540
+ "base": _json_value(_cell_display_value(base_cell, base_cached)),
541
+ "ours": _json_value(_cell_display_value(ours_cell, ours_cached)),
542
+ "theirs": _json_value(_cell_display_value(theirs_cell, theirs_cached)),
543
+ "basePresent": base_cell is not None,
544
+ "oursPresent": ours_cell is not None,
545
+ "theirsPresent": theirs_cell is not None,
546
+ "resolution": resolution,
547
+ "changed": changed,
548
+ "structural": structural,
549
+ "selectable": selectable,
550
+ })
551
+
552
+ # 只显示需要关注的行:结构变化行 + 含非 same(需决策/有变化信息)cell 的行
553
+ visible_rows = [
554
+ row for row in rows
555
+ if row["state"] != "common" or row["id"] in row_attention
556
+ ]
557
+ visible_ids = {row["id"] for row in visible_rows}
558
+ grid_cells = [cell for cell in all_cells if cell["rowId"] in visible_ids]
559
+ cells = [cell for cell in grid_cells if cell["changed"]]
560
+ decision_cell_count = sum(cell["changed"] and cell["selectable"] for cell in cells)
561
+ preferred_ws = None
562
+ for workbook, key in ((wb_ours, "ours"), (wb_theirs, "theirs"), (wb_base, "base")):
563
+ if workbook is not None and names.get(key) in workbook.sheetnames:
564
+ preferred_ws = workbook[names[key]]
565
+ break
566
+ header_rows = []
567
+ for row_number in _header_rows(preferred_ws):
568
+ header_rows.append({
569
+ "row": row_number,
570
+ "cells": [
571
+ _json_value(preferred_ws.cell(row_number, column.get("oursCol") or column.get("theirsCol") or column.get("baseCol")).value)
572
+ for column in columns
573
+ ],
574
+ })
575
+ merged_cells = _merged_cells_diff(names, rows, columns, wb_base, wb_ours, wb_theirs)
576
+ merged_cells_conflict = merged_cells["status"] == "conflict"
577
+ structural_conflicts = (
578
+ sum(axis["state"] == "delete_modify" for axis in [*rows, *columns])
579
+ + int(merged_cells_conflict)
580
+ )
581
+ rebuild_required = (
582
+ any(axis["state"] != "common" for axis in [*rows, *columns])
583
+ or any(cell["changed"] for cell in all_cells)
584
+ or merged_cells["status"] != "same"
585
+ )
586
+ selectable_cells = [
587
+ cell for cell in cells
588
+ if cell["changed"] and cell["resolution"] == "conflict"
589
+ and next(row for row in rows if row["id"] == cell["rowId"])["state"] == "common"
590
+ and next(column for column in columns if column["id"] == cell["colId"])["state"] == "common"
591
+ ]
592
+ return {
593
+ "name": report_sheet["name"],
594
+ "names": names,
595
+ "renameStatus": report_sheet.get("renameStatus", "unchanged"),
596
+ "action": "merge",
597
+ "rows": visible_rows,
598
+ "allRows": rows,
599
+ "columns": columns,
600
+ "cells": cells,
601
+ "gridCells": grid_cells,
602
+ "allCells": all_cells,
603
+ "headerRows": header_rows,
604
+ "mergedCells": merged_cells,
605
+ "rebuildRequired": rebuild_required,
606
+ "maxCol": len(columns),
607
+ "changedCount": decision_cell_count,
608
+ "decisionCellCount": decision_cell_count,
609
+ "rawChangedCellCount": sum(cell["changed"] for cell in cells),
610
+ "conflictCount": len(selectable_cells),
611
+ "structuralConflictCount": structural_conflicts,
612
+ "needsAttention": bool(selectable_cells) or structural_conflicts > 0
613
+ or report_sheet.get("renameStatus") == "rename_conflict",
614
+ }
615
+
616
+
617
+ def diff_workbooks(
618
+ base_path: Path | str | None,
619
+ ours_path: Path | str,
620
+ theirs_path: Path | str,
621
+ *,
622
+ analysis_dir: Path | str | None = None,
623
+ skip_hidden_sheets: bool = True,
624
+ ) -> dict[str, Any]:
625
+ wb_base = load_workbook(base_path, data_only=False, keep_links=True) if base_path else None
626
+ wb_ours = load_workbook(ours_path, data_only=False, keep_links=True)
627
+ wb_theirs = load_workbook(theirs_path, data_only=False, keep_links=True)
628
+ wb_base_v = load_workbook(base_path, data_only=True, keep_links=True) if base_path else None
629
+ wb_ours_v = load_workbook(ours_path, data_only=True, keep_links=True)
630
+ wb_theirs_v = load_workbook(theirs_path, data_only=True, keep_links=True)
631
+ try:
632
+ if base_path is not None:
633
+ structural_dir = Path(analysis_dir) if analysis_dir else Path(tempfile.mkdtemp(prefix="xlsx-merge-analysis-"))
634
+ structural = analyze_structural_workbooks(
635
+ base_path, ours_path, theirs_path, structural_dir,
636
+ write_sidecars=False, skip_hidden_sheets=skip_hidden_sheets,
637
+ )
638
+ sheets = []
639
+ for report_sheet in structural["sheets"]:
640
+ if report_sheet["action"] == "merge":
641
+ sheets.append(_structural_sheet_diff(
642
+ report_sheet, wb_base, wb_ours, wb_theirs,
643
+ wb_base_v, wb_ours_v, wb_theirs_v,
644
+ ))
645
+ continue
646
+ names = report_sheet.get("names") or {}
647
+ if not names.get("base"):
648
+ if names.get("ours") and names.get("theirs"):
649
+ action = "auto_add_theirs"
650
+ else:
651
+ action = "auto_add_ours" if names.get("ours") else "auto_add_theirs"
652
+ elif report_sheet.get("status") == "conflict":
653
+ conflict_kind = (report_sheet.get("sheetConflict") or {}).get("kind", "")
654
+ if conflict_kind.startswith("delete_modify_"):
655
+ action = f'conflict_delete_{conflict_kind.rsplit("_", 1)[-1]}'
656
+ else:
657
+ action = "conflict_sheet_structure"
658
+ else:
659
+ action = "auto_delete"
660
+ sheets.append({
661
+ "name": report_sheet["name"],
662
+ "names": names,
663
+ "renameStatus": report_sheet.get("renameStatus", "unchanged"),
664
+ "action": action,
665
+ "sheetConflict": report_sheet.get("sheetConflict"),
666
+ "cells": [],
667
+ "rows": [],
668
+ "allRows": [],
669
+ "columns": [],
670
+ "headerRows": [],
671
+ "maxCol": 0,
672
+ "changedCount": 0,
673
+ "conflictCount": 0,
674
+ "structuralConflictCount": int(action.startswith("conflict_")),
675
+ "needsAttention": action.startswith("conflict_"),
676
+ })
677
+ return {
678
+ "engineVersion": structural["version"],
679
+ "sheets": sheets,
680
+ "summary": {
681
+ "sheetCount": len(sheets),
682
+ "changedCellCount": sum(sheet["changedCount"] for sheet in sheets),
683
+ "cellConflictCount": sum(sheet["conflictCount"] for sheet in sheets),
684
+ "structuralConflictCount": sum(sheet.get("structuralConflictCount", 0) for sheet in sheets),
685
+ "sheetConflictCount": structural["summary"].get("sheetConflictCount", 0),
686
+ },
687
+ }
688
+
689
+ sheets: list[dict[str, Any]] = []
690
+ for name in _ordered_sheet_names(wb_base, wb_ours, wb_theirs):
691
+ base_exists = wb_base is not None and name in wb_base.sheetnames
692
+ ours_exists = name in wb_ours.sheetnames
693
+ theirs_exists = name in wb_theirs.sheetnames
694
+ ws_base = wb_base[name] if base_exists else None
695
+ ws_ours = wb_ours[name] if ours_exists else None
696
+ ws_theirs = wb_theirs[name] if theirs_exists else None
697
+ ws_base_v = wb_base_v[name] if base_exists else None
698
+ ws_ours_v = wb_ours_v[name] if ours_exists else None
699
+ ws_theirs_v = wb_theirs_v[name] if theirs_exists else None
700
+
701
+ if ours_exists and theirs_exists:
702
+ sheet = _modified_sheet_diff(name, ws_base, ws_ours, ws_theirs,
703
+ ws_base_v, ws_ours_v, ws_theirs_v)
704
+ if sheet["changedCount"]:
705
+ sheets.append(sheet)
706
+ continue
707
+ if not base_exists:
708
+ source = "ours" if ours_exists else "theirs"
709
+ sheets.append({
710
+ "name": name,
711
+ "action": f"auto_add_{source}",
712
+ "cells": [],
713
+ "contextRows": {},
714
+ "maxCol": 0,
715
+ "changedCount": 0,
716
+ "conflictCount": 0,
717
+ })
718
+ continue
719
+ if not ours_exists and not theirs_exists:
720
+ sheets.append({
721
+ "name": name,
722
+ "action": "auto_delete",
723
+ "cells": [],
724
+ "contextRows": {},
725
+ "maxCol": 0,
726
+ "changedCount": 0,
727
+ "conflictCount": 0,
728
+ })
729
+ continue
730
+
731
+ existing_ws = ws_ours or ws_theirs
732
+ missing_side = "theirs" if ours_exists else "ours"
733
+ if _sheet_equal(ws_base, existing_ws):
734
+ action = "auto_delete"
735
+ conflict_count = 0
736
+ else:
737
+ action = f"conflict_delete_{missing_side}"
738
+ conflict_count = 1
739
+ sheets.append({
740
+ "name": name,
741
+ "action": action,
742
+ "cells": [],
743
+ "contextRows": {},
744
+ "maxCol": 0,
745
+ "changedCount": 0,
746
+ "conflictCount": conflict_count,
747
+ })
748
+
749
+ return {
750
+ "sheets": sheets,
751
+ "summary": {
752
+ "sheetCount": len(sheets),
753
+ "changedCellCount": sum(sheet["changedCount"] for sheet in sheets),
754
+ "cellConflictCount": sum(
755
+ sum(cell["resolution"] == "conflict" for cell in sheet["cells"])
756
+ for sheet in sheets
757
+ ),
758
+ "sheetConflictCount": sum(sheet["action"].startswith("conflict_") for sheet in sheets),
759
+ },
760
+ }
761
+ finally:
762
+ if wb_base is not None:
763
+ wb_base.close()
764
+ wb_ours.close()
765
+ wb_theirs.close()
766
+ if wb_base_v is not None:
767
+ wb_base_v.close()
768
+ wb_ours_v.close()
769
+ wb_theirs_v.close()
770
+
771
+
772
+ def _author_and_date(repo: Path, relative_path: str, ref: str) -> tuple[str, str]:
773
+ verify = _run_git(repo, ["rev-parse", "--verify", "--quiet", ref])
774
+ if verify.returncode != 0:
775
+ return "", ""
776
+ result = _run_git(repo, ["log", "-1", "--format=%an|%cI", ref, "--", relative_path])
777
+ if result.returncode != 0 or not result.stdout.strip():
778
+ return "", ""
779
+ parts = result.stdout.strip().split("|", 1)
780
+ if len(parts) != 2:
781
+ return parts[0], ""
782
+ author, iso_date = parts
783
+ # ISO 8601 -> "2000-1-1 8:24"
784
+ try:
785
+ from datetime import datetime
786
+ dt = datetime.fromisoformat(iso_date)
787
+ date_str = f"{dt.year}-{dt.month}-{dt.day} {dt.hour}:{dt.minute:02d}"
788
+ except (ValueError, TypeError):
789
+ date_str = ""
790
+ return author, date_str
791
+
792
+
793
+ def _author(repo: Path, relative_path: str, ref: str) -> str:
794
+ author, _ = _author_and_date(repo, relative_path, ref)
795
+ return author
796
+
797
+
798
+ def _theirs_author(repo: Path, relative_path: str) -> str:
799
+ for ref in ("MERGE_HEAD", "CHERRY_PICK_HEAD", "REBASE_HEAD"):
800
+ author = _author(repo, relative_path, ref)
801
+ if author:
802
+ return author
803
+ return ""
804
+
805
+
806
+ def _ours_date(repo: Path, relative_path: str) -> str:
807
+ _, date_str = _author_and_date(repo, relative_path, "HEAD")
808
+ return date_str
809
+
810
+
811
+ def _theirs_date(repo: Path, relative_path: str) -> str:
812
+ for ref in ("MERGE_HEAD", "CHERRY_PICK_HEAD", "REBASE_HEAD"):
813
+ _, date_str = _author_and_date(repo, relative_path, ref)
814
+ if date_str:
815
+ return date_str
816
+ return ""
817
+
818
+
819
+ def prepare_conflicts(
820
+ repo: Path | str,
821
+ *,
822
+ relative_path: str | None = None,
823
+ runtime_dir: Path | str | None = None,
824
+ ) -> Path:
825
+ repo_root = find_repo_root(repo)
826
+ conflicts = detect_conflicts(repo_root)
827
+ if relative_path:
828
+ normalized = relative_path.replace("\\", "/")
829
+ conflicts = [item for item in conflicts if item["path"] == normalized]
830
+ if not conflicts:
831
+ raise ConflictError("No unresolved .xlsx/.xlsm conflicts were found.")
832
+
833
+ target_dir = _safe_runtime_dir(repo_root, runtime_dir)
834
+ prepared_files = []
835
+ for item in conflicts:
836
+ path = item["path"]
837
+ ours_blob = _git_blob(repo_root, 2, path)
838
+ theirs_blob = _git_blob(repo_root, 3, path)
839
+ if ours_blob is None or theirs_blob is None:
840
+ raise ConflictError(
841
+ f"{path} is a delete/modify conflict. This resolver currently requires both workbook versions."
842
+ )
843
+ base_blob = _git_blob(repo_root, 1, path)
844
+ extension = Path(path).suffix.lower()
845
+ macro = None
846
+ if extension == ".xlsm":
847
+ macro = _macro_payload_info(base_blob, ours_blob, theirs_blob)
848
+ work_dir = target_dir / _slug(path)
849
+ work_dir.mkdir(parents=True, exist_ok=True)
850
+ ours_path = work_dir / f"ours{extension}"
851
+ theirs_path = work_dir / f"theirs{extension}"
852
+ base_path = work_dir / f"base{extension}"
853
+ ours_path.write_bytes(ours_blob)
854
+ theirs_path.write_bytes(theirs_blob)
855
+ if base_blob is not None:
856
+ base_path.write_bytes(base_blob)
857
+ elif base_path.exists():
858
+ base_path.unlink()
859
+ workbook_diff = diff_workbooks(
860
+ base_path if base_blob is not None else None,
861
+ ours_path,
862
+ theirs_path,
863
+ analysis_dir=work_dir / "analysis",
864
+ )
865
+ prepared_files.append({
866
+ "id": path,
867
+ "path": path,
868
+ "base": str(base_path) if base_blob is not None else None,
869
+ "ours": str(ours_path),
870
+ "theirs": str(theirs_path),
871
+ "output": str((repo_root / Path(path)).resolve()),
872
+ "oursAuthor": _author(repo_root, path, "HEAD"),
873
+ "theirsAuthor": _theirs_author(repo_root, path),
874
+ "oursDate": _ours_date(repo_root, path),
875
+ "theirsDate": _theirs_date(repo_root, path),
876
+ "macro": macro,
877
+ "diff": workbook_diff,
878
+ })
879
+
880
+ manifest = {
881
+ "version": 3,
882
+ "repoRoot": str(repo_root),
883
+ "files": prepared_files,
884
+ "summary": {
885
+ "fileCount": len(prepared_files),
886
+ "cellConflictCount": sum(f["diff"]["summary"]["cellConflictCount"] for f in prepared_files),
887
+ "sheetConflictCount": sum(f["diff"]["summary"]["sheetConflictCount"] for f in prepared_files),
888
+ "structuralConflictCount": sum(f["diff"]["summary"].get("structuralConflictCount", 0) for f in prepared_files),
889
+ },
890
+ }
891
+ manifest_path = target_dir / "manifest.json"
892
+ manifest_path.write_text(json.dumps(manifest, ensure_ascii=False, indent=2), encoding="utf-8")
893
+ return manifest_path
894
+
895
+
896
+ def load_manifest(path: Path | str) -> dict[str, Any]:
897
+ manifest_path = Path(path).resolve()
898
+ data = json.loads(manifest_path.read_text(encoding="utf-8"))
899
+ if data.get("version") != 3 or not isinstance(data.get("files"), list):
900
+ raise ConflictError(f"Unsupported manifest: {manifest_path}")
901
+ return data
902
+
903
+
904
+ def _copy_cell(source, target) -> None:
905
+ target.value = source.value
906
+ if source.has_style:
907
+ if source.parent is not None and source.parent.parent is target.parent.parent:
908
+ # 同 workbook:样式表索引通用,浅拷贝 StyleArray 避免对象复制(大表 40 万+ 格)
909
+ target._style = copy(source._style)
910
+ else:
911
+ target.font = copy(source.font)
912
+ target.fill = copy(source.fill)
913
+ target.border = copy(source.border)
914
+ target.alignment = copy(source.alignment)
915
+ target.number_format = source.number_format
916
+ target.protection = copy(source.protection)
917
+ target.hyperlink = source.hyperlink
918
+ target.comment = source.comment
919
+
920
+
921
+ def _copy_sheet(source_ws, target_wb, *, index: int | None = None):
922
+ target_ws = target_wb.create_sheet(source_ws.title, index=index)
923
+ for row in source_ws.iter_rows():
924
+ for source_cell in row:
925
+ if isinstance(source_cell, MergedCell):
926
+ continue
927
+ _copy_cell(source_cell, target_ws.cell(source_cell.row, source_cell.column))
928
+ for key, dimension in source_ws.column_dimensions.items():
929
+ target_ws.column_dimensions[key] = copy(dimension)
930
+ target_ws.column_dimensions[key].worksheet = target_ws
931
+ for key, dimension in source_ws.row_dimensions.items():
932
+ target_ws.row_dimensions[key] = copy(dimension)
933
+ target_ws.row_dimensions[key].worksheet = target_ws
934
+ for merged_range in source_ws.merged_cells.ranges:
935
+ target_ws.merge_cells(str(merged_range))
936
+ target_ws.views = copy(source_ws.views)
937
+ target_ws.sheet_format = copy(source_ws.sheet_format)
938
+ target_ws.sheet_properties = copy(source_ws.sheet_properties)
939
+ target_ws.page_margins = copy(source_ws.page_margins)
940
+ target_ws.page_setup = copy(source_ws.page_setup)
941
+ target_ws.print_options = copy(source_ws.print_options)
942
+ target_ws.auto_filter.ref = source_ws.auto_filter.ref
943
+ target_ws.sheet_state = source_ws.sheet_state
944
+ return target_ws
945
+
946
+
947
+ def _replace_sheet(target_wb, source_ws, order: list[str]) -> None:
948
+ if source_ws.title in target_wb.sheetnames:
949
+ index = target_wb.sheetnames.index(source_ws.title)
950
+ target_wb.remove(target_wb[source_ws.title])
951
+ else:
952
+ desired = order.index(source_ws.title) if source_ws.title in order else len(target_wb.sheetnames)
953
+ index = min(desired, len(target_wb.sheetnames))
954
+ _copy_sheet(source_ws, target_wb, index=index)
955
+
956
+
957
+ def _file_decisions(decisions: dict[str, Any], file_id: str) -> dict[str, Any]:
958
+ return ((decisions.get("files") or {}).get(file_id) or {})
959
+
960
+
961
+ def _cell_choice(cell_choices: dict[str, Any], cell: dict[str, Any]) -> Any:
962
+ return cell_choices.get(cell.get("id"), cell_choices.get(cell.get("coordinate")))
963
+
964
+
965
+ def _validate_decisions(manifest: dict[str, Any], decisions: dict[str, Any]) -> None:
966
+ missing: list[str] = []
967
+ for file_entry in manifest["files"]:
968
+ file_choice = _file_decisions(decisions, file_entry["id"])
969
+ macro = file_entry.get("macro") or {}
970
+ macro_choice = file_choice.get("macro", macro.get("default"))
971
+ if macro.get("status") == "conflict" and macro_choice not in ("ours", "theirs"):
972
+ missing.append(f"{file_entry['path']} / <VBA/ActiveX>")
973
+ if macro_choice == "theirs" and not macro.get("canChooseTheirs", True):
974
+ raise ConflictError(
975
+ f"{file_entry['path']} has incompatible LOCAL and REMOTE VBA/ActiveX package structures; "
976
+ "only the LOCAL macro payload can be preserved safely."
977
+ )
978
+ sheet_choices = file_choice.get("sheets") or {}
979
+ for sheet in file_entry["diff"]["sheets"]:
980
+ choice = sheet_choices.get(sheet["name"]) or {}
981
+ if sheet["action"].startswith("conflict_") and choice.get("sheet") not in ("ours", "theirs"):
982
+ missing.append(f"{file_entry['path']} / {sheet['name']} / <sheet>")
983
+ if sheet.get("renameStatus") == "rename_conflict" and choice.get("rename") not in ("ours", "theirs"):
984
+ missing.append(f"{file_entry['path']} / {sheet['name']} / <rename>")
985
+ if (sheet.get("mergedCells") or {}).get("status") == "conflict" and choice.get("mergedCells") not in ("ours", "theirs"):
986
+ missing.append(f"{file_entry['path']} / {sheet['name']} / <merged-cells>")
987
+ row_choices = choice.get("rows") or {}
988
+ for row in sheet.get("allRows") or sheet.get("rows") or []:
989
+ if row.get("state") == "delete_modify" and row_choices.get(row["id"]) not in ("keep", "delete"):
990
+ missing.append(f"{file_entry['path']} / {sheet['name']} / {row['id']}")
991
+ column_choices = choice.get("columns") or {}
992
+ for column in sheet.get("columns") or []:
993
+ if column.get("state") == "delete_modify" and column_choices.get(column["id"]) not in ("keep", "delete"):
994
+ missing.append(f"{file_entry['path']} / {sheet['name']} / {column['id']}")
995
+ cell_choices = choice.get("cells") or {}
996
+ for cell in sheet["cells"]:
997
+ if cell["resolution"] == "conflict" and _cell_choice(cell_choices, cell) not in ("ours", "theirs"):
998
+ missing.append(f"{file_entry['path']} / {sheet['name']} / {cell['coordinate']}")
999
+ if missing:
1000
+ preview = "\n".join(f"- {item}" for item in missing[:20])
1001
+ suffix = f"\n... and {len(missing) - 20} more" if len(missing) > 20 else ""
1002
+ raise ConflictError(f"Unresolved choices remain:\n{preview}{suffix}")
1003
+
1004
+
1005
+ def _copy_sheet_properties(source_ws, target_ws) -> None:
1006
+ # freeze_panes only exposes topLeftCell. Reassigning it turns a scrolled
1007
+ # viewport such as topLeftCell=D857/ySplit=4 into a 856-row freeze.
1008
+ target_ws.views = copy(source_ws.views)
1009
+ target_ws.sheet_format = copy(source_ws.sheet_format)
1010
+ target_ws.sheet_properties = copy(source_ws.sheet_properties)
1011
+ target_ws.page_margins = copy(source_ws.page_margins)
1012
+ target_ws.page_setup = copy(source_ws.page_setup)
1013
+ target_ws.print_options = copy(source_ws.print_options)
1014
+ target_ws.auto_filter.ref = source_ws.auto_filter.ref
1015
+ target_ws.sheet_state = source_ws.sheet_state
1016
+
1017
+
1018
+ def _restore_merged_cells(target_ws, sheet, selection, active_rows, active_columns, header_count) -> None:
1019
+ model = sheet.get("mergedCells") or {}
1020
+ if model.get("status") == "conflict":
1021
+ regions = model.get(selection.get("mergedCells")) or []
1022
+ else:
1023
+ regions = model.get("resolved") or []
1024
+ row_positions = {f"header:{row}": row for row in range(1, header_count + 1)}
1025
+ row_positions.update({row["id"]: header_count + index for index, row in enumerate(active_rows, 1)})
1026
+ column_positions = {column["id"]: index for index, column in enumerate(active_columns, 1)}
1027
+ occupied: set[tuple[int, int]] = set()
1028
+ for region in regions:
1029
+ output_rows = sorted({row_positions[row] for row in region["rows"] if row in row_positions})
1030
+ output_columns = sorted({column_positions[column] for column in region["columns"] if column in column_positions})
1031
+ if not output_rows or not output_columns or len(output_rows) * len(output_columns) < 2:
1032
+ continue
1033
+ if output_rows != list(range(output_rows[0], output_rows[-1] + 1)):
1034
+ raise ConflictError(f"Merged rows are no longer contiguous in {sheet['name']}")
1035
+ if output_columns != list(range(output_columns[0], output_columns[-1] + 1)):
1036
+ raise ConflictError(f"Merged columns are no longer contiguous in {sheet['name']}")
1037
+ cells = {(row, column) for row in output_rows for column in output_columns}
1038
+ if occupied & cells:
1039
+ raise ConflictError(f"Merged regions overlap after alignment in {sheet['name']}")
1040
+ occupied.update(cells)
1041
+ target_ws.merge_cells(
1042
+ start_row=output_rows[0], end_row=output_rows[-1],
1043
+ start_column=output_columns[0], end_column=output_columns[-1],
1044
+ )
1045
+
1046
+
1047
+ def _axis_kept(axis: dict[str, Any], choices: dict[str, Any]) -> bool:
1048
+ if axis.get("state") == "deleted":
1049
+ return False
1050
+ if axis.get("state") == "delete_modify":
1051
+ return choices.get(axis["id"], axis.get("default", "keep")) == "keep"
1052
+ return True
1053
+
1054
+
1055
+ def _source_cell(workbooks, names, row, column, side: str):
1056
+ workbook = workbooks.get(side)
1057
+ sheet_name = names.get(side)
1058
+ row_number = row.get(f"{side}Row")
1059
+ column_number = column.get(f"{side}Col")
1060
+ if workbook is None or sheet_name is None or row_number is None or column_number is None:
1061
+ return None
1062
+ return workbook[sheet_name].cell(row_number, column_number)
1063
+
1064
+
1065
+ def _selected_source_cell(workbooks, names, row, column, cell, choice: str | None):
1066
+ preferred = []
1067
+ if choice in ("ours", "theirs"):
1068
+ preferred.append(choice)
1069
+ elif cell.get("resolution") == "theirs":
1070
+ preferred.append("theirs")
1071
+ elif cell.get("resolution") == "ours":
1072
+ preferred.append("ours")
1073
+ elif cell.get("resolution") == "same":
1074
+ preferred.extend(("ours", "theirs"))
1075
+ else:
1076
+ preferred.append("theirs")
1077
+ preferred.extend(side for side in ("ours", "theirs", "base") if side not in preferred)
1078
+ for side in preferred:
1079
+ source = _source_cell(workbooks, names, row, column, side)
1080
+ if source is not None:
1081
+ return source
1082
+ return None
1083
+
1084
+
1085
+ def _selected_sheet_name(sheet: dict[str, Any], selection: dict[str, Any]) -> str:
1086
+ names = sheet.get("names") or {}
1087
+ if sheet.get("renameStatus") == "rename_conflict":
1088
+ return names[selection["rename"]]
1089
+ return names.get("ours") or names.get("theirs") or names.get("base") or sheet["name"]
1090
+
1091
+
1092
+ _FORMULA_CACHE_NS = '{http://schemas.openxmlformats.org/spreadsheetml/2006/main}'
1093
+ _FORMULA_CACHE_RNS = '{http://schemas.openxmlformats.org/officeDocument/2006/relationships}'
1094
+
1095
+
1096
+ def _inject_formula_cache(temp_path: Path, cache: dict[str, dict[str, Any]]) -> None:
1097
+ """后处理 xlsx XML,为公式 cell 注入缓存值,使 data_only 读取得到正确值。"""
1098
+ if not cache:
1099
+ return
1100
+ import xml.etree.ElementTree as ET
1101
+ ET.register_namespace('', 'http://schemas.openxmlformats.org/spreadsheetml/2006/main')
1102
+ with zipfile.ZipFile(temp_path) as zin:
1103
+ infos = zin.infolist()
1104
+ parts = {info.filename: zin.read(info.filename) for info in infos}
1105
+ wb_tree = ET.fromstring(parts['xl/workbook.xml'])
1106
+ rels_tree = ET.fromstring(parts['xl/_rels/workbook.xml.rels'])
1107
+ rels = {rel.get('Id'): rel.get('Target') for rel in rels_tree}
1108
+ sheet_to_file = {}
1109
+ for sheet in wb_tree.iter(f'{_FORMULA_CACHE_NS}sheet'):
1110
+ name = sheet.get('name')
1111
+ rel_id = sheet.get(f'{_FORMULA_CACHE_RNS}id')
1112
+ target = rels.get(rel_id, '')
1113
+ if target:
1114
+ sheet_to_file[name] = target.lstrip('/') if target.startswith('/') else 'xl/' + target
1115
+ for sheet_name, coord_cache in cache.items():
1116
+ xml_path = sheet_to_file.get(sheet_name)
1117
+ if not xml_path or xml_path not in parts:
1118
+ continue
1119
+ tree = ET.fromstring(parts[xml_path])
1120
+ modified = False
1121
+ for c in tree.iter(f'{_FORMULA_CACHE_NS}c'):
1122
+ coord = c.get('r')
1123
+ if coord not in coord_cache:
1124
+ continue
1125
+ if c.find(f'{_FORMULA_CACHE_NS}f') is None:
1126
+ continue
1127
+ cached = coord_cache[coord]
1128
+ if cached is None:
1129
+ continue
1130
+ v_elem = c.find(f'{_FORMULA_CACHE_NS}v')
1131
+ if v_elem is None:
1132
+ v_elem = ET.SubElement(c, f'{_FORMULA_CACHE_NS}v')
1133
+ if isinstance(cached, bool):
1134
+ c.set('t', 'b')
1135
+ v_elem.text = '1' if cached else '0'
1136
+ elif isinstance(cached, str):
1137
+ c.set('t', 'str')
1138
+ v_elem.text = cached
1139
+ else:
1140
+ v_elem.text = str(cached)
1141
+ modified = True
1142
+ if modified:
1143
+ xml_bytes = ET.tostring(tree, encoding='UTF-8')
1144
+ if xml_bytes.startswith(b"<?xml"):
1145
+ xml_bytes = xml_bytes.replace(b"encoding='UTF-8'", b'encoding="UTF-8"')
1146
+ if b'standalone' not in xml_bytes:
1147
+ xml_bytes = xml_bytes.replace(b'?>', b' standalone="yes"?>', 1)
1148
+ else:
1149
+ xml_bytes = b'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n' + xml_bytes
1150
+ parts[xml_path] = xml_bytes
1151
+ with zipfile.ZipFile(temp_path, 'w', zipfile.ZIP_DEFLATED) as zout:
1152
+ for info in infos:
1153
+ zout.writestr(info, parts[info.filename])
1154
+
1155
+
1156
+ def _rebuild_structural_sheet(wb_out, wb_base, wb_ours, wb_theirs, sheet, selection,
1157
+ wb_base_v=None, wb_ours_v=None, wb_theirs_v=None) -> dict[str, Any]:
1158
+ names = sheet.get("names") or {"base": sheet["name"], "ours": sheet["name"], "theirs": sheet["name"]}
1159
+ source_ws = None
1160
+ for workbook, side in ((wb_ours, "ours"), (wb_theirs, "theirs"), (wb_base, "base")):
1161
+ if workbook is not None and names.get(side) in workbook.sheetnames:
1162
+ source_ws = workbook[names[side]]
1163
+ break
1164
+ if source_ws is None:
1165
+ raise ConflictError(f"No source sheet is available for {sheet['name']}")
1166
+
1167
+ existing_name = names.get("ours")
1168
+ index = wb_out.sheetnames.index(existing_name) if existing_name in wb_out.sheetnames else len(wb_out.sheetnames)
1169
+ temp_title = f"__merge_{len(wb_out.sheetnames)}__"
1170
+ while temp_title in wb_out.sheetnames:
1171
+ temp_title += "_"
1172
+ target_ws = wb_out.create_sheet(temp_title, index=index)
1173
+ _copy_sheet_properties(source_ws, target_ws)
1174
+
1175
+ row_choices = selection.get("rows") or {}
1176
+ column_choices = selection.get("columns") or {}
1177
+ active_rows = [row for row in sheet.get("allRows") or [] if _axis_kept(row, row_choices)]
1178
+ active_columns = [column for column in sheet.get("columns") or [] if _axis_kept(column, column_choices)]
1179
+ workbooks = {"base": wb_base, "ours": wb_ours, "theirs": wb_theirs}
1180
+ workbooks_v = {"base": wb_base_v, "ours": wb_ours_v, "theirs": wb_theirs_v}
1181
+ cell_map = {cell["id"]: cell for cell in sheet.get("allCells") or sheet.get("cells") or []}
1182
+ cell_choices = selection.get("cells") or {}
1183
+ formula_cache: dict[str, Any] = {}
1184
+
1185
+ header_count = max(
1186
+ [max(_header_rows(workbook[names[side]]) or [0])
1187
+ for workbook, side in ((wb_base, "base"), (wb_ours, "ours"), (wb_theirs, "theirs"))
1188
+ if workbook is not None and names.get(side) in workbook.sheetnames]
1189
+ or [0]
1190
+ )
1191
+ for output_col, column in enumerate(active_columns, 1):
1192
+ dimension_source = None
1193
+ for workbook, side in ((wb_ours, "ours"), (wb_theirs, "theirs"), (wb_base, "base")):
1194
+ source_col = column.get(f"{side}Col")
1195
+ if workbook is not None and names.get(side) in workbook.sheetnames and source_col is not None:
1196
+ dimension_source = workbook[names[side]].column_dimensions[get_column_letter(source_col)]
1197
+ break
1198
+ if dimension_source is not None:
1199
+ target_ws.column_dimensions[get_column_letter(output_col)] = copy(dimension_source)
1200
+ target_ws.column_dimensions[get_column_letter(output_col)].worksheet = target_ws
1201
+ # 表头行高:ours 优先,回退 theirs/base
1202
+ for header_row in range(1, header_count + 1):
1203
+ for workbook, side in ((wb_ours, "ours"), (wb_theirs, "theirs"), (wb_base, "base")):
1204
+ if workbook is not None and names.get(side) in workbook.sheetnames:
1205
+ dim = workbook[names[side]].row_dimensions[header_row]
1206
+ if dim.height is not None:
1207
+ target_ws.row_dimensions[header_row] = copy(dim)
1208
+ target_ws.row_dimensions[header_row].worksheet = target_ws
1209
+ break
1210
+ for header_row in range(1, header_count + 1):
1211
+ for output_col, column in enumerate(active_columns, 1):
1212
+ source = None
1213
+ for side in ("theirs", "ours", "base"):
1214
+ workbook = workbooks[side]
1215
+ source_col = column.get(f"{side}Col")
1216
+ if workbook is not None and names.get(side) in workbook.sheetnames and source_col is not None:
1217
+ source = workbook[names[side]].cell(header_row, source_col)
1218
+ if source.value is not None:
1219
+ break
1220
+ if source is not None:
1221
+ _copy_cell(source, target_ws.cell(header_row, output_col))
1222
+
1223
+ for output_offset, row in enumerate(active_rows, 1):
1224
+ output_row = header_count + output_offset
1225
+ dimension_source = None
1226
+ for workbook, side in ((wb_ours, "ours"), (wb_theirs, "theirs"), (wb_base, "base")):
1227
+ source_row = row.get(f"{side}Row")
1228
+ if workbook is not None and names.get(side) in workbook.sheetnames and source_row is not None:
1229
+ dimension_source = workbook[names[side]].row_dimensions[source_row]
1230
+ break
1231
+ if dimension_source is not None:
1232
+ target_ws.row_dimensions[output_row] = copy(dimension_source)
1233
+ target_ws.row_dimensions[output_row].worksheet = target_ws
1234
+ for output_col, column in enumerate(active_columns, 1):
1235
+ cell = cell_map.get(f'{row["id"]}|{column["id"]}') or {
1236
+ "resolution": "same", "id": f'{row["id"]}|{column["id"]}', "coordinate": ""
1237
+ }
1238
+ choice = _cell_choice(cell_choices, cell)
1239
+ source = _selected_source_cell(workbooks, names, row, column, cell, choice)
1240
+ if source is not None:
1241
+ # 空且无格式的 cell 跳过写入:目标默认状态即空,输出等价
1242
+ if (
1243
+ source.value is None
1244
+ and not source.has_style
1245
+ and source.hyperlink is None
1246
+ and source.comment is None
1247
+ ):
1248
+ continue
1249
+ _copy_cell(source, target_ws.cell(output_row, output_col))
1250
+ # 公式 cell:记录输出坐标 -> 缓存值,保存后注入 XML
1251
+ if source.data_type == 'f':
1252
+ cached_source = _selected_source_cell(workbooks_v, names, row, column, cell, choice)
1253
+ cached_val = cached_source.value if cached_source is not None else None
1254
+ if cached_val is not None:
1255
+ formula_cache[f'{get_column_letter(output_col)}{output_row}'] = cached_val
1256
+
1257
+ _restore_merged_cells(target_ws, sheet, selection, active_rows, active_columns, header_count)
1258
+
1259
+ if existing_name in wb_out.sheetnames:
1260
+ wb_out.remove(wb_out[existing_name])
1261
+ final_name = _selected_sheet_name(sheet, selection)
1262
+ if final_name in wb_out.sheetnames and wb_out[final_name] is not target_ws:
1263
+ raise ConflictError(f"Sheet name collision after merge: {final_name}")
1264
+ target_ws.title = final_name
1265
+ return {final_name: formula_cache}
1266
+
1267
+
1268
+ def _build_merged_file(file_entry: dict[str, Any], decisions: dict[str, Any]) -> Path:
1269
+ output = Path(file_entry["output"]).resolve()
1270
+ output.parent.mkdir(parents=True, exist_ok=True)
1271
+ extension = output.suffix.lower()
1272
+ keep_vba = extension == ".xlsm"
1273
+ file_choice = _file_decisions(decisions, file_entry["id"])
1274
+ macro = file_entry.get("macro") or {}
1275
+ macro_choice = file_choice.get("macro", macro.get("default", "ours"))
1276
+ fd, temp_name = tempfile.mkstemp(prefix=f".{output.stem}-", suffix=extension, dir=output.parent)
1277
+ os.close(fd)
1278
+ temp_path = Path(temp_name)
1279
+ wb_out = load_workbook(file_entry["ours"], data_only=False, keep_links=True, keep_vba=keep_vba)
1280
+ wb_base = load_workbook(file_entry["base"], data_only=False, keep_links=True) if file_entry.get("base") else None
1281
+ wb_ours = wb_out # 只读复用,使 _copy_cell 同 workbook 样式索引快路径生效
1282
+ wb_theirs = load_workbook(file_entry["theirs"], data_only=False, keep_links=True)
1283
+ wb_base_v = load_workbook(file_entry["base"], data_only=True, keep_links=True) if file_entry.get("base") else None
1284
+ wb_ours_v = load_workbook(file_entry["ours"], data_only=True, keep_links=True)
1285
+ wb_theirs_v = load_workbook(file_entry["theirs"], data_only=True, keep_links=True)
1286
+ sheet_choices = file_choice.get("sheets") or {}
1287
+ formula_cache: dict[str, dict[str, Any]] = {}
1288
+ try:
1289
+ theirs_order = wb_theirs.sheetnames
1290
+ for sheet in file_entry["diff"]["sheets"]:
1291
+ name = sheet["name"]
1292
+ action = sheet["action"]
1293
+ selection = sheet_choices.get(name) or {}
1294
+ if action == "auto_delete":
1295
+ if name in wb_out.sheetnames:
1296
+ wb_out.remove(wb_out[name])
1297
+ continue
1298
+ if action == "auto_add_theirs":
1299
+ theirs_name = (sheet.get("names") or {}).get("theirs") or name
1300
+ ours_name = (sheet.get("names") or {}).get("ours")
1301
+ if ours_name in wb_out.sheetnames:
1302
+ wb_out.remove(wb_out[ours_name])
1303
+ if theirs_name not in wb_out.sheetnames:
1304
+ _copy_sheet(wb_theirs[theirs_name], wb_out, index=min(theirs_order.index(theirs_name), len(wb_out.sheetnames)))
1305
+ continue
1306
+ if action.startswith("conflict_"):
1307
+ side = selection["sheet"]
1308
+ if side == "ours":
1309
+ continue
1310
+ if name in wb_theirs.sheetnames:
1311
+ _replace_sheet(wb_out, wb_theirs[name], theirs_order)
1312
+ elif name in wb_out.sheetnames:
1313
+ wb_out.remove(wb_out[name])
1314
+ continue
1315
+ if action != "merge":
1316
+ continue
1317
+ if not sheet.get("rebuildRequired", True):
1318
+ existing_name = (sheet.get("names") or {}).get("ours") or name
1319
+ final_name = _selected_sheet_name(sheet, selection)
1320
+ if existing_name in wb_out.sheetnames and final_name != existing_name:
1321
+ if final_name in wb_out.sheetnames:
1322
+ raise ConflictError(f"Sheet name collision after merge: {final_name}")
1323
+ wb_out[existing_name].title = final_name
1324
+ continue
1325
+ if sheet.get("allRows") is not None and sheet.get("columns") is not None:
1326
+ cache = _rebuild_structural_sheet(
1327
+ wb_out, wb_base, wb_ours, wb_theirs, sheet, selection,
1328
+ wb_base_v, wb_ours_v, wb_theirs_v,
1329
+ )
1330
+ formula_cache.update(cache)
1331
+ continue
1332
+ ws_out = wb_out[name]
1333
+ ws_theirs = wb_theirs[name]
1334
+ ws_theirs_v = wb_theirs_v[name] if name in wb_theirs_v.sheetnames else None
1335
+ cell_choices = selection.get("cells") or {}
1336
+ legacy_cache: dict[str, Any] = {}
1337
+ for cell in sheet["cells"]:
1338
+ side = cell_choices.get(cell["coordinate"], cell["resolution"])
1339
+ if side == "conflict":
1340
+ side = cell_choices[cell["coordinate"]]
1341
+ if side == "theirs":
1342
+ src = ws_theirs[cell["coordinate"]]
1343
+ _copy_cell(src, ws_out[cell["coordinate"]])
1344
+ if src.data_type == 'f' and ws_theirs_v is not None:
1345
+ cached = ws_theirs_v[cell["coordinate"]].value
1346
+ if cached is not None:
1347
+ legacy_cache[cell["coordinate"]] = cached
1348
+ if legacy_cache:
1349
+ formula_cache[name] = legacy_cache
1350
+ if not wb_out.sheetnames:
1351
+ raise ConflictError(f"Cannot save a workbook with no sheets: {file_entry['path']}")
1352
+ wb_out.save(temp_path)
1353
+ except Exception:
1354
+ temp_path.unlink(missing_ok=True)
1355
+ raise
1356
+ finally:
1357
+ _close_workbook(wb_out)
1358
+ _close_workbook(wb_base)
1359
+ if wb_ours is not wb_out:
1360
+ _close_workbook(wb_ours)
1361
+ _close_workbook(wb_theirs)
1362
+ _close_workbook(wb_base_v)
1363
+ _close_workbook(wb_ours_v)
1364
+ _close_workbook(wb_theirs_v)
1365
+
1366
+ _inject_formula_cache(temp_path, formula_cache)
1367
+ check_wb = load_workbook(temp_path, read_only=True, data_only=False)
1368
+ check_wb.close()
1369
+ if keep_vba:
1370
+ macro_source = file_entry["theirs"] if macro_choice == "theirs" else file_entry["ours"]
1371
+ if macro_choice == "theirs":
1372
+ if not macro.get("canChooseTheirs", True):
1373
+ temp_path.unlink(missing_ok=True)
1374
+ raise ConflictError(
1375
+ f"Cannot safely preserve the REMOTE macro payload for {file_entry['path']} because its package structure differs."
1376
+ )
1377
+ _replace_macro_payload(temp_path, macro_source)
1378
+ expected_hash, expected_entries = _macro_payload_digest(macro_source)
1379
+ actual_hash, actual_entries = _macro_payload_digest(temp_path)
1380
+ if actual_hash != expected_hash or actual_entries != expected_entries:
1381
+ temp_path.unlink(missing_ok=True)
1382
+ raise ConflictError(f"Macro payload changed while saving {file_entry['path']}; output was not written.")
1383
+ return temp_path
1384
+
1385
+
1386
+ def _git_step(repo: Path, args: list[str], label: str) -> dict[str, Any]:
1387
+ result = _run_git(repo, args)
1388
+ output = (result.stdout + result.stderr).strip()
1389
+ return {"step": label, "success": result.returncode == 0, "output": output}
1390
+
1391
+
1392
+ def _build_commit_message(manifest: dict[str, Any], decisions: dict[str, Any]) -> str:
1393
+ """生成结构化提交信息:每个已选择的冲突 Cell 一行。
1394
+
1395
+ 格式:resolve: [表:path]-[sheet:name]-[单元格:A1]-[选择:远端/本地] [远端值:xxx 本地值:xxx]
1396
+ 无冲突 Cell 时回退默认信息。
1397
+ """
1398
+ lines: list[str] = []
1399
+ for file_entry in manifest["files"]:
1400
+ file_choice = _file_decisions(decisions, file_entry["id"])
1401
+ sheet_choices = file_choice.get("sheets") or {}
1402
+ for sheet in file_entry["diff"]["sheets"]:
1403
+ choice = sheet_choices.get(sheet["name"]) or {}
1404
+ cell_choices = choice.get("cells") or {}
1405
+ for cell in sheet["cells"]:
1406
+ if cell.get("resolution") != "conflict":
1407
+ continue
1408
+ cell_choice = _cell_choice(cell_choices, cell)
1409
+ if cell_choice not in ("ours", "theirs"):
1410
+ continue
1411
+ label = cell.get("coordinate") or cell.get("id") or ""
1412
+ side = "远端" if cell_choice == "theirs" else "本地"
1413
+ theirs_value = _message_value(cell.get("theirs"))
1414
+ ours_value = _message_value(cell.get("ours"))
1415
+ lines.append(
1416
+ f"resolve: [表:{file_entry['path']}]-[sheet:{sheet['name']}]-[单元格:{label}]-[选择:{side}] "
1417
+ f"[远端值:{theirs_value} 本地值:{ours_value}]"
1418
+ )
1419
+ if not lines:
1420
+ return "resolve: merge xlsx conflicts"
1421
+ message = "\n".join(lines)
1422
+ # 防止超长消息撑爆 git commit 命令行(Windows 单条命令约 32K 字符)
1423
+ if len(message) > MAX_COMMIT_MESSAGE_CHARS:
1424
+ message = message[:MAX_COMMIT_MESSAGE_CHARS].rstrip() + "\n... (truncated)"
1425
+ return message
1426
+
1427
+
1428
+ MAX_COMMIT_MESSAGE_CHARS = 20000
1429
+
1430
+
1431
+ def _message_value(value) -> str:
1432
+ """Cell 显示值转提交信息字符串:None 转空,浮点去多余小数。"""
1433
+ if value is None:
1434
+ return ""
1435
+ if isinstance(value, float):
1436
+ return str(int(value)) if value == int(value) else str(value)
1437
+ return str(value)
1438
+
1439
+
1440
+ def apply_manifest(
1441
+ manifest_path: Path | str,
1442
+ decisions: dict[str, Any],
1443
+ *,
1444
+ commit: bool = True,
1445
+ push: bool = False,
1446
+ message: str | None = None,
1447
+ ) -> dict[str, Any]:
1448
+ manifest = load_manifest(manifest_path)
1449
+ _validate_decisions(manifest, decisions)
1450
+ repo = find_repo_root(manifest["repoRoot"])
1451
+ prepared: list[tuple[Path, Path]] = []
1452
+ try:
1453
+ for file_entry in manifest["files"]:
1454
+ output = Path(file_entry["output"]).resolve()
1455
+ if os.path.commonpath([str(repo), str(output)]) != str(repo):
1456
+ raise ConflictError(f"Output escapes meta repository: {output}")
1457
+ prepared.append((output, _build_merged_file(file_entry, decisions)))
1458
+ for output, temp_path in prepared:
1459
+ os.replace(temp_path, output)
1460
+
1461
+ relative_paths = [str(output.relative_to(repo)).replace("\\", "/") for output, _ in prepared]
1462
+ steps = [_git_step(repo, ["add", "--", *relative_paths], "git add")]
1463
+ success = steps[-1]["success"]
1464
+ if success and commit:
1465
+ commit_message = message or _build_commit_message(manifest, decisions)
1466
+ steps.append(_git_step(repo, ["commit", "-m", commit_message], "git commit"))
1467
+ success = steps[-1]["success"]
1468
+ if success and push:
1469
+ steps.append(_git_step(repo, ["push"], "git push"))
1470
+ success = steps[-1]["success"]
1471
+ return {
1472
+ "success": success,
1473
+ "merged": [str(output) for output, _ in prepared],
1474
+ "steps": steps,
1475
+ }
1476
+ finally:
1477
+ for _, temp_path in prepared:
1478
+ temp_path.unlink(missing_ok=True)