@kevlns/xlmerge 1.2.2 → 1.3.0

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 CHANGED
@@ -6,6 +6,7 @@
6
6
 
7
7
  ```bash
8
8
  xlmerge --repo <repo> detect
9
+ xlmerge --repo <repo> filter add <path.xlsx>
9
10
  xlmerge --repo <repo> launch
10
11
  ```
11
12
 
@@ -17,7 +18,7 @@ xlmerge --repo <repo> launch
17
18
 
18
19
  ## 使用规范(Agent 必须遵守)
19
20
 
20
- 1. 用户确认要处理冲突后,**只做快速连贯的检测与启动**:`detect` → `count > 0` 时 `launch` → 把返回的 `url` 告诉用户,然后停止分析,等待用户在页面完成选择;`count == 0` 时报告没有未解决冲突并结束。
21
+ 1. 用户确认要处理冲突后,**只做快速连贯的检测与启动**:`detect` → `count > 0` 时 `launch`。`reviewCount > 0` 时把返回的 `url` 告诉用户,然后停止分析,等待用户在页面完成选择;`reviewCount == 0` 时 `launch` 会直接采用过滤项的远端版本并提交,报告其 JSON 结果;`count == 0` 时报告没有未解决冲突并结束。
21
22
  2. **不额外审查冲突情况**:不检查工作簿 Cell、不自行做三方 diff、不总结冲突内容、不读取 base/ours/theirs;这些复杂度由固化程序处理。
22
23
  3. **不默认走无头自动合并**:`launch --no-browser` + 程序化 decisions/apply 的无头链路仅限自动化测试或用户明确提供决策 JSON / 明确要求自动化的场景;默认流程必须走 UI `launch`,决策权始终在用户。
23
24
  4. **不替用户选择 ours/theirs**;不因为冲突文件多、Sheet 多而进入计划模式。
@@ -34,16 +35,28 @@ xlmerge --repo <repo> launch
34
35
  xlmerge --repo <repo> detect
35
36
  ```
36
37
 
37
- 2. `count > 0` 时立即启动解析器;不传 `--path`,一次性把所有冲突工作簿放进同一页面:
38
+ 2. `count > 0` 时立即启动解析器;不传 `--path`,一次性处理所有冲突工作簿:
38
39
 
39
40
  ```bash
40
41
  xlmerge --repo <repo> launch
41
42
  ```
42
43
 
43
- 3. 把 `launch` 返回的 `url` 告诉用户,然后停止分析,等待用户在页面完成选择。`launch` 已经负责提取全部 Git 三方版本、计算多文件多 Sheet diff、后台启动服务并打开浏览器。
44
+ 3. `reviewCount > 0` 时,把 `launch` 返回的 `url` 告诉用户,然后停止分析,等待用户在页面完成选择。`launch` 已经负责提取全部 Git 三方版本、计算多文件多 Sheet diff、后台启动服务并打开浏览器。`reviewCount == 0` 时不会启动 UI,命令会写回所有过滤项、提交并返回 `autoResolved`。
44
45
 
45
46
  如果 `count` 为 `0`,报告没有未解决的 `.xlsx` / `.xlsm` 冲突并结束。
46
47
 
48
+ ## 仓库过滤列表
49
+
50
+ 过滤列表默认为空,仅在用户明确要求某类生成表始终采用远端整表时添加:
51
+
52
+ ```bash
53
+ xlmerge --repo <repo> filter add locale/Key.xlsx
54
+ ```
55
+
56
+ 命令把规范化后的相对 `.xlsx`/`.xlsm` 路径后缀写入仓库根目录 `.xlmerge.json` 的 `autoTheirs` 数组;匹配不区分大小写,重复添加是幂等操作。工具不内置任何业务路径。
57
+
58
+ 命中过滤项的冲突文件不进入结构化分析或 UI,而是逐字节写入 Git index stage 3(theirs)。若 stage 3 不存在则安全失败;混合批次会在用户确认人工冲突后,与 UI 处理结果一起写回并提交。
59
+
47
60
  ### 快速流程禁止事项
48
61
 
49
62
  - 不调用通用 `xlsx` Skill、Excel API 或临时 Python 读取 base/ours/theirs。
@@ -77,7 +90,7 @@ xlmerge --repo <repo> launch
77
90
  - 先请求只读 `/api/commit-preview` 生成 commit 信息,弹出居中的二次确认窗口;确认后才执行写回与 `git add` / `git commit`。
78
91
  - 以 `ours` 工作簿为基底重建受影响 Sheet;保留所选来源的值、公式、样式、批注、超链接、数字格式、行高列宽、冻结拆分等视图状态;公式保留并从源文件注入缓存值。
79
92
  - 保存到仓库原路径并重新打开验证可读;`.xlsm` 全程 `keep_vba` 模式,保存后逐字节校验 VBA 负载。
80
- - 存在冲突 Cell 选择时自动生成结构化提交信息(每个冲突 Cell 一行,含表、Sheet、单元格、选择、双方值),`--message` 可覆盖。
93
+ - 存在冲突 Cell 选择时自动生成结构化提交信息(每个冲突 Cell 一行,含表、Sheet、单元格、选择、双方值);过滤项以“远端全量”记录,`--message` 可覆盖。
81
94
  - 可视化入口不自动 push。
82
95
 
83
96
  4. 用户完成页面操作并返回后复核:
@@ -105,6 +118,7 @@ xlmerge --repo <repo> apply --manifest <manifest.json> --decisions <decisions.js
105
118
 
106
119
  - 只处理 Git 未合并状态中的 `.xlsx` / `.xlsm`;不处理普通修改。
107
120
  - 文件级 delete/modify 冲突缺少完整双方工作簿时,解析器停止并报告;不要猜测删除还是保留。
121
+ - 过滤项要求 Git stage 3 存在;缺少远端版本时停止并报告,不退回本地版本。
108
122
  - 写回前必须收齐所有人工选择;缺少任何选择时不改工作树。
109
123
  - Excel 正在占用目标文件导致替换失败时,要求用户关闭该工作簿后重试。
110
124
  - 不直接修改 XLSX 内部 XML,不把公式替换为缓存值。
@@ -119,4 +133,4 @@ npm 包通过 `bin/xlmerge.js` 启动:自动检测系统 Python(≥3.9,顺
119
133
  ```bash
