waybar2qs 0.1.0__py3-none-any.whl

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.
waybar2qs/__init__.py ADDED
@@ -0,0 +1,4 @@
1
+ """waybar2qs: Waybar (config.jsonc + style.css) to Quickshell (shell.qml) transpiler."""
2
+
3
+ __version__ = "0.1.0"
4
+ __all__ = ["__version__"]
waybar2qs/cli.py ADDED
@@ -0,0 +1,442 @@
1
+ """Command-line interface for waybar2qs."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ from collections import Counter
7
+ import inspect
8
+ from pathlib import Path
9
+ import re
10
+ import shutil
11
+ import subprocess
12
+ import sys
13
+ import tempfile
14
+ from typing import Any
15
+
16
+ from . import __version__
17
+ from .codegen import generate_quickshell_project
18
+ from .css_parser import load_waybar_css
19
+ from .ir import BarSpec, ConversionReport, ThemeTokens
20
+ from .jsonc import load_waybar_config
21
+ from .normalizer import build_bar_specs
22
+ from .report import format_report_json, format_report_text
23
+
24
+ _QT6_VERSION_RE = re.compile(r"\b6\.\d+")
25
+ _DEFAULT_CONFIG_CANDIDATES: tuple[Path, ...] = (
26
+ Path("~/.config/waybar/config.jsonc"),
27
+ Path("~/.config/waybar/config"),
28
+ )
29
+
30
+
31
+ def _build_parser() -> argparse.ArgumentParser:
32
+ """Create the top-level CLI argument parser."""
33
+ parser = argparse.ArgumentParser(
34
+ prog="waybar2qs",
35
+ description=(
36
+ "Transpile Waybar (config.jsonc + style.css) into a modular "
37
+ "Quickshell (shell.qml) project."
38
+ ),
39
+ )
40
+ parser.add_argument(
41
+ "config",
42
+ nargs="?",
43
+ help=(
44
+ "Path to Waybar config.jsonc or config "
45
+ "(auto-discovers ~/.config/waybar/config.jsonc or config if omitted)"
46
+ ),
47
+ )
48
+ parser.add_argument(
49
+ "-s",
50
+ "--style",
51
+ default=None,
52
+ help="Path to Waybar style.css (auto-discovers sibling style.css if omitted)",
53
+ )
54
+ parser.add_argument(
55
+ "-o",
56
+ "--output",
57
+ default="./quickshell-bar",
58
+ help="Output directory for the generated Quickshell project (default: ./quickshell-bar)",
59
+ )
60
+ parser.add_argument(
61
+ "--compositor",
62
+ choices=("auto", "hyprland", "niri"),
63
+ default="auto",
64
+ help="Target compositor backend (default: auto)",
65
+ )
66
+ parser.add_argument(
67
+ "--report",
68
+ action="store_true",
69
+ help="Print the full Markdown migration report to stdout",
70
+ )
71
+ parser.add_argument(
72
+ "--report-file",
73
+ default=None,
74
+ metavar="PATH",
75
+ help="Write the Markdown migration report to PATH (e.g. MIGRATION_REPORT.md)",
76
+ )
77
+ parser.add_argument(
78
+ "--report-json",
79
+ action="store_true",
80
+ help="Print the machine-readable JSON migration report to stdout",
81
+ )
82
+ parser.add_argument(
83
+ "--lint",
84
+ action="store_true",
85
+ help="Run Qt 6 qmllint on generated .qml files and record the result",
86
+ )
87
+ parser.add_argument(
88
+ "--dry-run",
89
+ action="store_true",
90
+ help="Parse, transpile, and report without writing files to disk",
91
+ )
92
+ parser.add_argument(
93
+ "--version",
94
+ action="version",
95
+ version=f"%(prog)s {__version__}",
96
+ )
97
+ return parser
98
+
99
+
100
+ def _resolve_config_path(raw_config: str | None) -> Path:
101
+ """Resolve explicit or default Waybar configuration path."""
102
+ if raw_config is not None:
103
+ candidate = Path(raw_config).expanduser()
104
+ if not candidate.is_file():
105
+ raise FileNotFoundError(f"Waybar config file not found: {candidate}")
106
+ return candidate
107
+
108
+ expanded = [p.expanduser() for p in _DEFAULT_CONFIG_CANDIDATES]
109
+ for candidate in expanded:
110
+ if candidate.is_file():
111
+ return candidate
112
+
113
+ checked = ", ".join(str(p) for p in expanded)
114
+ raise FileNotFoundError(
115
+ f"No Waybar config found (checked: {checked}). Pass a CONFIG path explicitly."
116
+ )
117
+
118
+
119
+ def _resolve_style_path(raw_style: str | None, config_path: Path) -> Path | None:
120
+ """Resolve explicit or sibling style.css path."""
121
+ if raw_style is not None:
122
+ candidate = Path(raw_style).expanduser()
123
+ if not candidate.is_file():
124
+ raise FileNotFoundError(f"Waybar style.css file not found: {candidate}")
125
+ return candidate
126
+
127
+ sibling = config_path.parent / "style.css"
128
+ return sibling if sibling.is_file() else None
129
+
130
+
131
+ def _is_qt6_qmllint(executable: str) -> bool:
132
+ """Return True if the given qmllint binary reports Qt 6."""
133
+ try:
134
+ proc = subprocess.run(
135
+ [executable, "--version"],
136
+ capture_output=True,
137
+ text=True,
138
+ timeout=5,
139
+ check=False,
140
+ )
141
+ except OSError:
142
+ return False
143
+ except subprocess.TimeoutExpired:
144
+ return False
145
+
146
+ version_text = f"{proc.stdout}\n{proc.stderr}"
147
+ return bool(_QT6_VERSION_RE.search(version_text))
148
+
149
+
150
+ def _find_qt6_qmllint() -> str | None:
151
+ """Auto-detect Qt 6 qmllint binary without falling back to Qt 5 qmllint."""
152
+ candidates: list[str] = []
153
+ qt6_usr = Path("/usr/lib/qt6/bin/qmllint")
154
+ if qt6_usr.is_file():
155
+ candidates.append(str(qt6_usr))
156
+
157
+ for name in ("qmllint6", "qmllint"):
158
+ found = shutil.which(name)
159
+ if found and found not in candidates:
160
+ candidates.append(found)
161
+
162
+ for candidate in candidates:
163
+ if _is_qt6_qmllint(candidate):
164
+ return candidate
165
+ return None
166
+
167
+
168
+ def _run_qmllint(qmllint_bin: str, project_dir: Path, qml_files: list[Path]) -> tuple[bool, str]:
169
+ """Run Qt 6 qmllint across generated QML files and return (passed, output)."""
170
+ if not qml_files:
171
+ return False, "No generated .qml files found to lint."
172
+
173
+ cmd = [
174
+ qmllint_bin,
175
+ "--uncreatable-type",
176
+ "disable",
177
+ "-W",
178
+ "0",
179
+ "-I",
180
+ str(project_dir),
181
+ *(str(p) for p in sorted(qml_files)),
182
+ ]
183
+ try:
184
+ proc = subprocess.run(
185
+ cmd,
186
+ capture_output=True,
187
+ text=True,
188
+ timeout=30,
189
+ check=False,
190
+ )
191
+ except OSError as exc:
192
+ return False, f"Failed to execute {qmllint_bin}: {exc}"
193
+ except subprocess.TimeoutExpired:
194
+ return False, f"Timed out running {qmllint_bin}"
195
+
196
+ combined = "\n".join(part.strip() for part in (proc.stdout, proc.stderr) if part.strip())
197
+ return proc.returncode == 0, combined
198
+
199
+
200
+ def _collect_qml_files(project_dir: Path, generated_files: list[str]) -> list[Path]:
201
+ """Resolve generated .qml files on disk under project_dir."""
202
+ qml_paths: list[Path] = []
203
+ for entry in generated_files:
204
+ if not entry.endswith(".qml"):
205
+ continue
206
+ p = Path(entry)
207
+ candidate = p if p.is_absolute() else (project_dir / p)
208
+ if candidate.is_file():
209
+ qml_paths.append(candidate)
210
+
211
+ if not qml_paths and project_dir.is_dir():
212
+ qml_paths = sorted(project_dir.rglob("*.qml"))
213
+ return qml_paths
214
+
215
+
216
+ def _call_build_bar_specs(
217
+ raw_bars: Any,
218
+ theme: ThemeTokens,
219
+ compositor: str,
220
+ jsonc_warnings: list[str],
221
+ ) -> tuple[list[BarSpec], list[str]]:
222
+ """Invoke normalizer.build_bar_specs across supported parameter conventions."""
223
+ sig = inspect.signature(build_bar_specs)
224
+ params = sig.parameters
225
+ kwargs: dict[str, Any] = {}
226
+ if "compositor" in params:
227
+ kwargs["compositor"] = compositor
228
+ elif "compositor_target" in params:
229
+ kwargs["compositor_target"] = compositor
230
+ if "warnings" in params:
231
+ kwargs["warnings"] = list(jsonc_warnings)
232
+
233
+ result = build_bar_specs(raw_bars, theme, **kwargs)
234
+ if isinstance(result, tuple) and len(result) == 2 and isinstance(result[1], list):
235
+ return result[0], list(result[1])
236
+ return result, []
237
+
238
+
239
+ def _call_codegen(
240
+ bars: list[BarSpec],
241
+ theme: ThemeTokens,
242
+ output_dir: Path,
243
+ *,
244
+ source_config: str,
245
+ source_style: str | None,
246
+ compositor: str,
247
+ dry_run: bool,
248
+ ) -> ConversionReport:
249
+ """Invoke codegen.generate_quickshell_project and return the populated report."""
250
+ report = ConversionReport(
251
+ source_config=source_config,
252
+ source_style=source_style,
253
+ output_dir=str(output_dir),
254
+ bar_count=len(bars),
255
+ compositor_target=compositor,
256
+ unsupported_css=list(theme.unsupported_css),
257
+ )
258
+ sig = inspect.signature(generate_quickshell_project)
259
+ params = sig.parameters
260
+ kwargs: dict[str, Any] = {}
261
+ if "dry_run" in params:
262
+ kwargs["dry_run"] = dry_run
263
+
264
+ supports_dry_run = "dry_run" in params
265
+ if dry_run and not supports_dry_run:
266
+ with tempfile.TemporaryDirectory(prefix="waybar2qs-dryrun-") as tmp:
267
+ tmp_dir = Path(tmp)
268
+ generate_quickshell_project(bars, theme, tmp_dir, report, **kwargs)
269
+ tmp_prefix = str(tmp_dir)
270
+ report.generated_files = [
271
+ f.replace(tmp_prefix, str(output_dir), 1) if f.startswith(tmp_prefix) else f
272
+ for f in report.generated_files
273
+ ]
274
+ else:
275
+ generate_quickshell_project(bars, theme, output_dir, report, **kwargs)
276
+
277
+ return report
278
+
279
+
280
+ def _merge_warnings(existing: list[str], *extra_lists: list[str]) -> list[str]:
281
+ """Deduplicate warnings while preserving insertion order."""
282
+ merged: list[str] = []
283
+ seen: set[str] = set()
284
+ for group in (existing, *extra_lists):
285
+ for msg in group:
286
+ if msg not in seen:
287
+ seen.add(msg)
288
+ merged.append(msg)
289
+ return merged
290
+
291
+
292
+ def _format_brief_summary(report: ConversionReport, *, dry_run: bool) -> str:
293
+ """Build a concise terminal summary when --report / --report-json are not set."""
294
+ counts = Counter(note.support_level for note in report.module_notes)
295
+ prefix = "[dry-run] " if dry_run else ""
296
+ lines = [
297
+ f"{prefix}waybar2qs: {report.source_config} -> {report.output_dir}",
298
+ (
299
+ f" Bars: {report.bar_count} | Target: {report.compositor_target} | "
300
+ f"Modules: {len(report.module_notes)} "
301
+ f"(native={counts.get('native', 0)}, process={counts.get('process', 0)}, "
302
+ f"partial={counts.get('partial', 0)}, stub={counts.get('stub', 0)})"
303
+ ),
304
+ (
305
+ f" Unsupported CSS: {len(report.unsupported_css)} | "
306
+ f"Warnings: {len(report.config_warnings)} | "
307
+ f"Files: {len(report.generated_files)}"
308
+ ),
309
+ ]
310
+ if report.lint_passed is not None:
311
+ status = "PASSED" if report.lint_passed else "FAILED"
312
+ lines.append(f" qmllint: {status}")
313
+ if not report.lint_passed and report.lint_output.strip():
314
+ lines.append(report.lint_output.strip())
315
+ if not dry_run:
316
+ lines.append(f" Run: quickshell -p {report.output_dir}")
317
+ lines.append(" Tip: pass --report for the full migration audit.")
318
+ return "\n".join(lines) + "\n"
319
+
320
+
321
+ def _lint_project(
322
+ bars: list[BarSpec],
323
+ theme: ThemeTokens,
324
+ output_dir: Path,
325
+ report: ConversionReport,
326
+ *,
327
+ source_config: str,
328
+ source_style: str | None,
329
+ compositor: str,
330
+ dry_run: bool,
331
+ ) -> None:
332
+ """Locate Qt 6 qmllint and run it on generated QML files."""
333
+ qmllint_bin = _find_qt6_qmllint()
334
+ if qmllint_bin is None:
335
+ report.lint_passed = False
336
+ report.lint_output = (
337
+ "Qt 6 qmllint not found (checked /usr/lib/qt6/bin/qmllint, qmllint6, qmllint)."
338
+ )
339
+ return
340
+
341
+ if dry_run:
342
+ with tempfile.TemporaryDirectory(prefix="waybar2qs-lint-") as tmp:
343
+ tmp_dir = Path(tmp)
344
+ tmp_report = _call_codegen(
345
+ bars,
346
+ theme,
347
+ tmp_dir,
348
+ source_config=source_config,
349
+ source_style=source_style,
350
+ compositor=compositor,
351
+ dry_run=False,
352
+ )
353
+ qml_files = _collect_qml_files(tmp_dir, tmp_report.generated_files)
354
+ passed, output = _run_qmllint(qmllint_bin, tmp_dir, qml_files)
355
+ output = output.replace(str(tmp_dir), str(output_dir))
356
+ else:
357
+ qml_files = _collect_qml_files(output_dir, report.generated_files)
358
+ passed, output = _run_qmllint(qmllint_bin, output_dir, qml_files)
359
+
360
+ report.lint_passed = passed
361
+ report.lint_output = output
362
+
363
+
364
+ def main(argv: list[str] | None = None) -> int:
365
+ """Entry point for the waybar2qs CLI."""
366
+ parser = _build_parser()
367
+ args = parser.parse_args(argv)
368
+
369
+ try:
370
+ config_path = _resolve_config_path(args.config)
371
+ style_path = _resolve_style_path(args.style, config_path)
372
+ output_dir = Path(args.output).expanduser()
373
+
374
+ raw_loaded = load_waybar_config(config_path)
375
+ if (
376
+ isinstance(raw_loaded, tuple)
377
+ and len(raw_loaded) == 2
378
+ and isinstance(raw_loaded[1], list)
379
+ ):
380
+ raw_bars, jsonc_warnings = raw_loaded
381
+ else:
382
+ raw_bars, jsonc_warnings = raw_loaded, []
383
+
384
+ theme = load_waybar_css(style_path) if style_path is not None else ThemeTokens()
385
+ bars, norm_warnings = _call_build_bar_specs(
386
+ raw_bars, theme, args.compositor, jsonc_warnings
387
+ )
388
+
389
+ source_style_str = str(style_path) if style_path is not None else None
390
+ report = _call_codegen(
391
+ bars,
392
+ theme,
393
+ output_dir,
394
+ source_config=str(config_path),
395
+ source_style=source_style_str,
396
+ compositor=args.compositor,
397
+ dry_run=args.dry_run,
398
+ )
399
+ report.config_warnings = _merge_warnings(
400
+ jsonc_warnings, norm_warnings, report.config_warnings
401
+ )
402
+
403
+ if args.lint:
404
+ _lint_project(
405
+ bars,
406
+ theme,
407
+ output_dir,
408
+ report,
409
+ source_config=str(config_path),
410
+ source_style=source_style_str,
411
+ compositor=args.compositor,
412
+ dry_run=args.dry_run,
413
+ )
414
+
415
+ if args.report_file is not None:
416
+ if args.dry_run:
417
+ print(
418
+ f"Note: skipped writing --report-file ({args.report_file}) due to --dry-run.",
419
+ file=sys.stderr,
420
+ )
421
+ else:
422
+ report_path = Path(args.report_file).expanduser()
423
+ report_path.parent.mkdir(parents=True, exist_ok=True)
424
+ report_path.write_text(format_report_text(report), encoding="utf-8")
425
+
426
+ if args.report_json:
427
+ print(format_report_json(report))
428
+ elif args.report:
429
+ print(format_report_text(report), end="")
430
+ else:
431
+ print(_format_brief_summary(report, dry_run=args.dry_run), end="")
432
+
433
+ if args.lint and report.lint_passed is False:
434
+ return 1
435
+ return 0
436
+ except (OSError, ValueError, TypeError) as exc:
437
+ print(f"Error: {exc}", file=sys.stderr)
438
+ return 1
439
+
440
+
441
+ if __name__ == "__main__":
442
+ raise SystemExit(main())