@kevlns/xlmerge 1.3.1 → 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.
@@ -0,0 +1,155 @@
1
+ [CmdletBinding()]
2
+ param([string]$ParametersPath, [string]$CleanupParametersPath)
3
+
4
+ $ErrorActionPreference = 'Stop'
5
+ $excel = $null
6
+ $book = $null
7
+ $excelPid = $null
8
+ $ownedExcel = $false
9
+ $excelStartFileTimeUtc = $null
10
+ $statePath = $null
11
+
12
+ if (![string]::IsNullOrWhiteSpace($CleanupParametersPath)) {
13
+ try {
14
+ $owned = Get-Content -LiteralPath $CleanupParametersPath -Raw -Encoding UTF8 | ConvertFrom-Json
15
+ $p = Get-Process -Id ([int]$owned.pid) -ErrorAction SilentlyContinue
16
+ if ($p -and $p.ProcessName -ieq 'EXCEL') {
17
+ $ft = $p.StartTime.ToUniversalTime().ToFileTimeUtc()
18
+ if ($ft -eq [int64]$owned.startFileTimeUtc) {
19
+ Stop-Process -Id $p.Id -Force -ErrorAction SilentlyContinue
20
+ }
21
+ }
22
+ exit 0
23
+ } catch { exit 1 }
24
+ }
25
+ if ([string]::IsNullOrWhiteSpace($ParametersPath)) { throw 'ParametersPath is required' }
26
+
27
+ if (-not ('XlmergeExcelWindow' -as [type])) {
28
+ Add-Type @"
29
+ using System;
30
+ using System.Runtime.InteropServices;
31
+ public static class XlmergeExcelWindow {
32
+ [DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint processId);
33
+ }
34
+ "@
35
+ }
36
+
37
+ function Write-State([string]$status, [string]$errorText = $null) {
38
+ if ([string]::IsNullOrWhiteSpace($statePath)) { return }
39
+ $state = [ordered]@{ status = $status }
40
+ if ($null -ne $excelPid) {
41
+ $state.pid = [int]$excelPid
42
+ if ($null -ne $excelStartFileTimeUtc) { $state.startFileTimeUtc = [int64]$excelStartFileTimeUtc }
43
+ }
44
+ if ($null -ne $errorText) { $state.error = $errorText }
45
+ $state | ConvertTo-Json -Compress | Set-Content -LiteralPath $statePath -Encoding UTF8
46
+ }
47
+
48
+ try {
49
+ $parameters = Get-Content -LiteralPath $ParametersPath -Raw -Encoding UTF8 | ConvertFrom-Json
50
+ $source = [IO.Path]::GetFullPath([string]$parameters.source)
51
+ $result = [IO.Path]::GetFullPath([string]$parameters.result)
52
+ $statePath = [IO.Path]::GetFullPath([string]$parameters.state)
53
+ $timeoutSeconds = [int]$parameters.timeoutSeconds
54
+ if ($timeoutSeconds -lt 1) { throw 'timeoutSeconds must be positive' }
55
+ if (!(Test-Path -LiteralPath $source -PathType Leaf)) { throw "Source workbook does not exist: $source" }
56
+ $parent = Split-Path -Parent $result
57
+ if (!(Test-Path -LiteralPath $parent)) { New-Item -ItemType Directory -Path $parent -Force | Out-Null }
58
+
59
+ # Excel constants are used as numbers so this script has no interop assembly
60
+ # dependency. AutomationSecurity=3 is msoAutomationSecurityForceDisable.
61
+ $existingExcelPids = @(Get-Process -Name EXCEL -ErrorAction SilentlyContinue | ForEach-Object { $_.Id })
62
+ $excel = New-Object -ComObject Excel.Application
63
+ $window = [IntPtr]$excel.Hwnd
64
+ [uint32]$windowPid = 0
65
+ [XlmergeExcelWindow]::GetWindowThreadProcessId($window, [ref]$windowPid) | Out-Null
66
+ if ($windowPid -eq 0) { throw 'Unable to identify the Excel process created for this calculation' }
67
+ $excelProcess = Get-Process -Id ([int]$windowPid) -ErrorAction Stop
68
+ if ($excelProcess.ProcessName -ine 'EXCEL') { throw 'Excel window belongs to an unexpected process' }
69
+ if ($existingExcelPids -contains $excelProcess.Id) { throw 'Excel COM attached to a pre-existing user Excel process' }
70
+ $excelPid = $excelProcess.Id
71
+ $excelStartFileTimeUtc = [int64]$excelProcess.StartTime.ToUniversalTime().ToFileTimeUtc()
72
+ $ownedExcel = $true
73
+ Write-State 'running'
74
+
75
+ $excel.Visible = $false
76
+ $excel.DisplayAlerts = $false
77
+ $excel.EnableEvents = $false
78
+ $excel.ScreenUpdating = $false
79
+ $excel.AskToUpdateLinks = $false
80
+ $excel.AutomationSecurity = 3
81
+ $excel.UserControl = $false
82
+ # Iterative calculation can make a circular workbook appear to have a
83
+ # stable value. It is never safe for a conflict snapshot.
84
+ if ($excel.Iteration) { throw 'Excel iterative calculation is enabled' }
85
+
86
+ # UpdateLinks=0 and ReadOnly=true are positional arguments in the Excel COM
87
+ # API. The temporary source is never saved in place.
88
+ $book = $excel.Workbooks.Open($source, 0, $true)
89
+ if ($excel.Iteration) { throw 'Workbook enables iterative calculation' }
90
+ $excel.CalculateFullRebuild()
91
+ $deadline = [DateTime]::UtcNow.AddSeconds($timeoutSeconds)
92
+ while ($excel.CalculationState -ne 0) { # xlDone
93
+ if ([DateTime]::UtcNow -gt $deadline) { throw 'Excel calculation did not reach xlDone before timeout' }
94
+ Start-Sleep -Milliseconds 100
95
+ }
96
+ if ([DateTime]::UtcNow -gt $deadline) { throw 'Excel calculation exceeded timeout' }
97
+ try {
98
+ $circular = $excel.CircularReference
99
+ if ($null -ne $circular) { throw 'Workbook contains a circular reference' }
100
+ } catch {
101
+ if ($_.Exception.Message -like '*circular reference*') { throw }
102
+ throw "Unable to verify circular references: $($_.Exception.Message)"
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
+ }
122
+ $book.SaveCopyAs($result)
123
+ if (!(Test-Path -LiteralPath $result -PathType Leaf)) { throw 'Excel did not produce a result file' }
124
+ Write-State 'completed'
125
+ exit 0
126
+ }
127
+ catch {
128
+ Write-State 'failed' $_.Exception.Message
129
+ exit 1
130
+ }
131
+ finally {
132
+ if ($null -ne $book) {
133
+ try { $book.Close($false) } catch { }
134
+ try { [Runtime.InteropServices.Marshal]::ReleaseComObject($book) | Out-Null } catch { }
135
+ }
136
+ if ($null -ne $excel -and $ownedExcel) {
137
+ try { $excel.Quit() } catch { }
138
+ }
139
+ if ($null -ne $excel) {
140
+ try { [Runtime.InteropServices.Marshal]::ReleaseComObject($excel) | Out-Null } catch { }
141
+ }
142
+ [GC]::Collect()
143
+ [GC]::WaitForPendingFinalizers()
144
+ # Quit can leave an orphaned hidden Excel process while COM child ranges
145
+ # are being finalized. Ownership is exact: PID + creation timestamp.
146
+ if ($null -ne $excelProcess -and $null -ne $excelPid) {
147
+ try {
148
+ $left = Get-Process -Id ([int]$excelPid) -ErrorAction SilentlyContinue
149
+ if ($left -and $left.ProcessName -ieq 'EXCEL' -and
150
+ $left.StartTime.ToUniversalTime().ToFileTimeUtc() -eq $excelStartFileTimeUtc) {
151
+ Stop-Process -Id ([int]$excelPid) -Force -ErrorAction SilentlyContinue
152
+ }
153
+ } catch { }
154
+ }
155
+ }
@@ -1,222 +1,222 @@
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
+ 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())