@kevlns/xlmerge 2.0.0 → 2.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -535,11 +535,12 @@ function sheetDecision(file, sheet) {
535
535
  }
536
536
  function cellKey(cell) { return cell.id || cell.coordinate; }
537
537
  function defaultCellChoice(cell) {
538
+ if (cell.requiresChoice) return null;
538
539
  if (cell.resolution === 'conflict') return 'theirs';
539
540
  if (cell.resolution === 'same') return cell.oursPresent === false ? 'theirs' : 'ours';
540
541
  return cell.resolution;
541
542
  }
542
- function defaultSheetChoice(sheet) { return sheet.action.startsWith('conflict_') ? 'ours' : null; }
543
+ function defaultSheetChoice(sheet) { return sheet.action.startsWith('conflict_') && !sheet.requiresChoice ? 'ours' : null; }
543
544
  function initializeDecisions() {
544
545
  for (const file of model.files) {
545
546
  const fileTarget = fileDecision(file);
@@ -621,10 +622,10 @@ function renderSheetTabs() {
621
622
  const host = byId('sheetTabs');
622
623
  host.replaceChildren();
623
624
  const file = currentFileData();
624
- // 只显示需要处理的 Sheet(needsAttention=false 的无冲突/无更改 Sheet 折叠)
625
+ // 单侧修改仍可人工覆盖,与双侧冲突使用相同的审阅入口。
625
626
  const visible = [];
626
627
  file.diff.sheets.forEach((sheet, index) => {
627
- if (sheet.needsAttention === false) return;
628
+ if (!sheetNeedsConfirmation(sheet)) return;
628
629
  visible.push({ sheet, index });
629
630
  });
630
631
  if (!visible.length) {
@@ -635,7 +636,7 @@ function renderSheetTabs() {
635
636
  return;
636
637
  }
637
638
  const current = file.diff.sheets[currentSheet];
638
- if (!current || current.needsAttention === false) {
639
+ if (!sheetNeedsConfirmation(current)) {
639
640
  currentSheet = visible[0].index;
640
641
  }
641
642
  visible.forEach(({ sheet, index }) => {
@@ -649,11 +650,24 @@ function renderSheetTabs() {
649
650
  confirmation.type = 'checkbox';
650
651
  confirmation.className = 'sheet-confirm-checkbox';
651
652
  confirmation.checked = target.confirmed === true;
652
- confirmation.title = '勾选表示你已人工审阅并确认本 Sheet 的所有冲突;取消勾选可继续编辑。';
653
+ confirmation.title = '勾选表示你已人工审阅并确认本 Sheet 的所有待处理项(含单侧改动);取消勾选可继续编辑。';
653
654
  confirmation.setAttribute('aria-label', `${sheet.name}:已确认(人工审阅完成)`);
654
655
  confirmation.onclick = event => event.stopPropagation();
655
656
  confirmation.onchange = event => {
656
657
  event.stopPropagation();
658
+ if (confirmation.checked && ((sheet.requiresChoice && !target.sheet) ||
659
+ (!target.sheet && (sheet.cells || []).some(cell => cell.requiresChoice && !target.cells[cellKey(cell)])))) {
660
+ confirmation.checked = false;
661
+ byId('footerStatus').textContent = '公式无法计算:请先明确选择这些单元格或整个 Sheet 的来源。';
662
+ return;
663
+ }
664
+ const invalid = !target.sheet && (sheet.cells || []).find(cell => (cell.errorSides || {})[target.cells[cellKey(cell)]]);
665
+ const sheetError = selectedSourceErrors(sheet, target).find(error => !validRepair(error, ((target.repairs || {})[target.sheet] || {})[error.coordinate]));
666
+ if (confirmation.checked && (invalid || sheetError)) {
667
+ confirmation.checked = false;
668
+ byId('footerStatus').textContent = '请先填写所选整表来源的合法修复值,再确认 Sheet。';
669
+ return;
670
+ }
657
671
  target.confirmed = confirmation.checked;
658
672
  render();
659
673
  };
@@ -693,6 +707,32 @@ function renderSheetChoice() {
693
707
  }
694
708
  }
695
709
  if (!sheet) return;
710
+ if (sheet.replacements && sheet.replacements.length) {
711
+ const note = document.createElement('span'); note.className = 'macro-label';
712
+ const count = new Set(sheet.replacements.map(repair => JSON.stringify([repair.recordId, repair.field]))).size;
713
+ note.textContent = sheet.replacements.some(repair => repair.manual)
714
+ ? '公式错误已按人工指定值修复,请确认整表来源。'
715
+ : `双方错误已按字段类型替换 ${count} 个值(ID、引用和未知类型保留人工处理)。`;
716
+ note.title = sheet.replacements.map(repair => `${repair.side} / ${repair.coordinate}: ${repair.formula} → ${JSON.stringify(repair.value)}`).join('\n');
717
+ host.append(note);
718
+ }
719
+ if (sheet.calculationErrors && sheet.calculationErrors.length) {
720
+ const note = document.createElement('span'); note.className = 'macro-label';
721
+ note.textContent = `有 ${sheet.calculationErrors.length} 个无法计算的值,必须选择有效来源。`;
722
+ note.title = sheet.calculationErrors.map(error => `${error.side} / ${error.sheet}!${error.coordinate}: ${error.formula} → ${error.error}`).join('\n');
723
+ host.append(note);
724
+ if (sheet.action === 'merge') {
725
+ for (const side of ['ours', 'theirs']) {
726
+ const button = document.createElement('button'); button.className = 'structure-toggle';
727
+ button.textContent = side === 'ours' ? '整表采用本地' : '整表采用远端';
728
+ button.disabled = currentSheetIsConfirmed(); button.onclick = () => chooseSheet(file, sheet, side); host.append(button);
729
+ }
730
+ if (sheetDecision(file, sheet).sheet) {
731
+ const button = document.createElement('button'); button.className = 'structure-toggle'; button.textContent = '返回单元格合并';
732
+ button.onclick = () => { delete sheetDecision(file, sheet).sheet; sheetDecision(file, sheet).confirmed = false; render(); }; host.append(button);
733
+ }
734
+ }
735
+ }
696
736
  const target = sheetDecision(file, sheet);
697
737
  const confirmed = sheetNeedsConfirmation(sheet) && target.confirmed;
698
738
  if (sheet.renameStatus === 'rename_conflict') {
@@ -738,7 +778,7 @@ function renderTable() {
738
778
  renderMessage(host, '无需处理', '两侧工作簿内容一致,没有需要展示的 Sheet 差异。');
739
779
  return;
740
780
  }
741
- if (sheet.action.startsWith('conflict_')) {
781
+ if (sheet.action.startsWith('conflict_') || sheetDecision(file, sheet).sheet) {
742
782
  renderSheetConflict(host, file, sheet);
743
783
  renderConfirmedOverlay(host, file, sheet);
744
784
  return;
@@ -757,7 +797,12 @@ function renderTable() {
757
797
  renderConfirmedOverlay(host, file, sheet);
758
798
  }
759
799
  function sheetNeedsConfirmation(sheet) {
760
- return !!sheet && sheet.needsAttention !== false;
800
+ return !!sheet && (sheet.needsAttention !== false || sheet.decisionCellCount > 0 ||
801
+ (sheet.cells || []).some(cell => cellNeedsReview(cell)));
802
+ }
803
+ function cellNeedsReview(cell) {
804
+ return !!cell && !cell.replacement && cell.selectable !== false &&
805
+ ['ours', 'theirs', 'conflict'].includes(cell.resolution);
761
806
  }
762
807
  function renderConfirmedOverlay(host, file, sheet) {
763
808
  if (!sheetNeedsConfirmation(sheet) || !sheetDecision(file, sheet).confirmed) return;
@@ -791,9 +836,9 @@ function renderActionAvailability() {
791
836
  function navigableConflictCells(file, sheet) {
792
837
  if (!sheet || !sheetNeedsConfirmation(sheet)) return [];
793
838
  if (sheet.columns && sheet.allRows) {
794
- return (sheet.cells || []).filter(cell => cell.resolution === 'conflict' && structuralCellSelectable(file, sheet, cell));
839
+ return (sheet.cells || []).filter(cell => cellNeedsReview(cell) && structuralCellSelectable(file, sheet, cell));
795
840
  }
796
- return (sheet.cells || []).filter(cell => cell.resolution === 'conflict');
841
+ return (sheet.cells || []).filter(cell => cellNeedsReview(cell));
797
842
  }
798
843
  function conflictCellKey(cell) { return cell && (cell.id || cell.coordinate); }
799
844
  function renderConflictNavigation() {
@@ -807,8 +852,8 @@ function renderConflictNavigation() {
807
852
  count.textContent = cells.length ? `${currentIndex < 0 ? 0 : currentIndex + 1} / ${cells.length}` : '0 / 0';
808
853
  previous.disabled = cells.length === 0;
809
854
  next.disabled = cells.length === 0;
810
- previous.title = cells.length ? '定位到当前 Sheet 的上一个可处理冲突(循环)' : '当前 Sheet 没有可定位的冲突';
811
- next.title = cells.length ? '定位到当前 Sheet 的下一个可处理冲突(循环)' : '当前 Sheet 没有可定位的冲突';
855
+ previous.title = cells.length ? '定位到当前 Sheet 的上一个待审阅改动(含单侧改动,循环)' : '当前 Sheet 没有可定位的改动';
856
+ next.title = cells.length ? '定位到当前 Sheet 的下一个待审阅改动(含单侧改动,循环)' : '当前 Sheet 没有可定位的改动';
812
857
  }
813
858
  function markConflictCell(cellElement) {
814
859
  if (!cellElement) return;
@@ -863,6 +908,14 @@ function renderSheetConflict(host, file, sheet) {
863
908
  const heading = document.createElement('h2'); heading.textContent = `${sheet.name}:删除 / 修改冲突`;
864
909
  const body = document.createElement('p');
865
910
  body.textContent = '一侧删除了整个 Sheet,另一侧继续修改。选择某一侧后,将按该侧实际状态保留或删除 Sheet。';
911
+ if (sheet.action === 'conflict_calculation_errors' || (sheet.calculationErrors || []).length) {
912
+ heading.textContent = `${sheet.name}:公式错误`;
913
+ body.textContent = '存在无法计算的值,且无法可靠对应行列或确认记录身份。请明确选择整个 Sheet 的有效本地或远端版本。';
914
+ if (!(sheet.calculationErrors || []).length) {
915
+ heading.textContent = `${sheet.name}:修复后整表选择`;
916
+ body.textContent = '公式错误已修复。选择整表来源后,勾选 Sheet 标签前的确认框完成审阅。';
917
+ }
918
+ }
866
919
  const target = sheetDecision(file, sheet);
867
920
  const names = sheet.names || {};
868
921
  const local = document.createElement('button');
@@ -874,6 +927,47 @@ function renderSheetConflict(host, file, sheet) {
874
927
  remote.className = 'btn btn-remote'; remote.textContent = target.sheet === 'theirs' ? `✓ ${remoteLabel}` : remoteLabel;
875
928
  remote.onclick = () => chooseSheet(file, sheet, 'theirs');
876
929
  box.append(heading, body, local, document.createTextNode(' '), remote); host.append(box);
930
+ const errors = selectedSourceErrors(sheet, target);
931
+ if (errors.length) {
932
+ const label = document.createElement('p'); label.textContent = '修复所选来源的错误值后,再确认整张 Sheet。ID / 引用字段需人工核对。'; box.append(label);
933
+ const values = ((target.repairs || {})[target.sheet] || {});
934
+ for (const error of errors) {
935
+ const row = document.createElement('div'); row.style.margin = '12px 0';
936
+ const title = document.createElement('label'); title.textContent = `${error.coordinate} · ${error.field || '字段未识别'} · ${error.type || '未知类型'}:`;
937
+ title.title = `${error.formula} → ${error.error}`;
938
+ const input = document.createElement(error.type === 'bool' ? 'select' : 'input');
939
+ input.setAttribute('aria-label', `${error.coordinate} 修复值`); input.disabled = currentSheetIsConfirmed();
940
+ if (error.type === 'bool') {
941
+ for (const text of ['', 'true', 'false']) {const option = document.createElement('option'); option.value = text; option.textContent = text || '请选择'; input.append(option);}
942
+ } else {input.type = 'text'; input.placeholder = error.type === 'string' ? '请输入文本(可为空串)' : '请输入合法数值';}
943
+ if (Object.hasOwn(values, error.coordinate)) input.value = String(values[error.coordinate]);
944
+ input.onchange = () => {
945
+ target.repairs ||= {}; target.repairs[target.sheet] ||= {};
946
+ const value = error.type === 'string' ? input.value : error.type === 'bool' ? (input.value ? input.value === 'true' : undefined) : (input.value.trim() ? Number(input.value) : undefined);
947
+ if (validRepair(error, value)) target.repairs[target.sheet][error.coordinate] = value;
948
+ else delete target.repairs[target.sheet][error.coordinate];
949
+ target.confirmed = false; renderSheetTabs(); updateStats();
950
+ };
951
+ title.append(input); row.append(title);
952
+ if (Object.hasOwn(error, 'defaultValue')) {
953
+ const button = document.createElement('button'); button.className = 'btn'; button.textContent = `使用类型默认值 ${JSON.stringify(error.defaultValue)}`;
954
+ button.onclick = () => {target.repairs ||= {}; target.repairs[target.sheet] ||= {}; target.repairs[target.sheet][error.coordinate] = error.defaultValue; target.confirmed = false; render();}; row.append(button);
955
+ }
956
+ box.append(row);
957
+ }
958
+ }
959
+ }
960
+ function selectedSourceErrors(sheet, target) {return (sheet.calculationErrors || []).filter(error => error.side === target.sheet);}
961
+ function validRepair(error, value) {
962
+ if (error.type === 'string') return typeof value === 'string';
963
+ if (error.type === 'bool') return typeof value === 'boolean';
964
+ if (['float', 'double', 'decimal'].includes(error.type)) return typeof value === 'number' && Number.isFinite(value);
965
+ const kind = error.type || '';
966
+ if (!/^(?:u?int(?:8|16|32|64)?|s?byte|u?short|u?long)$/.test(kind) || !Number.isSafeInteger(value)) return false;
967
+ const sizes = {byte:8,sbyte:8,short:16,ushort:16,long:64,ulong:64};
968
+ const bits = sizes[kind] || Number((kind.match(/\d+$/) || ['32'])[0]);
969
+ const unsigned = kind.startsWith('u') || kind === 'byte';
970
+ return value >= (unsigned ? 0 : -(2 ** (bits - 1))) && value <= 2 ** (unsigned ? bits : bits - 1) - 1;
877
971
  }
878
972
  function axisChoice(file, sheet, kind, axis) {
879
973
  if (axis.state !== 'delete_modify') return axis.default;
@@ -897,6 +991,7 @@ function structuralOutputMaps(file, sheet) {
897
991
  return {rows, columns};
898
992
  }
899
993
  function structuralCellSelectable(file, sheet, cell) {
994
+ if (cell.replacement) return false;
900
995
  if (!cell || !cell.changed || cell.selectable === false) return false;
901
996
  const row = (sheet.allRows || []).find(item => item.id === cell.rowId);
902
997
  const column = (sheet.columns || []).find(item => item.id === cell.colId);
@@ -1037,9 +1132,13 @@ function renderStructuralTable(host, file, sheet) {
1037
1132
  } else cell.className = 'cell-no-conflict' + (structurallyLocked ? ' cell-locked' : '');
1038
1133
  if (cellData) {
1039
1134
  cell.textContent = fmtVal(structuralCellValue(target, cellData));
1135
+ if (cellData.requiresChoice && !target.cells[cellData.id]) {
1136
+ cell.textContent = '待选择';
1137
+ cell.className = 'cell-no-conflict cell-selectable';
1138
+ }
1040
1139
  if (structuralCellSelectable(file, sheet, cellData)) {
1041
1140
  cell.onclick = () => cycleCell(file, sheet, cellData);
1042
- if (cellData.resolution === 'conflict') cell.dataset.conflictId = cellData.id;
1141
+ if (cellNeedsReview(cellData)) cell.dataset.conflictId = cellData.id;
1043
1142
  }
1044
1143
  bindStructuralTip(cell, file, sheet, axisRow, column, cellData);
1045
1144
  }
@@ -1108,7 +1207,7 @@ function renderLegacyDiffTable(host, file, sheet) {
1108
1207
  cell.className = choice === 'ours' ? 'cell-local' : 'cell-remote';
1109
1208
  cell.textContent = fmtVal(choice === 'ours' ? changed.ours : changed.theirs);
1110
1209
  cell.onclick = () => cycleCell(file, sheet, changed);
1111
- if (changed.resolution === 'conflict') cell.dataset.conflictId = changed.id || changed.coordinate;
1210
+ if (cellNeedsReview(changed)) cell.dataset.conflictId = changed.id || changed.coordinate;
1112
1211
  } else {
1113
1212
  cell.className = 'cell-no-conflict';
1114
1213
  cell.textContent = fmtVal(gridVal(sheet, rowNumber, col));
@@ -1171,10 +1270,22 @@ function showStructuralTip(event, file, sheet, row, column, cell) {
1171
1270
  const label = document.createElement('div'); label.className = 'label';
1172
1271
  label.textContent = `${file.path} / ${sheet.name} / ${row.id} / ${column.id}`; tip.append(label);
1173
1272
  addTipLine(tip, 'val-base', '基线', cell.base, '');
1273
+ if (cell.calculationErrors) {
1274
+ for (const [side, error] of Object.entries(cell.calculationErrors)) {
1275
+ addTipLine(tip, 'label', `${side === 'base' ? '历史' : side === 'ours' ? '本地' : '远端'}值未知`, `${error.coordinate}: ${error.formula} → ${error.error}`, '');
1276
+ }
1277
+ if (!sheetDecision(file, sheet).cells[cellKey(cell)]) addTipLine(tip, 'label', '待选择', '请点击明确选择本地或远端;当前展示不代表已选择。', '');
1278
+ }
1279
+ if (cell.replacement) {
1280
+ for (const [side, repair] of Object.entries(cell.replacement)) {
1281
+ addTipLine(tip, 'label', side === 'ours' ? '本地原错误' : '远端原错误', `${repair.coordinate}: ${repair.formula} → ${repair.error}`, '');
1282
+ }
1283
+ addTipLine(tip, 'label', '按类型替换', JSON.stringify(cell.replacement.ours.value), '');
1284
+ }
1174
1285
  addTipLine(tip, 'val-local', '本地', cell.ours, file.oursAuthor, file.oursDate);
1175
1286
  addTipLine(tip, 'val-remote', '远端', cell.theirs, file.theirsAuthor, file.theirsDate);
1176
1287
  const choice = sheetDecision(file, sheet).cells[cell.id] || defaultDisplayChoice(cell);
1177
- addTipLine(tip, 'val-current', '当前选择', choice === 'ours' ? '本地' : '远端', '');
1288
+ addTipLine(tip, 'val-current', '当前选择', choice ? (choice === 'ours' ? '本地' : '远端') : '待选择', '');
1178
1289
  addTipLine(tip, 'label', '行来源', axisSource(row, 'rows'), '');
1179
1290
  addTipLine(tip, 'label', '列来源', axisSource(column, 'columns'), '');
1180
1291
  if (row.state !== 'common') addTipLine(tip, 'label', '行状态', row.status, '');
@@ -1203,7 +1314,7 @@ function cycleCell(file, sheet, cell) {
1203
1314
  function chooseSheet(file, sheet, side) {
1204
1315
  const target = sheetDecision(file, sheet);
1205
1316
  undoStack.push({kind: 'sheet', fileId: file.id, sheet: sheet.name, previous: target.sheet});
1206
- target.sheet = side; renderTable(); updateStats();
1317
+ target.sheet = side; target.confirmed = false; render();
1207
1318
  }
1208
1319
  function chooseRename(file, sheet, side) {
1209
1320
  const target = sheetDecision(file, sheet);
@@ -1332,6 +1443,7 @@ function resetSheet() {
1332
1443
  if (sheet.renameStatus === 'rename_conflict') target.rename = 'ours'; else delete target.rename;
1333
1444
  if (sheet.mergedCells && sheet.mergedCells.status === 'conflict') target.mergedCells = sheet.mergedCells.default || 'ours'; else delete target.mergedCells;
1334
1445
  target.rows = {}; target.columns = {}; target.cells = {};
1446
+ delete target.repairs;
1335
1447
  for (const row of sheet.allRows || sheet.rows || []) if (row.state === 'delete_modify') target.rows[row.id] = row.default;
1336
1448
  for (const column of sheet.columns || []) if (column.state === 'delete_modify') target.columns[column.id] = column.default;
1337
1449
  for (const cell of sheet.cells || []) target.cells[cellKey(cell)] = defaultCellChoice(cell);
@@ -0,0 +1,34 @@
1
+ """Per-preparation progress and cooperative cancellation; no global job state."""
2
+ from contextvars import ContextVar
3
+ from contextlib import contextmanager
4
+
5
+
6
+ class PreparationCancelled(RuntimeError):
7
+ pass
8
+
9
+
10
+ _current = ContextVar('xlmerge_preparation', default=None)
11
+
12
+
13
+ @contextmanager
14
+ def preparation_context(report, cancelled):
15
+ token = _current.set((report, cancelled))
16
+ try:
17
+ yield
18
+ finally:
19
+ _current.reset(token)
20
+
21
+
22
+ def checkpoint(**progress):
23
+ context = _current.get()
24
+ if context is None:
25
+ return
26
+ report, cancelled = context
27
+ if cancelled.is_set():
28
+ raise PreparationCancelled('解析已中断,工作树未修改。')
29
+ if progress:
30
+ report(progress)
31
+
32
+
33
+ def cancellable():
34
+ return _current.get() is not None
@@ -101,24 +101,10 @@ try {
101
101
  if ($_.Exception.Message -like '*circular reference*') { throw }
102
102
  throw "Unable to verify circular references: $($_.Exception.Message)"
103
103
  }
104
- # Value2 is used only as a typed error probe. The actual typed value is
105
- # read from Excel's serialized cache by openpyxl so dates retain the
106
- # workbook epoch/number format and booleans never become numeric 1/0.
107
- foreach ($sheet in $book.Worksheets) {
108
- $used = $sheet.UsedRange
109
- foreach ($cell in $used.Cells) {
110
- if ($cell.HasFormula) {
111
- try {
112
- if ($excel.WorksheetFunction.IsError($cell.Value2)) {
113
- throw "Excel returned an error value at $($sheet.Name)!$($cell.Address($false,$false))"
114
- }
115
- } catch {
116
- if ($_.Exception.Message -like '*returned an error value*') { throw }
117
- throw "Unable to verify formula result at $($sheet.Name)!$($cell.Address($false,$false)): $($_.Exception.Message)"
118
- }
119
- }
120
- }
121
- }
104
+ # Save the completed calculation once. Python verifies every original
105
+ # formula's serialized cache and cell type, including errors and missing
106
+ # results. Traversing UsedRange through COM duplicates that validation and
107
+ # also visits potentially millions of formatted, non-formula cells.
122
108
  $book.SaveCopyAs($result)
123
109
  if (!(Test-Path -LiteralPath $result -PathType Leaf)) { throw 'Excel did not produce a result file' }
124
110
  Write-State 'completed'
@@ -7,6 +7,7 @@ import json
7
7
  import subprocess
8
8
  import sys
9
9
  import time
10
+ import tempfile
10
11
  from pathlib import Path
11
12
 
12
13
  SCRIPT_DIR = Path(__file__).resolve().parent
@@ -42,7 +43,7 @@ def _print(data) -> None:
42
43
  print(json.dumps(data, ensure_ascii=False, indent=2))
43
44
 
44
45
 
45
- def _launch_background(repo: Path, manifest: Path, *, open_browser: bool) -> dict:
46
+ def _launch_background(repo: Path, manifest: Path, *, open_browser: bool, prepare=False, relative_path=None) -> dict:
46
47
  """Start the resolver as a detached child and return its URL promptly."""
47
48
  runtime_dir = manifest.parent
48
49
  stamp = int(time.time() * 1000)
@@ -59,6 +60,10 @@ def _launch_background(repo: Path, manifest: Path, *, open_browser: bool) -> dic
59
60
  ]
60
61
  if not open_browser:
61
62
  command.append("--no-browser")
63
+ if prepare:
64
+ command.append('--prepare')
65
+ if relative_path:
66
+ command.extend(['--path', relative_path])
62
67
  creationflags = (
63
68
  getattr(subprocess, "CREATE_NO_WINDOW", 0)
64
69
  | getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0)
@@ -143,6 +148,8 @@ def build_parser() -> argparse.ArgumentParser:
143
148
  serve_parser.add_argument("--manifest", required=True)
144
149
  serve_parser.add_argument("--no-browser", action="store_true")
145
150
  serve_parser.add_argument("--port", type=int, default=0, help="Fixed listen port (0 = ephemeral).")
151
+ serve_parser.add_argument('--prepare', action='store_true', help=argparse.SUPPRESS)
152
+ serve_parser.add_argument('--path', help=argparse.SUPPRESS)
146
153
 
147
154
  apply_parser = subparsers.add_parser("apply", help="Apply a decisions JSON without launching the UI.")
148
155
  apply_parser.add_argument("--manifest", required=True)
@@ -182,27 +189,34 @@ def main(argv: list[str] | None = None) -> int:
182
189
  manifest = prepare_conflicts(repo, relative_path=args.path, runtime_dir=args.runtime_dir)
183
190
  _print({"ok": True, "manifest": str(manifest)})
184
191
  return 0
185
- if args.command == "resolve":
186
- manifest = prepare_conflicts(repo, relative_path=args.path, runtime_dir=args.runtime_dir)
187
- auto = _auto_only(manifest)
188
- if auto is not None:
189
- _print(auto)
190
- return 0 if auto["ok"] else 1
191
- from merge_server import serve
192
-
193
- return 0 if serve(manifest, open_browser=not args.no_browser) else 1
194
- if args.command == "launch":
195
- manifest = prepare_conflicts(repo, relative_path=args.path, runtime_dir=args.runtime_dir)
196
- auto = _auto_only(manifest)
197
- if auto is not None:
192
+ if args.command in ('resolve', 'launch'):
193
+ conflicts = detect_conflicts(repo)
194
+ if args.path:
195
+ conflicts = [c for c in conflicts if c['path'] == args.path.replace('\\', '/')]
196
+ if not conflicts:
197
+ raise ConflictError('No unresolved .xlsx/.xlsm conflicts were found.')
198
+ filters = load_auto_theirs_filters(repo)
199
+ if all(auto_theirs_path(c['path'], filters) for c in conflicts):
200
+ manifest = prepare_conflicts(repo, relative_path=args.path, runtime_dir=args.runtime_dir)
201
+ auto = _auto_only(manifest)
198
202
  _print(auto)
199
- return 0 if auto["ok"] else 1
200
- _print(_launch_background(repo, manifest, open_browser=not args.no_browser))
203
+ return 0 if auto['ok'] else 1
204
+ if args.runtime_dir:
205
+ Path(args.runtime_dir).mkdir(parents=True, exist_ok=True)
206
+ runtime = Path(tempfile.mkdtemp(prefix='xlmerge-session-', dir=args.runtime_dir))
207
+ if args.command == 'resolve':
208
+ from merge_server import serve
209
+ return 0 if serve(runtime / 'manifest.json', open_browser=not args.no_browser,
210
+ prepare_repo=repo, relative_path=args.path) else 1
211
+ _print(_launch_background(repo, runtime / 'manifest.json', open_browser=not args.no_browser,
212
+ prepare=True, relative_path=args.path))
201
213
  return 0
202
214
  if args.command == "serve":
203
215
  from merge_server import serve
204
216
 
205
- return 0 if serve(args.manifest, open_browser=not args.no_browser, port=args.port) else 1
217
+ return 0 if serve(args.manifest, open_browser=not args.no_browser, port=args.port,
218
+ prepare_repo=find_repo_root(args.repo) if args.prepare else None,
219
+ relative_path=args.path) else 1
206
220
  decisions = json.loads(Path(args.decisions).read_text(encoding="utf-8"))
207
221
  result = apply_manifest(
208
222
  args.manifest,