@kevlns/xlmerge 2.0.1 → 2.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,222 +1,236 @@
1
- """CLI entry point for repository-local XLSX/XLSM conflict resolution."""
2
-
3
- from __future__ import annotations
4
-
5
- import argparse
6
- import json
7
- import subprocess
8
- import sys
9
- import time
10
- from pathlib import Path
11
-
12
- SCRIPT_DIR = Path(__file__).resolve().parent
13
- if str(SCRIPT_DIR) not in sys.path:
14
- sys.path.insert(0, str(SCRIPT_DIR))
15
-
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
- )
27
-
28
-
29
- SCRIPT_PATH = Path(__file__).resolve()
30
- PACKAGE_ROOT = SCRIPT_DIR.parent
31
-
32
-
33
- def _configure_stdio() -> None:
34
- """Keep structured CLI output UTF-8 even under legacy Windows code pages."""
35
- for stream in (sys.stdout, sys.stderr):
36
- reconfigure = getattr(stream, "reconfigure", None)
37
- if callable(reconfigure):
38
- reconfigure(encoding="utf-8", errors="replace")
39
-
40
-
41
- def _print(data) -> None:
42
- print(json.dumps(data, ensure_ascii=False, indent=2))
43
-
44
-
45
- def _launch_background(repo: Path, manifest: Path, *, open_browser: bool) -> dict:
46
- """Start the resolver as a detached child and return its URL promptly."""
47
- runtime_dir = manifest.parent
48
- stamp = int(time.time() * 1000)
49
- stdout_path = runtime_dir / f"resolver-{stamp}.stdout.log"
50
- stderr_path = runtime_dir / f"resolver-{stamp}.stderr.log"
51
- command = [
52
- sys.executable,
53
- str(SCRIPT_PATH),
54
- "--repo",
55
- str(repo),
56
- "serve",
57
- "--manifest",
58
- str(manifest),
59
- ]
60
- if not open_browser:
61
- command.append("--no-browser")
62
- creationflags = (
63
- getattr(subprocess, "CREATE_NO_WINDOW", 0)
64
- | getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0)
65
- )
66
- with stdout_path.open("w", encoding="utf-8") as stdout_handle, stderr_path.open("w", encoding="utf-8") as stderr_handle:
67
- process = subprocess.Popen(
68
- command,
69
- cwd=str(PACKAGE_ROOT),
70
- stdout=stdout_handle,
71
- stderr=stderr_handle,
72
- stdin=subprocess.DEVNULL,
73
- creationflags=creationflags,
74
- close_fds=True,
75
- )
76
-
77
- deadline = time.monotonic() + 15
78
- url = ""
79
- while time.monotonic() < deadline:
80
- output = stdout_path.read_text(encoding="utf-8", errors="replace") if stdout_path.exists() else ""
81
- for line in output.splitlines():
82
- if line.startswith("MERGE_SERVER_URL="):
83
- url = line.split("=", 1)[1].strip()
84
- break
85
- if url or process.poll() is not None:
86
- break
87
- time.sleep(0.1)
88
-
89
- if not url:
90
- if process.poll() is None:
91
- process.terminate()
92
- stderr = stderr_path.read_text(encoding="utf-8", errors="replace") if stderr_path.exists() else ""
93
- raise ConflictError(f"Resolver failed to start: {stderr.strip() or 'URL was not reported within 15 seconds'}")
94
- return {
95
- "ok": True,
96
- "pid": process.pid,
97
- "url": url,
98
- "manifest": str(manifest),
99
- "stdout": str(stdout_path),
100
- "stderr": str(stderr_path),
101
- }
102
-
103
-
104
- def _auto_only(manifest: Path) -> dict | None:
105
- """Resolve an all-auto-theirs manifest immediately instead of starting an empty UI."""
106
- if load_manifest(manifest)["files"]:
107
- return None
108
- result = apply_manifest(manifest, {"files": {}})
109
- return {
110
- "ok": result["success"],
111
- "url": None,
112
- "manifest": str(manifest),
113
- "autoResolved": result.get("autoTheirs", []),
114
- "steps": result["steps"],
115
- }
116
-
117
-
118
- def build_parser() -> argparse.ArgumentParser:
119
- parser = argparse.ArgumentParser(description="Resolve Git XLSX/XLSM conflicts in a Git repository.")
120
- parser.add_argument("--repo", default=".", help="Git repository (default: %(default)s; the current directory).")
121
- parser.add_argument("--runtime-dir", help="Optional directory for extracted Git stage workbooks and manifest.")
122
- subparsers = parser.add_subparsers(dest="command", required=True)
123
-
124
- subparsers.add_parser("detect", help="List unresolved .xlsx/.xlsm files.")
125
-
126
- filter_parser = subparsers.add_parser("filter", help="Manage repository-scoped auto-theirs workbook filters.")
127
- filter_subparsers = filter_parser.add_subparsers(dest="filter_command", required=True)
128
- filter_add = filter_subparsers.add_parser("add", help="Add one case-insensitive workbook path-suffix filter.")
129
- filter_add.add_argument("path", help="Relative .xlsx/.xlsm path suffix to adopt from Git stage 3.")
130
-
131
- prepare = subparsers.add_parser("prepare", help="Extract base/ours/theirs and build a sheet-aware manifest.")
132
- prepare.add_argument("--path", help="Only prepare this repository-relative .xlsx/.xlsm path.")
133
-
134
- resolve = subparsers.add_parser("resolve", help="Prepare conflicts and launch the local visual resolver.")
135
- resolve.add_argument("--path", help="Only resolve this repository-relative .xlsx/.xlsm path.")
136
- resolve.add_argument("--no-browser", action="store_true", help="Print the URL without opening a browser.")
137
-
138
- launch = subparsers.add_parser("launch", help="Prepare conflicts, start the visual resolver in background, and return its URL.")
139
- launch.add_argument("--path", help="Only resolve this repository-relative .xlsx/.xlsm path.")
140
- launch.add_argument("--no-browser", action="store_true", help="Start the server without opening a browser.")
141
-
142
- serve_parser = subparsers.add_parser("serve", help=argparse.SUPPRESS)
143
- serve_parser.add_argument("--manifest", required=True)
144
- serve_parser.add_argument("--no-browser", action="store_true")
145
- serve_parser.add_argument("--port", type=int, default=0, help="Fixed listen port (0 = ephemeral).")
146
-
147
- apply_parser = subparsers.add_parser("apply", help="Apply a decisions JSON without launching the UI.")
148
- apply_parser.add_argument("--manifest", required=True)
149
- apply_parser.add_argument("--decisions", required=True)
150
- apply_parser.add_argument("--no-commit", action="store_true")
151
- apply_parser.add_argument("--push", action="store_true")
152
- apply_parser.add_argument("--message", default=None, help="Override the auto-generated structured commit message.")
153
- return parser
154
-
155
-
156
- def main(argv: list[str] | None = None) -> int:
157
- _configure_stdio()
158
- args = build_parser().parse_args(argv)
159
- try:
160
- # serve/apply 仅依赖 manifest(其 repoRoot 在 apply_manifest 内部解析),
161
- # 可在非 git 目录下运行;其余公开命令需要前置解析仓库。
162
- if args.command in ("detect", "filter", "prepare", "resolve", "launch"):
163
- repo = find_repo_root(args.repo)
164
- if args.command == "filter":
165
- result = add_auto_theirs_filter(repo, args.path)
166
- _print({"ok": True, "repo": str(repo), **result})
167
- return 0
168
- if args.command == "detect":
169
- conflicts = detect_conflicts(repo)
170
- filters = load_auto_theirs_filters(repo)
171
- auto = [item["path"] for item in conflicts if auto_theirs_path(item["path"], filters)]
172
- _print({
173
- "ok": True,
174
- "repo": str(repo),
175
- "count": len(conflicts),
176
- "reviewCount": len(conflicts) - len(auto),
177
- "autoTheirs": auto,
178
- "conflicts": conflicts,
179
- })
180
- return 0
181
- if args.command == "prepare":
182
- manifest = prepare_conflicts(repo, relative_path=args.path, runtime_dir=args.runtime_dir)
183
- _print({"ok": True, "manifest": str(manifest)})
184
- 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:
198
- _print(auto)
199
- return 0 if auto["ok"] else 1
200
- _print(_launch_background(repo, manifest, open_browser=not args.no_browser))
201
- return 0
202
- if args.command == "serve":
203
- from merge_server import serve
204
-
205
- return 0 if serve(args.manifest, open_browser=not args.no_browser, port=args.port) else 1
206
- decisions = json.loads(Path(args.decisions).read_text(encoding="utf-8"))
207
- result = apply_manifest(
208
- args.manifest,
209
- decisions,
210
- commit=not args.no_commit,
211
- push=args.push,
212
- message=args.message,
213
- )
214
- _print(result)
215
- return 0 if result["success"] else 1
216
- except (ConflictError, OSError, ValueError, json.JSONDecodeError) as exc:
217
- _print({"ok": False, "error": str(exc)})
218
- return 1
219
-
220
-
221
- if __name__ == "__main__":
222
- sys.exit(main())
1
+ """CLI entry point for repository-local XLSX/XLSM conflict resolution."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import subprocess
8
+ import sys
9
+ import time
10
+ import tempfile
11
+ from pathlib import Path
12
+
13
+ SCRIPT_DIR = Path(__file__).resolve().parent
14
+ if str(SCRIPT_DIR) not in sys.path:
15
+ sys.path.insert(0, str(SCRIPT_DIR))
16
+
17
+ from xlsx_conflict import (
18
+ ConflictError,
19
+ add_auto_theirs_filter,
20
+ apply_manifest,
21
+ auto_theirs_path,
22
+ detect_conflicts,
23
+ find_repo_root,
24
+ load_manifest,
25
+ load_auto_theirs_filters,
26
+ prepare_conflicts,
27
+ )
28
+
29
+
30
+ SCRIPT_PATH = Path(__file__).resolve()
31
+ PACKAGE_ROOT = SCRIPT_DIR.parent
32
+
33
+
34
+ def _configure_stdio() -> None:
35
+ """Keep structured CLI output UTF-8 even under legacy Windows code pages."""
36
+ for stream in (sys.stdout, sys.stderr):
37
+ reconfigure = getattr(stream, "reconfigure", None)
38
+ if callable(reconfigure):
39
+ reconfigure(encoding="utf-8", errors="replace")
40
+
41
+
42
+ def _print(data) -> None:
43
+ print(json.dumps(data, ensure_ascii=False, indent=2))
44
+
45
+
46
+ def _launch_background(repo: Path, manifest: Path, *, open_browser: bool, prepare=False, relative_path=None) -> dict:
47
+ """Start the resolver as a detached child and return its URL promptly."""
48
+ runtime_dir = manifest.parent
49
+ stamp = int(time.time() * 1000)
50
+ stdout_path = runtime_dir / f"resolver-{stamp}.stdout.log"
51
+ stderr_path = runtime_dir / f"resolver-{stamp}.stderr.log"
52
+ command = [
53
+ sys.executable,
54
+ str(SCRIPT_PATH),
55
+ "--repo",
56
+ str(repo),
57
+ "serve",
58
+ "--manifest",
59
+ str(manifest),
60
+ ]
61
+ if not open_browser:
62
+ command.append("--no-browser")
63
+ if prepare:
64
+ command.append('--prepare')
65
+ if relative_path:
66
+ command.extend(['--path', relative_path])
67
+ creationflags = (
68
+ getattr(subprocess, "CREATE_NO_WINDOW", 0)
69
+ | getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0)
70
+ )
71
+ with stdout_path.open("w", encoding="utf-8") as stdout_handle, stderr_path.open("w", encoding="utf-8") as stderr_handle:
72
+ process = subprocess.Popen(
73
+ command,
74
+ cwd=str(PACKAGE_ROOT),
75
+ stdout=stdout_handle,
76
+ stderr=stderr_handle,
77
+ stdin=subprocess.DEVNULL,
78
+ creationflags=creationflags,
79
+ close_fds=True,
80
+ )
81
+
82
+ deadline = time.monotonic() + 15
83
+ url = ""
84
+ while time.monotonic() < deadline:
85
+ output = stdout_path.read_text(encoding="utf-8", errors="replace") if stdout_path.exists() else ""
86
+ for line in output.splitlines():
87
+ if line.startswith("MERGE_SERVER_URL="):
88
+ url = line.split("=", 1)[1].strip()
89
+ break
90
+ if url or process.poll() is not None:
91
+ break
92
+ time.sleep(0.1)
93
+
94
+ if not url:
95
+ if process.poll() is None:
96
+ process.terminate()
97
+ stderr = stderr_path.read_text(encoding="utf-8", errors="replace") if stderr_path.exists() else ""
98
+ raise ConflictError(f"Resolver failed to start: {stderr.strip() or 'URL was not reported within 15 seconds'}")
99
+ return {
100
+ "ok": True,
101
+ "pid": process.pid,
102
+ "url": url,
103
+ "manifest": str(manifest),
104
+ "stdout": str(stdout_path),
105
+ "stderr": str(stderr_path),
106
+ }
107
+
108
+
109
+ def _auto_only(manifest: Path) -> dict | None:
110
+ """Resolve an all-auto-theirs manifest immediately instead of starting an empty UI."""
111
+ if load_manifest(manifest)["files"]:
112
+ return None
113
+ result = apply_manifest(manifest, {"files": {}})
114
+ return {
115
+ "ok": result["success"],
116
+ "url": None,
117
+ "manifest": str(manifest),
118
+ "autoResolved": result.get("autoTheirs", []),
119
+ "steps": result["steps"],
120
+ }
121
+
122
+
123
+ def build_parser() -> argparse.ArgumentParser:
124
+ parser = argparse.ArgumentParser(description="Resolve Git XLSX/XLSM conflicts in a Git repository.")
125
+ parser.add_argument("--repo", default=".", help="Git repository (default: %(default)s; the current directory).")
126
+ parser.add_argument("--runtime-dir", help="Optional directory for extracted Git stage workbooks and manifest.")
127
+ subparsers = parser.add_subparsers(dest="command", required=True)
128
+
129
+ subparsers.add_parser("detect", help="List unresolved .xlsx/.xlsm files.")
130
+
131
+ filter_parser = subparsers.add_parser("filter", help="Manage repository-scoped auto-theirs workbook filters.")
132
+ filter_subparsers = filter_parser.add_subparsers(dest="filter_command", required=True)
133
+ filter_add = filter_subparsers.add_parser("add", help="Add one case-insensitive workbook path-suffix filter.")
134
+ filter_add.add_argument("path", help="Relative .xlsx/.xlsm path suffix to adopt from Git stage 3.")
135
+
136
+ prepare = subparsers.add_parser("prepare", help="Extract base/ours/theirs and build a sheet-aware manifest.")
137
+ prepare.add_argument("--path", help="Only prepare this repository-relative .xlsx/.xlsm path.")
138
+
139
+ resolve = subparsers.add_parser("resolve", help="Prepare conflicts and launch the local visual resolver.")
140
+ resolve.add_argument("--path", help="Only resolve this repository-relative .xlsx/.xlsm path.")
141
+ resolve.add_argument("--no-browser", action="store_true", help="Print the URL without opening a browser.")
142
+
143
+ launch = subparsers.add_parser("launch", help="Prepare conflicts, start the visual resolver in background, and return its URL.")
144
+ launch.add_argument("--path", help="Only resolve this repository-relative .xlsx/.xlsm path.")
145
+ launch.add_argument("--no-browser", action="store_true", help="Start the server without opening a browser.")
146
+
147
+ serve_parser = subparsers.add_parser("serve", help=argparse.SUPPRESS)
148
+ serve_parser.add_argument("--manifest", required=True)
149
+ serve_parser.add_argument("--no-browser", action="store_true")
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)
153
+
154
+ apply_parser = subparsers.add_parser("apply", help="Apply a decisions JSON without launching the UI.")
155
+ apply_parser.add_argument("--manifest", required=True)
156
+ apply_parser.add_argument("--decisions", required=True)
157
+ apply_parser.add_argument("--no-commit", action="store_true")
158
+ apply_parser.add_argument("--push", action="store_true")
159
+ apply_parser.add_argument("--message", default=None, help="Override the auto-generated structured commit message.")
160
+ return parser
161
+
162
+
163
+ def main(argv: list[str] | None = None) -> int:
164
+ _configure_stdio()
165
+ args = build_parser().parse_args(argv)
166
+ try:
167
+ # serve/apply 仅依赖 manifest(其 repoRoot 在 apply_manifest 内部解析),
168
+ # 可在非 git 目录下运行;其余公开命令需要前置解析仓库。
169
+ if args.command in ("detect", "filter", "prepare", "resolve", "launch"):
170
+ repo = find_repo_root(args.repo)
171
+ if args.command == "filter":
172
+ result = add_auto_theirs_filter(repo, args.path)
173
+ _print({"ok": True, "repo": str(repo), **result})
174
+ return 0
175
+ if args.command == "detect":
176
+ conflicts = detect_conflicts(repo)
177
+ filters = load_auto_theirs_filters(repo)
178
+ auto = [item["path"] for item in conflicts if auto_theirs_path(item["path"], filters)]
179
+ _print({
180
+ "ok": True,
181
+ "repo": str(repo),
182
+ "count": len(conflicts),
183
+ "reviewCount": len(conflicts) - len(auto),
184
+ "autoTheirs": auto,
185
+ "conflicts": conflicts,
186
+ })
187
+ return 0
188
+ if args.command == "prepare":
189
+ manifest = prepare_conflicts(repo, relative_path=args.path, runtime_dir=args.runtime_dir)
190
+ _print({"ok": True, "manifest": str(manifest)})
191
+ return 0
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)
202
+ _print(auto)
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))
213
+ return 0
214
+ if args.command == "serve":
215
+ from merge_server import serve
216
+
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
220
+ decisions = json.loads(Path(args.decisions).read_text(encoding="utf-8"))
221
+ result = apply_manifest(
222
+ args.manifest,
223
+ decisions,
224
+ commit=not args.no_commit,
225
+ push=args.push,
226
+ message=args.message,
227
+ )
228
+ _print(result)
229
+ return 0 if result["success"] else 1
230
+ except (ConflictError, OSError, ValueError, json.JSONDecodeError) as exc:
231
+ _print({"ok": False, "error": str(exc)})
232
+ return 1
233
+
234
+
235
+ if __name__ == "__main__":
236
+ sys.exit(main())