@kevlns/xlmerge 2.0.0 → 2.0.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.
- package/AGENTS.md +141 -141
- package/LICENSE +21 -21
- package/README.md +193 -189
- package/bin/xlmerge.js +152 -152
- package/package.json +1 -1
- package/python/xlsx_merge_engine/__init__.py +2 -2
- package/python/xlsx_merge_engine/xlsx_git_merge_bridge.py +1611 -1611
- package/python/xlsx_resolver/__init__.py +2 -2
- package/python/xlsx_resolver/__main__.py +4 -4
- package/python/xlsx_resolver/formula_values.py +565 -565
- package/python/xlsx_resolver/merge_server.py +126 -126
- package/python/xlsx_resolver/merge_ui.html +1522 -1522
- package/python/xlsx_resolver/recalculate_workbook.ps1 +155 -155
- package/python/xlsx_resolver/resolve_xlsx_conflict.py +222 -222
- package/python/xlsx_resolver/xlsx_conflict.py +1994 -1994
- package/v-cli.plugin.json +194 -194
|
@@ -1,1994 +1,1994 @@
|
|
|
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 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)
|