120
134
  cd <npm 包目录>
121
135
  python -m unittest discover -s python/tests -v
122
- ```
136
+ ```
package/README.md CHANGED
@@ -25,6 +25,7 @@ Git 对二进制 `.xlsx`/`.xlsm` 只会整文件冲突,无法像文本一样
25
25
  - **保真写回** - 保留公式(注入缓存值,`data_only` 读取正确)、样式、批注、合并单元格、冻结窗格、行高列宽
26
26
  - **VBA 安全** - `.xlsm` 全程 `keep_vba`,保存后逐字节校验 VBA/ActiveX 负载
27
27
  - **Luban 表头识别** - 自动识别 `##var` / `##type` / `##group`,注释列、占位列参与对齐
28
+ - **可配置整表过滤** - 仓库可把生成表加入过滤列表;命中时直接采用 Git stage 3 的远端原始文件
28
29
  - **默认不越权** - 服务只监听 `127.0.0.1`,不自动 push
29
30
 
30
31
  ## Getting started
@@ -46,6 +47,9 @@ npm install -g git+https://github.com/kevlns/xlmerge.git
46
47
  # 检测未合并的 .xlsx/.xlsm(输出 JSON)
47
48
  xlmerge --repo <仓库路径> detect
48
49
 
50
+ # 可选:把无需逐 Cell 审查的生成表加入仓库过滤列表
51
+ xlmerge --repo <仓库路径> filter add locale/Key.xlsx
52
+
49
53
  # 提取三方版本并后台启动可视化解析器,返回 url(自动打开浏览器)
50
54
  xlmerge --repo <仓库路径> launch
51
55
  ```
@@ -63,6 +67,9 @@ xlmerge --repo <仓库路径> launch
63
67
  # 检测未合并的 .xlsx/.xlsm(输出 JSON)
64
68
  xlmerge --repo <仓库路径> detect
65
69
 
70
+ # 添加整表过滤项(写入仓库根目录 .xlmerge.json)
71
+ xlmerge --repo <仓库路径> filter add <相对路径或路径后缀.xlsx>
72
+
66
73
  # 提取三方版本并后台启动可视化解析器,返回 url(自动打开浏览器)
67
74
  xlmerge --repo <仓库路径> launch
68
75
 
@@ -76,6 +83,18 @@ xlmerge --repo <仓库路径> apply --manifest <manifest.json> --decisions <deci
76
83
 
77
84
  `--repo` 缺省为当前目录(向上查找 Git 根)。
78
85
 
86
+ 过滤列表默认为空,保存在仓库根目录的 `.xlmerge.json`:
87
+
88
+ ```json
89
+ {
90
+ "autoTheirs": [
91
+ "locale/Key.xlsx"
92
+ ]
93
+ }
94
+ ```
95
+
96
+ 过滤项按路径段做不区分大小写的后缀匹配。命中的冲突工作簿不做 Cell 分析,而是逐字节采用 Git stage 3(theirs)并随同本批次提交;如果整批冲突都命中过滤项,`launch`/`resolve` 会直接写回并提交,不启动空白 UI。命令可重复执行,已有项不会重复写入。
97
+
79
98
  decisions.json 格式(Cell 用 manifest 中的稳定逻辑 ID,如 `row:base:4|name`):
80
99
 
81
100
  ```json
