@kevlns/xlmerge 1.2.1-beta.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,159 @@
1
+ """CLI entry point for Debussy meta XLSX 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 ConflictError, apply_manifest, detect_conflicts, find_repo_root, prepare_conflicts
17
+
18
+
19
+ SCRIPT_PATH = Path(__file__).resolve()
20
+ PACKAGE_ROOT = SCRIPT_DIR.parent
21
+
22
+
23
+ def _print(data) -> None:
24
+ print(json.dumps(data, ensure_ascii=False, indent=2))
25
+
26
+
27
+ def _launch_background(repo: Path, manifest: Path, *, open_browser: bool) -> dict:
28
+ """Start the resolver as a detached child and return its URL promptly."""
29
+ runtime_dir = manifest.parent
30
+ stamp = int(time.time() * 1000)
31
+ stdout_path = runtime_dir / f"resolver-{stamp}.stdout.log"
32
+ stderr_path = runtime_dir / f"resolver-{stamp}.stderr.log"
33
+ command = [
34
+ sys.executable,
35
+ str(SCRIPT_PATH),
36
+ "--repo",
37
+ str(repo),
38
+ "serve",
39
+ "--manifest",
40
+ str(manifest),
41
+ ]
42
+ if not open_browser:
43
+ command.append("--no-browser")
44
+ creationflags = (
45
+ getattr(subprocess, "CREATE_NO_WINDOW", 0)
46
+ | getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0)
47
+ )
48
+ with stdout_path.open("w", encoding="utf-8") as stdout_handle, stderr_path.open("w", encoding="utf-8") as stderr_handle:
49
+ process = subprocess.Popen(
50
+ command,
51
+ cwd=str(PACKAGE_ROOT),
52
+ stdout=stdout_handle,
53
+ stderr=stderr_handle,
54
+ stdin=subprocess.DEVNULL,
55
+ creationflags=creationflags,
56
+ close_fds=True,
57
+ )
58
+
59
+ deadline = time.monotonic() + 15
60
+ url = ""
61
+ while time.monotonic() < deadline:
62
+ output = stdout_path.read_text(encoding="utf-8", errors="replace") if stdout_path.exists() else ""
63
+ for line in output.splitlines():
64
+ if line.startswith("MERGE_SERVER_URL="):
65
+ url = line.split("=", 1)[1].strip()
66
+ break
67
+ if url or process.poll() is not None:
68
+ break
69
+ time.sleep(0.1)
70
+
71
+ if not url:
72
+ if process.poll() is None:
73
+ process.terminate()
74
+ stderr = stderr_path.read_text(encoding="utf-8", errors="replace") if stderr_path.exists() else ""
75
+ raise ConflictError(f"Resolver failed to start: {stderr.strip() or 'URL was not reported within 15 seconds'}")
76
+ return {
77
+ "ok": True,
78
+ "pid": process.pid,
79
+ "url": url,
80
+ "manifest": str(manifest),
81
+ "stdout": str(stdout_path),
82
+ "stderr": str(stderr_path),
83
+ }
84
+
85
+
86
+ def build_parser() -> argparse.ArgumentParser:
87
+ parser = argparse.ArgumentParser(description="Resolve Git XLSX/XLSM conflicts in the sibling Debussy meta repository.")
88
+ parser.add_argument("--repo", default=",", help="Git repository (default: current directory).")
89
+ parser.add_argument("--runtime-dir", help="Optional directory for extracted Git stage workbooks and manifest.")
90
+ subparsers = parser.add_subparsers(dest="command", required=True)
91
+
92
+ subparsers.add_parser("detect", help="List unresolved .xlsx/.xlsm files.")
93
+
94
+ prepare = subparsers.add_parser("prepare", help="Extract base/ours/theirs and build a sheet-aware manifest.")
95
+ prepare.add_argument("--path", help="Only prepare this repository-relative .xlsx/.xlsm path.")
96
+
97
+ resolve = subparsers.add_parser("resolve", help="Prepare conflicts and launch the local visual resolver.")
98
+ resolve.add_argument("--path", help="Only resolve this repository-relative .xlsx/.xlsm path.")
99
+ resolve.add_argument("--no-browser", action="store_true", help="Print the URL without opening a browser.")
100
+
101
+ launch = subparsers.add_parser("launch", help="Prepare conflicts, start the visual resolver in background, and return its URL.")
102
+ launch.add_argument("--path", help="Only resolve this repository-relative .xlsx/.xlsm path.")
103
+ launch.add_argument("--no-browser", action="store_true", help="Start the server without opening a browser.")
104
+
105
+ serve_parser = subparsers.add_parser("serve", help=argparse.SUPPRESS)
106
+ serve_parser.add_argument("--manifest", required=True)
107
+ serve_parser.add_argument("--no-browser", action="store_true")
108
+
109
+ apply_parser = subparsers.add_parser("apply", help="Apply a decisions JSON without launching the UI.")
110
+ apply_parser.add_argument("--manifest", required=True)
111
+ apply_parser.add_argument("--decisions", required=True)
112
+ apply_parser.add_argument("--no-commit", action="store_true")
113
+ apply_parser.add_argument("--push", action="store_true")
114
+ apply_parser.add_argument("--message", default=None, help="Override the auto-generated structured commit message.")
115
+ return parser
116
+
117
+
118
+ def main(argv: list[str] | None = None) -> int:
119
+ args = build_parser().parse_args(argv)
120
+ try:
121
+ repo = find_repo_root(args.repo)
122
+ if args.command == "detect":
123
+ conflicts = detect_conflicts(repo)
124
+ _print({"ok": True, "repo": str(repo), "count": len(conflicts), "conflicts": conflicts})
125
+ return 0
126
+ if args.command == "prepare":
127
+ manifest = prepare_conflicts(repo, relative_path=args.path, runtime_dir=args.runtime_dir)
128
+ _print({"ok": True, "manifest": str(manifest)})
129
+ return 0
130
+ if args.command == "resolve":
131
+ manifest = prepare_conflicts(repo, relative_path=args.path, runtime_dir=args.runtime_dir)
132
+ from merge_server import serve
133
+
134
+ return 0 if serve(manifest, open_browser=not args.no_browser) else 1
135
+ if args.command == "launch":
136
+ manifest = prepare_conflicts(repo, relative_path=args.path, runtime_dir=args.runtime_dir)
137
+ _print(_launch_background(repo, manifest, open_browser=not args.no_browser))
138
+ return 0
139
+ if args.command == "serve":
140
+ from merge_server import serve
141
+
142
+ return 0 if serve(args.manifest, open_browser=not args.no_browser) else 1
143
+ decisions = json.loads(Path(args.decisions).read_text(encoding="utf-8"))
144
+ result = apply_manifest(
145
+ args.manifest,
146
+ decisions,
147
+ commit=not args.no_commit,
148
+ push=args.push,
149
+ message=args.message,
150
+ )
151
+ _print(result)
152
+ return 0 if result["success"] else 1
153
+ except (ConflictError, OSError, ValueError, json.JSONDecodeError) as exc:
154
+ _print({"ok": False, "error": str(exc)})
155
+ return 1
156
+
157
+
158
+ if __name__ == "__main__":
159
+ sys.exit(main())