zig-recipe 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.
zig_recipe/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """zig-recipe: Generate package manager recipes from Zig projects."""
2
+
3
+ __version__ = "0.1.0"
zig_recipe/cli.py ADDED
@@ -0,0 +1,459 @@
1
+ """Command-line interface for zig-recipe."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import logging
7
+ import sys
8
+ from enum import StrEnum
9
+ from pathlib import Path
10
+ from typing import Annotated
11
+
12
+ import typer
13
+ from rich.console import Console
14
+ from rich.logging import RichHandler
15
+
16
+ from zig_recipe import __version__
17
+ from zig_recipe.config import (
18
+ PassConfig,
19
+ RecipeConfig,
20
+ UserConfig,
21
+ load_config_file,
22
+ load_config_text,
23
+ load_user_config_file,
24
+ merge_gentoo_config,
25
+ merge_pass_config,
26
+ )
27
+ from zig_recipe.errors import ZigRecipeError
28
+ from zig_recipe.gentoo.renderer import (
29
+ CommentStyle,
30
+ UnusedDepsMode,
31
+ default_gentoo_filename,
32
+ render_gentoo_deps_only,
33
+ render_gentoo_ebuild,
34
+ resolve_unused_deps_mode,
35
+ )
36
+ from zig_recipe.jinja import render_template
37
+ from zig_recipe.model import RecipeModel
38
+ from zig_recipe.pipeline import analyze_project
39
+ from zig_recipe.ui.progress import ProgressReporter
40
+ from zig_recipe.ui.tables import print_inspect_tables
41
+
42
+ app = typer.Typer(
43
+ name="zig-recipe",
44
+ help="Generate package manager recipes from Zig projects.",
45
+ no_args_is_help=True,
46
+ add_completion=False,
47
+ )
48
+
49
+ stderr_console = Console(stderr=True)
50
+ stdout_console = Console()
51
+
52
+
53
+ class LogLevel(StrEnum):
54
+ ERROR = "error"
55
+ WARNING = "warning"
56
+ INFO = "info"
57
+ DEBUG = "debug"
58
+
59
+
60
+ class InspectFormat(StrEnum):
61
+ TABLE = "table"
62
+ JSON = "json"
63
+
64
+
65
+ # Shared Typer option / argument type aliases across commands.
66
+ ProjectArg = Annotated[
67
+ Path | None,
68
+ typer.Argument(
69
+ help="Project directory or build.zig (defaults to current directory).",
70
+ show_default=False,
71
+ ),
72
+ ]
73
+ ZigOpt = Annotated[
74
+ str | None,
75
+ typer.Option("--zig", help="Zig executable to use (default: zig).", show_default=False),
76
+ ]
77
+ ConfigOpt = Annotated[
78
+ str | None,
79
+ typer.Option(
80
+ "--config",
81
+ help="TOML configuration file ('-' for stdin).",
82
+ show_default=False,
83
+ ),
84
+ ]
85
+ NoUserConfigOpt = Annotated[
86
+ bool,
87
+ typer.Option(
88
+ "--no-user-config",
89
+ help="Ignore the user config file (~/.config/zig-recipe/config.toml).",
90
+ rich_help_panel="Advanced",
91
+ ),
92
+ ]
93
+ FetchOpt = Annotated[
94
+ bool,
95
+ typer.Option(
96
+ "--fetch/--no-fetch",
97
+ help="Download missing dependencies into cache (use --no-fetch to run offline).",
98
+ ),
99
+ ]
100
+ TarballDirOpt = Annotated[
101
+ Path | None,
102
+ typer.Option(
103
+ "--tarball-dir",
104
+ help=(
105
+ "Where to save the bundled git-dependencies archive, if any git URLs "
106
+ "cannot be converted to tarballs."
107
+ ),
108
+ rich_help_panel="Advanced",
109
+ ),
110
+ ]
111
+ CacheDirOpt = Annotated[
112
+ Path | None,
113
+ typer.Option(
114
+ "--cache-dir",
115
+ envvar="ZIG_RECIPE_CACHE_DIR",
116
+ help="Override zig-recipe cache directory.",
117
+ rich_help_panel="Advanced",
118
+ ),
119
+ ]
120
+
121
+
122
+ def _version_callback(value: bool) -> None:
123
+ if value:
124
+ typer.echo(f"zig-recipe {__version__}")
125
+ raise typer.Exit()
126
+
127
+
128
+ @app.callback()
129
+ def main_callback(
130
+ version: Annotated[
131
+ bool,
132
+ typer.Option(
133
+ "--version",
134
+ callback=_version_callback,
135
+ is_eager=True,
136
+ help="Show zig-recipe version and exit.",
137
+ ),
138
+ ] = False,
139
+ log_level: Annotated[
140
+ LogLevel,
141
+ typer.Option(
142
+ "--log-level",
143
+ "-l",
144
+ case_sensitive=False,
145
+ help="Logging verbosity.",
146
+ ),
147
+ ] = LogLevel.INFO,
148
+ ) -> None:
149
+ logging.basicConfig(
150
+ level=getattr(logging, log_level.value.upper()),
151
+ format="%(message)s",
152
+ handlers=[RichHandler(console=stderr_console, show_path=False, show_time=False)],
153
+ force=True,
154
+ )
155
+
156
+
157
+ def _extract_zig_build_args(ctx: typer.Context) -> tuple[str, ...]:
158
+ args = list(ctx.args)
159
+ if args and args[0] == "--":
160
+ args = args[1:]
161
+ return tuple(args)
162
+
163
+
164
+ def _load_effective_configs(
165
+ *,
166
+ ctx: typer.Context,
167
+ config_source: str | None,
168
+ no_user_config: bool,
169
+ ) -> tuple[UserConfig, RecipeConfig, PassConfig]:
170
+ user_cfg = UserConfig() if no_user_config else load_user_config_file()
171
+ project_cfg = RecipeConfig()
172
+ if config_source is not None:
173
+ if config_source == "-":
174
+ project_cfg = load_config_text(sys.stdin.read(), source="<stdin>")
175
+ else:
176
+ project_cfg = load_config_file(Path(config_source))
177
+
178
+ merged_recipe = RecipeConfig(
179
+ package=project_cfg.package,
180
+ build=project_cfg.build,
181
+ gentoo=merge_gentoo_config(user=user_cfg.gentoo, project=project_cfg.gentoo),
182
+ )
183
+ pass_cfg = merge_pass_config(
184
+ file_config=project_cfg.build,
185
+ cli_base_args=_extract_zig_build_args(ctx),
186
+ )
187
+ return user_cfg, merged_recipe, pass_cfg
188
+
189
+
190
+ def _run_analysis(
191
+ *,
192
+ ctx: typer.Context,
193
+ project: Path | None,
194
+ zig: str | None,
195
+ config: str | None,
196
+ fetch: bool,
197
+ no_user_config: bool,
198
+ cache_dir: Path | None,
199
+ tarball_dir: Path | None = None,
200
+ configs: tuple[UserConfig, RecipeConfig, PassConfig] | None = None,
201
+ ) -> RecipeModel:
202
+ user_cfg, recipe_cfg, pass_config = (
203
+ configs
204
+ if configs is not None
205
+ else _load_effective_configs(
206
+ ctx=ctx,
207
+ config_source=config,
208
+ no_user_config=no_user_config,
209
+ )
210
+ )
211
+ effective_zig = zig or user_cfg.general.zig or "zig"
212
+ effective_cache = cache_dir if cache_dir is not None else user_cfg.general.cache_dir
213
+ with ProgressReporter(stderr_console) as progress:
214
+ return analyze_project(
215
+ project_path=project or Path("."),
216
+ zig_exe=effective_zig,
217
+ cache_dir=effective_cache,
218
+ fetch=fetch,
219
+ pass_config=pass_config,
220
+ recipe_config=recipe_cfg,
221
+ tarball_dir=tarball_dir,
222
+ progress=progress,
223
+ )
224
+
225
+
226
+ def _write_output(content: str, output: str | None, default_name: str) -> None:
227
+ if output == "-":
228
+ sys.stdout.write(content)
229
+ return
230
+ target = Path(output) if output is not None else Path(default_name)
231
+ target.parent.mkdir(parents=True, exist_ok=True)
232
+ target.write_text(content, encoding="utf-8", newline="\n")
233
+ stderr_console.print(f"[green]Wrote[/green] {target}")
234
+
235
+
236
+ @app.command(
237
+ context_settings={"allow_extra_args": True, "ignore_unknown_options": True},
238
+ )
239
+ def gentoo(
240
+ ctx: typer.Context,
241
+ project: ProjectArg = None,
242
+ output: Annotated[
243
+ str | None,
244
+ typer.Option(
245
+ "--output",
246
+ "-o",
247
+ help=(
248
+ "Output path ('-' for stdout; defaults to <name>-<version>.ebuild, "
249
+ "or stdout with --deps-only)."
250
+ ),
251
+ ),
252
+ ] = None,
253
+ zig: ZigOpt = None,
254
+ comments: Annotated[
255
+ CommentStyle | None,
256
+ typer.Option(
257
+ "--comments",
258
+ case_sensitive=False,
259
+ help="Comment detail level: full, compact, or none (default: full).",
260
+ show_default=False,
261
+ ),
262
+ ] = None,
263
+ unused_deps: Annotated[
264
+ UnusedDepsMode | None,
265
+ typer.Option(
266
+ "--unused-deps",
267
+ case_sensitive=False,
268
+ help=(
269
+ "How to handle unused dependencies in ZBS_DEPENDENCIES "
270
+ "(default: comment, or drop with --comments none)."
271
+ ),
272
+ show_default=False,
273
+ ),
274
+ ] = None,
275
+ deps_only: Annotated[
276
+ bool,
277
+ typer.Option(
278
+ "--deps-only",
279
+ help="Print only the ZBS_DEPENDENCIES array (handy when bumping an ebuild).",
280
+ ),
281
+ ] = False,
282
+ config: ConfigOpt = None,
283
+ fetch: FetchOpt = True,
284
+ template: Annotated[
285
+ Path | None,
286
+ typer.Option(
287
+ "--template",
288
+ help="Custom Jinja2 template overriding the built-in one.",
289
+ rich_help_panel="Advanced",
290
+ ),
291
+ ] = None,
292
+ experimental_zbs_packages: Annotated[
293
+ bool,
294
+ typer.Option(
295
+ "--experimental-zbs-packages",
296
+ help=(
297
+ "Emit ZBS_PACKAGES / ZBS_BUNDLED_PACKAGES with conditional SRC_URI "
298
+ "(requires zig.eclass support)."
299
+ ),
300
+ rich_help_panel="Advanced",
301
+ ),
302
+ ] = False,
303
+ no_user_config: NoUserConfigOpt = False,
304
+ tarball_dir: TarballDirOpt = None,
305
+ cache_dir: CacheDirOpt = None,
306
+ ) -> None:
307
+ """Generate a Gentoo ebuild.
308
+
309
+ Any arguments after '--' are forwarded to 'zig build' as base arguments
310
+ (e.g. '-- -Dbackend=wayland'). Use '--config' to run additional variant
311
+ passes and detect conditional dependencies.
312
+ """
313
+ try:
314
+ configs = _load_effective_configs(
315
+ ctx=ctx,
316
+ config_source=config,
317
+ no_user_config=no_user_config,
318
+ )
319
+ _, recipe_cfg, _ = configs
320
+ effective_comments = (
321
+ comments
322
+ if comments is not None
323
+ else (
324
+ CommentStyle(recipe_cfg.gentoo.comments)
325
+ if recipe_cfg.gentoo.comments is not None
326
+ else CommentStyle.FULL
327
+ )
328
+ )
329
+ effective_unused_opt = (
330
+ unused_deps
331
+ if unused_deps is not None
332
+ else (
333
+ UnusedDepsMode(recipe_cfg.gentoo.unused_deps)
334
+ if recipe_cfg.gentoo.unused_deps is not None
335
+ else None
336
+ )
337
+ )
338
+ effective_unused = resolve_unused_deps_mode(effective_comments, effective_unused_opt)
339
+
340
+ model = _run_analysis(
341
+ ctx=ctx,
342
+ project=project,
343
+ zig=zig,
344
+ config=config,
345
+ fetch=fetch,
346
+ no_user_config=no_user_config,
347
+ cache_dir=cache_dir,
348
+ tarball_dir=tarball_dir,
349
+ configs=configs,
350
+ )
351
+ if deps_only:
352
+ rendered = render_gentoo_deps_only(
353
+ model,
354
+ comments=effective_comments,
355
+ unused_deps=effective_unused,
356
+ use_zbs_packages=experimental_zbs_packages,
357
+ )
358
+ else:
359
+ rendered = render_gentoo_ebuild(
360
+ model,
361
+ comments=effective_comments,
362
+ unused_deps=effective_unused,
363
+ use_zbs_packages=experimental_zbs_packages,
364
+ template_path=template,
365
+ )
366
+ except ZigRecipeError as exc:
367
+ stderr_console.print(f"[red]Error:[/red] {exc}")
368
+ raise typer.Exit(code=1) from exc
369
+
370
+ effective_output = output if output is not None else ("-" if deps_only else None)
371
+ _write_output(rendered, effective_output, default_gentoo_filename(model))
372
+
373
+
374
+ @app.command(
375
+ context_settings={"allow_extra_args": True, "ignore_unknown_options": True},
376
+ )
377
+ def inspect(
378
+ ctx: typer.Context,
379
+ project: ProjectArg = None,
380
+ fmt: Annotated[
381
+ InspectFormat,
382
+ typer.Option("--format", "-f", case_sensitive=False, help="Output format."),
383
+ ] = InspectFormat.TABLE,
384
+ zig: ZigOpt = None,
385
+ config: ConfigOpt = None,
386
+ fetch: FetchOpt = True,
387
+ no_user_config: NoUserConfigOpt = False,
388
+ cache_dir: CacheDirOpt = None,
389
+ ) -> None:
390
+ """Print build metadata (packages, options, system libraries) as a table or JSON.
391
+
392
+ Any arguments after '--' are forwarded to 'zig build' as base arguments
393
+ (e.g. '-- -Dbackend=wayland'). Use '--config' to run additional variant
394
+ passes and detect conditional dependencies.
395
+ """
396
+ try:
397
+ model = _run_analysis(
398
+ ctx=ctx,
399
+ project=project,
400
+ zig=zig,
401
+ config=config,
402
+ fetch=fetch,
403
+ no_user_config=no_user_config,
404
+ cache_dir=cache_dir,
405
+ )
406
+ except ZigRecipeError as exc:
407
+ stderr_console.print(f"[red]Error:[/red] {exc}")
408
+ raise typer.Exit(code=1) from exc
409
+
410
+ if fmt is InspectFormat.JSON:
411
+ sys.stdout.write(json.dumps(model.to_dict(), indent=2) + "\n")
412
+ else:
413
+ print_inspect_tables(stdout_console, model)
414
+
415
+
416
+ @app.command(
417
+ context_settings={"allow_extra_args": True, "ignore_unknown_options": True},
418
+ )
419
+ def render(
420
+ ctx: typer.Context,
421
+ template: Annotated[
422
+ Path,
423
+ typer.Argument(help="Path to a Jinja2 template file."),
424
+ ],
425
+ project: ProjectArg = None,
426
+ output: Annotated[
427
+ str,
428
+ typer.Option("--output", "-o", help="Output file path ('-' for stdout)."),
429
+ ] = "-",
430
+ zig: ZigOpt = None,
431
+ config: ConfigOpt = None,
432
+ fetch: FetchOpt = True,
433
+ no_user_config: NoUserConfigOpt = False,
434
+ tarball_dir: TarballDirOpt = None,
435
+ cache_dir: CacheDirOpt = None,
436
+ ) -> None:
437
+ """Generate a recipe using a custom Jinja2 template.
438
+
439
+ Any arguments after '--' are forwarded to 'zig build' as base arguments
440
+ (e.g. '-- -Dbackend=wayland'). Use '--config' to run additional variant
441
+ passes and detect conditional dependencies.
442
+ """
443
+ try:
444
+ model = _run_analysis(
445
+ ctx=ctx,
446
+ project=project,
447
+ zig=zig,
448
+ config=config,
449
+ fetch=fetch,
450
+ no_user_config=no_user_config,
451
+ cache_dir=cache_dir,
452
+ tarball_dir=tarball_dir,
453
+ )
454
+ rendered = render_template(model, template_path=template)
455
+ except ZigRecipeError as exc:
456
+ stderr_console.print(f"[red]Error:[/red] {exc}")
457
+ raise typer.Exit(code=1) from exc
458
+
459
+ _write_output(rendered, output, "recipe.out")