@@ -97,7 +116,7 @@ decisions.json 格式(Cell 用 manifest 中的稳定逻辑 ID,如 `row:base:
97
116
  ## Development
98
117
 
99
118
  ```bash
100
- # 单元测试(72 个,覆盖引擎与解析器全流程)
119
+ # 单元测试(覆盖引擎、解析器、过滤配置与大请求体全流程)
101
120
  python -m unittest discover -s python/tests -v
102
121
 
103
122
  # 校验 v-cli.plugin.json 与 CLI 解析器未漂移(命令/选项/副作用覆盖)
@@ -131,9 +150,9 @@ kevlns 工具家族共享同一套发布约定(tag 驱动、CI 护栏、MIT)
131
150
 
132
151
  | Package | Purpose | Status |
133
152
  | --- | --- | --- |
134
- | [`v-cli`](https://github.com/kevlns/v-cli) | 个人工具箱 CLI | v0.2.1 |
135
- | [`xlmerge`](https://github.com/kevlns/xlmerge) | Git 中 .xlsx/.xlsm 冲突可视化解决工具(本仓库) | v1.2.2 |
136
- | [`u-cli-mod`](https://github.com/kevlns/u-cli-mod) | Unity 精确版本路由 + CLI + pipeline 包(Windows-first) | v0.1.1 |
153
+ | [`v-cli`](https://github.com/kevlns/v-cli) | 个人工具箱 CLI | v0.2.3 |
154
+ | [`xlmerge`](https://github.com/kevlns/xlmerge) | Git 中 .xlsx/.xlsm 冲突可视化解决工具(本仓库) | v1.3.0 |
155
+ | [`u-cli-mod`](https://github.com/kevlns/u-cli-mod) | Unity 精确版本路由 + CLI + pipeline 包(Windows-first) | v0.1.4 |
137
156
 
138
157
  ## Compatibility
139
158
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kevlns/xlmerge",
3
- "version": "1.2.2",
3
+ "version": "1.3.0",
4
4
  "description": "Visual resolver for unresolved Git merge conflicts in .xlsx/.xlsm workbooks: three-way sheet/row/cell diff, local UI, write-back and commit.",
5
5
  "bin": {
6
6
  "xlmerge": "bin/xlmerge.js"
@@ -18,6 +18,17 @@ if str(SCRIPT_DIR) not in sys.path:
18
18
  from xlsx_conflict import ConflictError, _build_commit_message, apply_manifest, load_manifest
19
19
 
20
20
 
21
+ def _payload() -> dict:
22
+ """Read raw JSON without Bottle's 100 KiB ``request.json`` form-memory limit."""
23
+ if not request.content_length:
24
+ return {}
25
+ data = request.body.read()
26
+ if not data:
27
+ return {}
28
+ parsed = json.loads(data.decode("utf-8"))
29
+ return parsed if isinstance(parsed, dict) else {}
30
+
31
+
21
32
  def _json(data, status: int = 200):
22
33
  response.status = status
23
34
  response.content_type = "application/json; charset=utf-8"
@@ -43,9 +54,15 @@ def _public_manifest(manifest):
43
54
  }
44
55
 
45
56
 
46
- def serve(manifest_path: Path | str, *, open_browser: bool = True) -> bool:
57
+ def serve(manifest_path: Path | str, *, open_browser: bool = True, port: int = 0) -> bool:
47
58
  manifest_path = Path(manifest_path).resolve()
48
59
  manifest = load_manifest(manifest_path)
60
+ if not manifest["files"]:
61
+ print(
62
+ "Manifest has no conflicts requiring review; use resolve/apply for auto-theirs entries.",
63
+ file=sys.stderr,
64
+ )
65
+ return False
49
66
  html_path = Path(__file__).with_name("merge_ui.html")
50
67
  app = Bottle()
51
68
  state = {"resolved": False, "server": None}
@@ -62,7 +79,7 @@ def serve(manifest_path: Path | str, *, open_browser: bool = True) -> bool:
62
79
  @app.post("/api/commit-preview")
63
80
  def commit_preview():
64
81
  """只读:按当前 decisions 生成结构化 commit 信息,不执行任何写操作。"""
65
- payload = request.json or {}
82
+ payload = _payload()
66
83
  try:
67
84
  message = _build_commit_message(manifest, payload.get("decisions") or {})
68
85
  return _json({"message": message})
@@ -71,7 +88,7 @@ def serve(manifest_path: Path | str, *, open_browser: bool = True) -> bool:
71
88
 
72
89
  @app.post("/api/resolve")
73
90
  def resolve():
74
- payload = request.json or {}
91
+ payload = _payload()
75
92
  try:
76
93
  result = apply_manifest(
77
94
  manifest_path,
@@ -87,12 +104,16 @@ def serve(manifest_path: Path | str, *, open_browser: bool = True) -> bool:
87
104
  except (ConflictError, OSError, ValueError, KeyError) as exc:
88
105
  return _json({"success": False, "error": str(exc)}, 400)
89
106
 
107
+ @app.error(413)
108
+ def too_large(error):
109
+ return _json({"success": False, "error": "request body too large"}, 413)
110
+
90
111
  @app.post("/api/shutdown")
91
112
  def shutdown():
92
113
  threading.Thread(target=state["server"].shutdown, daemon=True).start()
93
114
  return _json({"success": True})
94
115
 
95
- server = make_server("127.0.0.1", 0, app)
116
+ server = make_server("127.0.0.1", port, app)
96
117
  state["server"] = server
97
118
  url = f"http://127.0.0.1:{server.server_port}"
98
119
  print(f"MERGE_SERVER_URL={url}", flush=True)
@@ -460,11 +460,16 @@ function enableHorizontalWheel(host) {
460
460
  }, {passive: false});
461
461
  }
462
462
 
463
+ function autoTheirsNote(sep) {
464
+ const count = (model && model.summary) ? (model.summary.autoTheirsCount || 0) : 0;
465
+ return count ? `${sep}已按远端全量自动处理 ${count} 张表` : '';
466
+ }
467
+
463
468
  async function init() {
464
469
  const response = await fetch('/api/diff');
465
470
  model = await response.json();
466
471
  if (!model.files || model.files.length === 0) {
467
- byId('footerStatus').textContent = '未发现冲突。';
472
+ byId('footerStatus').textContent = '未发现冲突。' + autoTheirsNote('');
468
473
  return;
469
474
  }
470
475
  initializeDecisions();
@@ -1123,7 +1128,7 @@ function updateStats() {
1123
1128
  }
1124
1129
  byId('localCount').textContent = String(local); byId('totalCount').textContent = String(total);
1125
1130
  const file = currentFileData(); const sheet = currentSheetData();
1126
- byId('footerStatus').textContent = `共 ${total} 个可决策项,${local} 项采用本地 · 当前:${file.path}${sheet ? ` / ${sheet.name}` : ''}`;
1131
+ byId('footerStatus').textContent = `共 ${total} 个可决策项,${local} 项采用本地 · 当前:${file.path}${sheet ? ` / ${sheet.name}` : ''}${autoTheirsNote(' · ')}`;
1127
1132
  }
1128
1133
 
1129
1134
  function renderCommitSteps(steps) {
@@ -1,4 +1,4 @@
1
- """CLI entry point for Debussy meta XLSX conflict resolution."""
1
+ """CLI entry point for repository-local XLSX/XLSM conflict resolution."""
2
2
 
3
3
  from __future__ import annotations
4
4
 
@@ -13,7 +13,17 @@ SCRIPT_DIR = Path(__file__).resolve().parent
13
13
  if str(SCRIPT_DIR) not in sys.path:
14
14
  sys.path.insert(0, str(SCRIPT_DIR))
15
15
 
16
- from xlsx_conflict import ConflictError, apply_manifest, detect_conflicts, find_repo_root, prepare_conflicts
16
+ from xlsx_conflict import (
17
+ ConflictError,
18
+ add_auto_theirs_filter,
19
+ apply_manifest,
20
+ auto_theirs_path,
21
+ detect_conflicts,
22
+ find_repo_root,
23
+ load_manifest,
24
+ load_auto_theirs_filters,
25
+ prepare_conflicts,
26
+ )
17
27
 
18
28
 
19
29
  SCRIPT_PATH = Path(__file__).resolve()
@@ -83,14 +93,33 @@ def _launch_background(repo: Path, manifest: Path, *, open_browser: bool) -> dic
83
93
  }
84
94
 
85
95
 
96
+ def _auto_only(manifest: Path) -> dict | None:
97
+ """Resolve an all-auto-theirs manifest immediately instead of starting an empty UI."""
98
+ if load_manifest(manifest)["files"]:
99
+ return None
100
+ result = apply_manifest(manifest, {"files": {}})
101
+ return {
102
+ "ok": result["success"],
103
+ "url": None,
104
+ "manifest": str(manifest),
105
+ "autoResolved": result.get("autoTheirs", []),
106
+ "steps": result["steps"],
107
+ }
108
+
109
+
86
110
  def build_parser() -> argparse.ArgumentParser:
87
- parser = argparse.ArgumentParser(description="Resolve Git XLSX/XLSM conflicts in the sibling Debussy meta repository.")
111
+ parser = argparse.ArgumentParser(description="Resolve Git XLSX/XLSM conflicts in a Git repository.")
88
112
  parser.add_argument("--repo", default=".", help="Git repository (default: %(default)s; the current directory).")
89
113
  parser.add_argument("--runtime-dir", help="Optional directory for extracted Git stage workbooks and manifest.")
90
114
  subparsers = parser.add_subparsers(dest="command", required=True)
91
115
 
92
116
  subparsers.add_parser("detect", help="List unresolved .xlsx/.xlsm files.")
93
117
 
118
+ filter_parser = subparsers.add_parser("filter", help="Manage repository-scoped auto-theirs workbook filters.")
119
+ filter_subparsers = filter_parser.add_subparsers(dest="filter_command", required=True)
120
+ filter_add = filter_subparsers.add_parser("add", help="Add one case-insensitive workbook path-suffix filter.")
121
+ filter_add.add_argument("path", help="Relative .xlsx/.xlsm path suffix to adopt from Git stage 3.")
122
+
94
123
  prepare = subparsers.add_parser("prepare", help="Extract base/ours/theirs and build a sheet-aware manifest.")
95
124
  prepare.add_argument("--path", help="Only prepare this repository-relative .xlsx/.xlsm path.")
96
125
 
@@ -105,6 +134,7 @@ def build_parser() -> argparse.ArgumentParser:
105
134
  serve_parser = subparsers.add_parser("serve", help=argparse.SUPPRESS)
106
135
  serve_parser.add_argument("--manifest", required=True)
107
136
  serve_parser.add_argument("--no-browser", action="store_true")
137
+ serve_parser.add_argument("--port", type=int, default=0, help="Fixed listen port (0 = ephemeral).")
108
138
 
109
139
  apply_parser = subparsers.add_parser("apply", help="Apply a decisions JSON without launching the UI.")
110
140
  apply_parser.add_argument("--manifest", required=True)
@@ -119,12 +149,25 @@ def main(argv: list[str] | None = None) -> int:
119
149
  args = build_parser().parse_args(argv)
120
150
  try:
121
151
  # serve/apply 仅依赖 manifest(其 repoRoot 在 apply_manifest 内部解析),
122
- # 可在非 git 目录下运行;仅 detect/prepare/resolve/launch 需要前置解析仓库。
123
- if args.command in ("detect", "prepare", "resolve", "launch"):
152
+ # 可在非 git 目录下运行;其余公开命令需要前置解析仓库。
153
+ if args.command in ("detect", "filter", "prepare", "resolve", "launch"):
124
154
  repo = find_repo_root(args.repo)
155
+ if args.command == "filter":
156
+ result = add_auto_theirs_filter(repo, args.path)
157
+ _print({"ok": True, "repo": str(repo), **result})
158
+ return 0
125
159
  if args.command == "detect":
126
160
  conflicts = detect_conflicts(repo)
127
- _print({"ok": True, "repo": str(repo), "count": len(conflicts), "conflicts": conflicts})
161
+ filters = load_auto_theirs_filters(repo)
162
+ auto = [item["path"] for item in conflicts if auto_theirs_path(item["path"], filters)]
163
+ _print({
164
+ "ok": True,
165
+ "repo": str(repo),
166
+ "count": len(conflicts),
167
+ "reviewCount": len(conflicts) - len(auto),
168
+ "autoTheirs": auto,
169
+ "conflicts": conflicts,
170
+ })
128
171
  return 0
129
172
  if args.command == "prepare":
130
173
  manifest = prepare_conflicts(repo, relative_path=args.path, runtime_dir=args.runtime_dir)
@@ -132,17 +175,25 @@ def main(argv: list[str] | None = None) -> int:
132
175
  return 0
133
176
  if args.command == "resolve":
134
177
  manifest = prepare_conflicts(repo, relative_path=args.path, runtime_dir=args.runtime_dir)
178
+ auto = _auto_only(manifest)
179
+ if auto is not None:
180
+ _print(auto)
181
+ return 0 if auto["ok"] else 1
135
182
  from merge_server import serve
136
183
 
137
184
  return 0 if serve(manifest, open_browser=not args.no_browser) else 1
138
185
  if args.command == "launch":
139
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
140
191
  _print(_launch_background(repo, manifest, open_browser=not args.no_browser))
141
192
  return 0
142
193
  if args.command == "serve":
143
194
  from merge_server import serve
144
195
 
145
- return 0 if serve(args.manifest, open_browser=not args.no_browser) else 1
196
+ return 0 if serve(args.manifest, open_browser=not args.no_browser, port=args.port) else 1
146
197
  decisions = json.loads(Path(args.decisions).read_text(encoding="utf-8"))
147
198
  result = apply_manifest(
148
199
  args.manifest,
@@ -43,6 +43,88 @@ def _is_macro_workbook(path: str | Path) -> bool:
43
43
  return Path(path).suffix.lower() == ".xlsm"
44
44
 
45
45
 
46
+ CONFIG_FILENAME = ".xlmerge.json"
47
+
48
+
49
+ def _normalize_filter_path(pattern: str) -> str:
50
+ normalized = pattern.replace("\\", "/").strip()
51
+ while normalized.startswith("./"):
52
+ normalized = normalized[2:]
53
+ parts = normalized.split("/")
54
+ if (
55
+ not normalized
56
+ or Path(normalized).is_absolute()
57
+ or any(part in ("", ".", "..") for part in parts)
58
+ or not _is_supported_workbook(normalized)
59
+ ):
60
+ raise ConflictError("Filter must be a relative .xlsx/.xlsm path without empty, '.' or '..' segments.")
61
+ return normalized
62
+
63
+
64
+ def load_auto_theirs_filters(repo: Path | str) -> list[str]:
65
+ """Load repository-scoped auto-theirs suffix filters; missing config means no filters."""
66
+ repo_root = find_repo_root(repo)
67
+ config_path = repo_root / CONFIG_FILENAME
68
+ if not config_path.exists():
69
+ return []
70
+ try:
71
+ data = json.loads(config_path.read_text(encoding="utf-8"))
72
+ except (OSError, json.JSONDecodeError) as exc:
73
+ raise ConflictError(f"Invalid {CONFIG_FILENAME}: {exc}") from exc
74
+ if not isinstance(data, dict) or not isinstance(data.get("autoTheirs", []), list):
75
+ raise ConflictError(f"Invalid {CONFIG_FILENAME}: 'autoTheirs' must be an array.")
76
+ filters: list[str] = []
77
+ for value in data.get("autoTheirs", []):
78
+ if not isinstance(value, str):
79
+ raise ConflictError(f"Invalid {CONFIG_FILENAME}: every autoTheirs entry must be a string.")
80
+ filters.append(_normalize_filter_path(value))
81
+ return filters
82
+
83
+
84
+ def add_auto_theirs_filter(repo: Path | str, pattern: str) -> dict[str, Any]:
85
+ """Persist one repository-scoped auto-theirs suffix filter atomically."""
86
+ repo_root = find_repo_root(repo)
87
+ normalized = _normalize_filter_path(pattern)
88
+ config_path = repo_root / CONFIG_FILENAME
89
+ data: dict[str, Any] = {}
90
+ if config_path.exists():
91
+ try:
92
+ loaded = json.loads(config_path.read_text(encoding="utf-8"))
93
+ except (OSError, json.JSONDecodeError) as exc:
94
+ raise ConflictError(f"Invalid {CONFIG_FILENAME}: {exc}") from exc
95
+ if not isinstance(loaded, dict):
96
+ raise ConflictError(f"Invalid {CONFIG_FILENAME}: root must be an object.")
97
+ data = loaded
98
+ filters = load_auto_theirs_filters(repo_root)
99
+ existing = {value.lower() for value in filters}
100
+ added = normalized.lower() not in existing
101
+ if added:
102
+ filters.append(normalized)
103
+ data["autoTheirs"] = filters
104
+ temp_path = config_path.with_name(f".{config_path.name}.{os.getpid()}.tmp")
105
+ try:
106
+ temp_path.write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
107
+ os.replace(temp_path, config_path)
108
+ finally:
109
+ temp_path.unlink(missing_ok=True)
110
+ return {
111
+ "config": str(config_path),
112
+ "filter": normalized,
113
+ "added": added,
114
+ "filters": filters,
115
+ }
116
+
117
+
118
+ def auto_theirs_path(relative_path: str, filters: Iterable[str]) -> str | None:
119
+ """Return the canonical filter for a case-insensitive path-suffix match."""
120
+ parts = relative_path.replace("\\", "/").lower().split("/")
121
+ for pattern in filters:
122
+ expected = pattern.lower().split("/")
123
+ if len(parts) >= len(expected) and parts[-len(expected):] == expected:
124
+ return pattern
125
+ return None
126
+
127
+
46
128
  def _is_macro_payload_entry(name: str) -> bool:
47
129
  lowered = name.lower()
48
130
  return (
@@ -831,9 +913,22 @@ def prepare_conflicts(
831
913
  raise ConflictError("No unresolved .xlsx/.xlsm conflicts were found.")
832
914
 
833
915
  target_dir = _safe_runtime_dir(repo_root, runtime_dir)
916
+ auto_filters = load_auto_theirs_filters(repo_root)
834
917
  prepared_files = []
918
+ auto_entries: list[dict[str, Any]] = []
835
919
  for item in conflicts:
836
920
  path = item["path"]
921
+ if auto_theirs_path(path, auto_filters):
922
+ if 3 not in item["stages"]:
923
+ raise ConflictError(
924
+ f"{path} matches the auto-theirs rule, but Git stage 3 is missing."
925
+ )
926
+ auto_entries.append({
927
+ "path": path,
928
+ "theirsAuthor": _theirs_author(repo_root, path),
929
+ "theirsDate": _theirs_date(repo_root, path),
930
+ })
931
+ continue
837
932
  ours_blob = _git_blob(repo_root, 2, path)
838
933
  theirs_blob = _git_blob(repo_root, 3, path)
839
934
  if ours_blob is None or theirs_blob is None:
@@ -881,11 +976,13 @@ def prepare_conflicts(
881
976
  "version": 3,
882
977
  "repoRoot": str(repo_root),
883
978
  "files": prepared_files,
979
+ "autoTheirs": auto_entries,
884
980
  "summary": {
885
981
  "fileCount": len(prepared_files),
886
982
  "cellConflictCount": sum(f["diff"]["summary"]["cellConflictCount"] for f in prepared_files),
887
983
  "sheetConflictCount": sum(f["diff"]["summary"]["sheetConflictCount"] for f in prepared_files),
888
984
  "structuralConflictCount": sum(f["diff"]["summary"].get("structuralConflictCount", 0) for f in prepared_files),
985
+ "autoTheirsCount": len(auto_entries),
889
986
  },
890
987
  }
891
988
  manifest_path = target_dir / "manifest.json"
@@ -1389,6 +1486,24 @@ def _git_step(repo: Path, args: list[str], label: str) -> dict[str, Any]:
1389
1486
  return {"step": label, "success": result.returncode == 0, "output": output}
1390
1487
 
1391
1488
 
1489
+ def _apply_auto_theirs(repo: Path, entries: list[dict[str, Any]]) -> list[Path]:
1490
+ """Write auto-theirs workbooks byte-for-byte from Git index stage 3."""
1491
+ outputs: list[Path] = []
1492
+ for entry in entries:
1493
+ relative_path = entry["path"]
1494
+ output = (repo / Path(relative_path)).resolve()
1495
+ if os.path.commonpath([str(repo), str(output)]) != str(repo):
1496
+ raise ConflictError(f"Output escapes repository: {output}")
1497
+ blob = _git_blob(repo, 3, relative_path)
1498
+ if blob is None:
1499
+ raise ConflictError(f"{relative_path} matches the auto-theirs rule, but Git stage 3 is missing.")
1500
+ output.parent.mkdir(parents=True, exist_ok=True)
1501
+ with open(output, "wb") as handle:
1502
+ handle.write(blob)
1503
+ outputs.append(output)
1504
+ return outputs
1505
+
1506
+
1392
1507
  def _build_commit_message(manifest: dict[str, Any], decisions: dict[str, Any]) -> str:
1393
1508
  """生成结构化提交信息:每个已选择的冲突 Cell 一行。
1394
1509
 
@@ -1396,6 +1511,8 @@ def _build_commit_message(manifest: dict[str, Any], decisions: dict[str, Any]) -
1396
1511
  无冲突 Cell 时回退默认信息。
1397
1512
  """
1398
1513
  lines: list[str] = []
1514
+ for entry in manifest.get("autoTheirs") or []:
1515
+ lines.append(f"resolve(auto): [表:{entry['path']}]-[选择:远端全量]")
1399
1516
  for file_entry in manifest["files"]:
1400
1517
  file_choice = _file_decisions(decisions, file_entry["id"])
1401
1518
  sheet_choices = file_choice.get("sheets") or {}
@@ -1448,6 +1565,9 @@ def apply_manifest(
1448
1565
  manifest = load_manifest(manifest_path)
1449
1566
  _validate_decisions(manifest, decisions)
1450
1567
  repo = find_repo_root(manifest["repoRoot"])
1568
+ auto_entries = manifest.get("autoTheirs") or []
1569
+ if not manifest["files"] and not auto_entries:
1570
+ raise ConflictError("Manifest has no conflicts to resolve.")
1451
1571
  prepared: list[tuple[Path, Path]] = []
1452
1572
  try:
1453
1573
  for file_entry in manifest["files"]:
@@ -1457,8 +1577,10 @@ def apply_manifest(
1457
1577
  prepared.append((output, _build_merged_file(file_entry, decisions)))
1458
1578
  for output, temp_path in prepared:
1459
1579
  os.replace(temp_path, output)
1580
+ auto_outputs = _apply_auto_theirs(repo, auto_entries)
1460
1581
 
1461
- relative_paths = [str(output.relative_to(repo)).replace("\\", "/") for output, _ in prepared]
1582
+ outputs = [output for output, _ in prepared] + auto_outputs
1583
+ relative_paths = [str(output.relative_to(repo)).replace("\\", "/") for output in outputs]
1462
1584
  steps = [_git_step(repo, ["add", "--", *relative_paths], "git add")]
1463
1585
  success = steps[-1]["success"]
1464
1586
  if success and commit:
@@ -1471,6 +1593,7 @@ def apply_manifest(
1471
1593
  return {
1472
1594
  "success": success,
1473
1595
  "merged": [str(output) for output, _ in prepared],
1596
+ "autoTheirs": [str(output.relative_to(repo)).replace("\\", "/") for output in auto_outputs],
1474
1597
  "steps": steps,
1475
1598
  }
1476
1599
  finally:
package/v-cli.plugin.json CHANGED
@@ -21,7 +21,7 @@
21
21
  }
22
22
  ],
23
23
  "agent": {
24
- "whenToUse": "When a user asks to resolve Git merge conflicts in .xlsx/.xlsm planning or configuration tables (策划表/配置表冲突): run detect first; when count > 0 run launch and give the returned url to the user. Do not inspect workbook cells or summarize diffs yourself; the resolver owns diff, choices, write-back and commit.",
24
+ "whenToUse": "When a user asks to resolve Git merge conflicts in .xlsx/.xlsm planning or configuration tables (策划表/配置表冲突): run detect first; when reviewCount > 0 run launch and give the returned url to the user. Configured auto-theirs filters may resolve and commit matched generated workbooks without opening the UI. Do not inspect workbook cells or summarize diffs yourself; the resolver owns diff, choices, write-back and commit.",
25
25
  "globalOptions": [
26
26
  {
27
27
  "flags": "--repo <path>",
@@ -41,7 +41,7 @@
41
41
  "options": [],
42
42
  "output": {
43
43
  "format": "json",
44
- "description": "Object with ok, repo (absolute path), count and conflicts (array of {path, stages})."
44
+ "description": "Object with ok, repo, count, reviewCount, autoTheirs and conflicts (array of {path, stages})."
45
45
  },
46
46
  "exitCodes": {
47
47
  "0": "success",
@@ -50,10 +50,33 @@
50
50
  },
51
51
  "safety": ["read-only", "no-worktree-modification"]
52
52
  },
53
+ {
54
+ "path": ["filter", "add"],
55
+ "usage": "xlmerge --repo <repo> filter add <path>",
56
+ "description": "Add a repository-scoped case-insensitive workbook path-suffix filter whose conflicts are adopted byte-for-byte from Git stage 3.",
57
+ "arguments": [
58
+ {
59
+ "name": "path",
60
+ "required": true,
61
+ "description": "Relative .xlsx/.xlsm path suffix to adopt from Git stage 3."
62
+ }
63
+ ],
64
+ "options": [],
65
+ "output": {
66
+ "format": "json",
67
+ "description": "Object with ok, repo, config, filter, added and the complete filters list. Writes <repo>/.xlmerge.json."
68
+ },
69
+ "exitCodes": {
70
+ "0": "success (including an already-present filter)",
71
+ "1": "invalid repository, filter path or .xlmerge.json",
72
+ "2": "usage error"
73
+ },
74
+ "safety": ["writes-worktree", "no-commit"]
75
+ },
53
76
  {
54
77
  "path": ["prepare"],
55
78
  "usage": "xlmerge --repo <repo> prepare [--path <file>]",
56
- "description": "Extract base/ours/theirs stage versions from the Git index and build a sheet-aware manifest.",
79
+ "description": "Build a sheet-aware manifest; configured auto-theirs matches skip extraction and cell analysis.",
57
80
  "arguments": [],
58
81
  "options": [
59
82
  {
@@ -89,14 +112,14 @@
89
112
  ],
90
113
  "output": {
91
114
  "format": "stdout",
92
- "description": "Prints MERGE_SERVER_URL=http://127.0.0.1:<port> then serves the UI on loopback until a resolution is applied (write-back + commit) and the server shuts down."
115
+ "description": "Prints MERGE_SERVER_URL=http://127.0.0.1:<port> for review conflicts; an all-filtered batch instead returns JSON after stage-3 write-back and commit."
93
116
  },
94
117
  "exitCodes": {
95
- "0": "success (resolution applied; server shut down after write-back)",
118
+ "0": "success (resolution applied automatically or via UI; server shuts down after UI write-back)",
96
119
  "1": "error (prepare failure or server stopped before a resolution was applied)",
97
120
  "2": "usage error"
98
121
  },
99
- "safety": ["blocking", "binds-loopback", "opens-browser-by-default", "no-push", "writes-runtime-dir", "writes-worktree-via-ui", "commits-by-default-via-ui"]
122
+ "safety": ["blocking", "binds-loopback", "opens-browser-by-default", "no-push", "writes-runtime-dir", "writes-worktree", "commits-by-default", "writes-worktree-via-ui", "commits-by-default-via-ui"]
100
123
  },
101
124
  {
102
125
  "path": ["launch"],
@@ -115,14 +138,14 @@
115
138
  ],
116
139
  "output": {
117
140
  "format": "json",
118
- "description": "Object with ok, pid, url (http://127.0.0.1:<port>), manifest and stdout/stderr log file paths."
141
+ "description": "For review conflicts: object with ok, pid, url, manifest and log paths. For an all-filtered batch: url is null and autoResolved/steps report automatic stage-3 write-back and commit."
119
142
  },
120
143
  "exitCodes": {
121
144
  "0": "success",
122
145
  "1": "error (prepare failure or server did not report a URL within 15 seconds)",
123
146
  "2": "usage error"
124
147
  },
125
- "safety": ["starts-background-server", "binds-loopback", "opens-browser-by-default", "no-push", "writes-runtime-dir", "writes-worktree-via-ui", "commits-by-default-via-ui"]
148
+ "safety": ["starts-background-server", "binds-loopback", "opens-browser-by-default", "no-push", "writes-runtime-dir", "writes-worktree", "commits-by-default", "writes-worktree-via-ui", "commits-by-default-via-ui"]
126
149
  },
127
150
  {
128
151
  "path": ["apply"],
@@ -164,4 +187,4 @@
164
187
  }
165
188
  ]
166
189
  }
167
- }
190
+ }