utilifex 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.
utilifex/__init__.py ADDED
@@ -0,0 +1,15 @@
1
+ """`utilifex`: helpers for the scripts of the utilifex toolkit.
2
+
3
+ The Python helpers under `utilifex.*` mirror the bash helpers under
4
+ `lib/bash/`. The JSON report of `utilifex.report` has the fields of the one
5
+ `lib/bash/json.sh` writes (see `tests/lib/test_report_parity.py`).
6
+ """
7
+
8
+ from importlib import metadata
9
+
10
+ try:
11
+ __version__: str = metadata.version("utilifex")
12
+ except metadata.PackageNotFoundError: # editable install / source checkout
13
+ __version__ = "0.0.0+local"
14
+
15
+ __all__ = ["__version__"]
utilifex/cli.py ADDED
@@ -0,0 +1,457 @@
1
+ """Typer-based CLI base: gives every Python script the universal flags.
2
+
3
+ Single-script utilities under `scripts/` use the `@app.callback` pattern,
4
+ not subcommands. Pattern:
5
+
6
+ from utilifex.cli import build_app, finalize_report, get_context, prepare_context
7
+ from utilifex.cli import DryRun, JsonReport, LogLevel, ShowVersion
8
+ from utilifex.report import Report
9
+
10
+ app = build_app(name="my-tool", category="git")
11
+
12
+ @app.callback(invoke_without_command=True)
13
+ def main(
14
+ ctx: typer.Context,
15
+ # script-specific flags first:
16
+ path: str = typer.Argument(..., help="Target path."),
17
+ # universal flags last:
18
+ dry_run: DryRun = False,
19
+ json_report: JsonReport = None,
20
+ log_level: LogLevel = "INFO",
21
+ version: ShowVersion = False,
22
+ ) -> None:
23
+ prepare_context(
24
+ ctx, name="my-tool", category="git",
25
+ dry_run=dry_run, json_report=json_report, log_level=log_level,
26
+ )
27
+ cli = get_context(ctx)
28
+ report = Report.start("my-tool", "git")
29
+ # ... work ...
30
+ finalize_report(report, "success", 0, json_report=cli.json_report)
31
+
32
+ if __name__ == "__main__":
33
+ app()
34
+
35
+ The `DryRun`/`JsonReport`/`LogLevel`/`ShowVersion` annotated types pre-define
36
+ the universal flags so each script repeats the same surface without
37
+ copy-pasted Typer Option calls.
38
+ """
39
+
40
+ from __future__ import annotations
41
+
42
+ import contextlib
43
+ import os
44
+ import signal
45
+ import sys
46
+ import threading
47
+ from collections.abc import Generator
48
+ from dataclasses import dataclass
49
+ from datetime import date
50
+ from pathlib import Path
51
+ from types import FrameType
52
+ from typing import Annotated, Any, Final, NoReturn
53
+
54
+ import click
55
+ import typer
56
+ from click.core import ParameterSource
57
+ from typer.core import TyperGroup
58
+
59
+ from utilifex import __version__
60
+ from utilifex.files import INTERRUPTED_STATUS, OutputRefusedError, check_destination
61
+ from utilifex.headers import HELD, StatusError, release_status
62
+ from utilifex.log import configure as configure_logging
63
+ from utilifex.log import get_logger
64
+ from utilifex.proc import dry_run_value
65
+
66
+ logger = get_logger(__name__)
67
+
68
+ # Bounds for integer options whose value reaches C. A Python int has no bound, so an option
69
+ # without one lets a value through that ends the run in an OverflowError traceback, exit 1;
70
+ # `typer.Option(..., max=...)` refuses it with exit 2 and a message naming the option.
71
+
72
+ #: The longest timeout, in seconds, a script passes to `subprocess.run(..., timeout=)`. With its
73
+ #: output captured, subprocess waits in poll(2), whose timeout is an `int` of milliseconds
74
+ #: (man 2 poll), so `(2**31 - 1) // 1000` seconds, about 24 days, is the longest it accepts.
75
+ MAX_TIMEOUT_SECONDS: Final[int] = (2**31 - 1) // 1000
76
+
77
+ #: The most days an age option may go back: the days from 0001-01-01, the earliest
78
+ #: `datetime`, to the Unix epoch. A cutoff that far before any present date stays inside
79
+ #: `datetime`'s range, and is older than anything a script is asked about.
80
+ MAX_DAYS_AGO: Final[int] = (date(1970, 1, 1) - date.min).days
81
+
82
+
83
+ @dataclass(frozen=True, slots=True)
84
+ class CliContext:
85
+ """Shared CLI state populated by the universal flags."""
86
+
87
+ name: str
88
+ category: str
89
+ dry_run: bool
90
+ json_report: Path | None
91
+ log_level: str
92
+
93
+
94
+ def _version_callback(ctx: typer.Context, value: bool) -> None:
95
+ """Eager Typer callback for `--version`: print `<name> <version>` and exit 0.
96
+
97
+ The name is the one the program was started by without its `.py`, as `args_print_version`
98
+ in lib/bash/args.sh prints a shell script's (`${0##*/}` without `.sh`): `registry-cleanup`
99
+ for `scripts/docker/registry-cleanup.py`, `find-script` for `bin/find-script`.
100
+ """
101
+ if value:
102
+ root = ctx.find_root()
103
+ name = root.info_name or ""
104
+ # Run as `python -m PACKAGE`, Click names the program by that whole command line.
105
+ if not name or " " in name:
106
+ name = root.command.name or "utilifex"
107
+ name = name.removesuffix(".py")
108
+ typer.echo(f"{name} {__version__}")
109
+ raise typer.Exit(code=0)
110
+
111
+
112
+ def _dry_run(ctx: typer.Context, value: bool) -> bool:
113
+ """Typer callback for `--dry-run`: the command line wins, else `$DRY_RUN`, read strictly.
114
+
115
+ `$DRY_RUN` is read as `dry_run_validate` in lib/bash/dryrun.sh reads it
116
+ (`utilifex.proc.dry_run_value`): a value other than 0, 1 or empty is a usage error, exit 2,
117
+ even beside `--dry-run`, so a mistyped environment is never silently overridden.
118
+ """
119
+ try:
120
+ from_environment = dry_run_value(os.environ.get("DRY_RUN"))
121
+ except ValueError as e:
122
+ raise typer.BadParameter(str(e)) from e
123
+ if ctx.get_parameter_source("dry_run") is ParameterSource.COMMANDLINE:
124
+ return value
125
+ return from_environment
126
+
127
+
128
+ # Pre-typed annotations that scripts drop into their main function signature.
129
+ # The values they default to live on the function (e.g. `dry_run: DryRun = False`).
130
+ DryRun = Annotated[
131
+ bool,
132
+ typer.Option(
133
+ "--dry-run/--no-dry-run",
134
+ "-n",
135
+ callback=_dry_run,
136
+ help="Print what would run; do not change anything. DRY_RUN=1 in the environment "
137
+ "does the same; DRY_RUN may be only 0, 1 or empty.",
138
+ ),
139
+ ]
140
+ JsonReport = Annotated[
141
+ Path | None,
142
+ typer.Option(
143
+ "--json-report",
144
+ metavar="PATH",
145
+ help="Emit a machine-readable JSON report to PATH.",
146
+ ),
147
+ ]
148
+ #: The levels `--log-level` takes, any case, as `log_level_known` in lib/bash/log.sh: another
149
+ #: value, on the command line or in UTILIFEX_LOG_LEVEL, is refused with exit 2.
150
+ LOG_LEVELS: Final[tuple[str, ...]] = ("DEBUG", "INFO", "WARN", "WARNING", "ERROR", "ERR")
151
+
152
+
153
+ def _known_log_level(value: str) -> str:
154
+ """Typer callback for `--log-level`: `value` when it is a level, else a usage error."""
155
+ if value.upper() not in LOG_LEVELS:
156
+ msg = f"{value!r} is not one of DEBUG, INFO, WARN, ERROR"
157
+ raise typer.BadParameter(msg)
158
+ return value
159
+
160
+
161
+ LogLevel = Annotated[
162
+ str,
163
+ typer.Option(
164
+ "--log-level",
165
+ envvar="UTILIFEX_LOG_LEVEL",
166
+ callback=_known_log_level,
167
+ help="DEBUG | INFO (default) | WARN | ERROR.",
168
+ ),
169
+ ]
170
+ ShowVersion = Annotated[
171
+ bool,
172
+ typer.Option(
173
+ "--version",
174
+ callback=_version_callback,
175
+ is_eager=True,
176
+ help="Print version and exit.",
177
+ ),
178
+ ]
179
+
180
+
181
+ #: The signals that end a run as interrupted: docs/style.md, "130 Interrupted", the status
182
+ #: lib/bash/traps.sh gives HUP, INT and TERM.
183
+ _INTERRUPTING: Final = (signal.SIGHUP, signal.SIGINT, signal.SIGTERM)
184
+
185
+ #: The context `prepare_context` set up for this run, read when the run ends early.
186
+ _RUN: list[CliContext] = []
187
+
188
+
189
+ class Interrupted(BaseException):
190
+ """A run ended by SIGHUP, SIGINT or SIGTERM, raised where the main thread is.
191
+
192
+ Raised, not handled in place, so every `finally` block and context manager between the
193
+ signal and the app runs, a temporary file or directory is removed and the report is
194
+ written. A `BaseException`, as `KeyboardInterrupt` is, so `except Exception` does not
195
+ swallow it; not a `KeyboardInterrupt`, which Click turns into "Aborted!" and exit 1.
196
+ """
197
+
198
+ def __init__(self, signum: int) -> None:
199
+ """Record the signal that ended the run."""
200
+ self.signal_name = signal.Signals(signum).name
201
+ super().__init__(self.signal_name)
202
+
203
+
204
+ def _raise_interrupted(signum: int, frame: FrameType | None) -> NoReturn:
205
+ """Signal handler: raise `Interrupted` in the main thread."""
206
+ del frame
207
+ raise Interrupted(signum)
208
+
209
+
210
+ @contextlib.contextmanager
211
+ def _interruptions_raise() -> Generator[None]:
212
+ """For the block, make SIGHUP, SIGINT and SIGTERM raise `Interrupted`.
213
+
214
+ Python's default ends the process at once on SIGTERM and SIGHUP, without unwinding.
215
+ Left alone outside the main thread, where no handler can be set.
216
+ """
217
+ if threading.current_thread() is not threading.main_thread():
218
+ yield
219
+ return
220
+ previous = {number: signal.signal(number, _raise_interrupted) for number in _INTERRUPTING}
221
+ try:
222
+ yield
223
+ finally:
224
+ for number, handler in previous.items():
225
+ signal.signal(number, handler)
226
+
227
+
228
+ def _write_failure(message: str, exit_code: int) -> None:
229
+ """Write the run's report as a failure with `message`, when the run asked for one."""
230
+ if not _RUN:
231
+ return
232
+ run = _RUN[0]
233
+ report = active_report() or Report.start(run.name, run.category)
234
+ report.add_error(message)
235
+ report.finalize("failure", exit_code)
236
+ if run.json_report is not None:
237
+ try:
238
+ report.emit(run.json_report)
239
+ except OSError as e:
240
+ logger.error("could not write the report %s: %s", run.json_report, e)
241
+
242
+
243
+ def held_reason() -> str | None:
244
+ """The Held-Reason of the script being run (`sys.argv[0]`) when its header says it is held.
245
+
246
+ None for a released script, or for a program whose first argument is no script with a header
247
+ (a test runner). A held header without a reason reads as "no reason given":
248
+ threat-model-check reports that header, and the script is still said to be held. Read by
249
+ `utilifex.headers.release_status`, as `_args_release_status` in lib/bash/args.sh reads it
250
+ with `header_status`.
251
+
252
+ Raises:
253
+ typer.Exit: Code 2, the error logged naming the file, when the header's Status is
254
+ missing or is neither released nor held: such a script is neither state.
255
+ """
256
+ try:
257
+ status = release_status(Path(sys.argv[0])) if sys.argv else None
258
+ except StatusError as e:
259
+ logger.error("%s", e)
260
+ raise typer.Exit(code=2) from e
261
+ if status is None or status[0] != HELD:
262
+ return None
263
+ return status[1]
264
+
265
+
266
+ class _ScriptGroup(TyperGroup):
267
+ """The Click group of a script and its subcommands: a held script's help says so first."""
268
+
269
+ def format_help(self, ctx: click.Context, formatter: click.HelpFormatter) -> None:
270
+ """Print "HELD, not yet released: REASON" before the help of a held script.
271
+
272
+ Written straight out, before the help: Typer prints its rich help itself, not through the
273
+ formatter, so a line added to the formatter would come after it.
274
+ """
275
+ reason = held_reason()
276
+ if reason is not None:
277
+ click.echo(f"HELD, not yet released: {reason}")
278
+ super().format_help(ctx, formatter)
279
+
280
+ def collect_usage_pieces(self, ctx: click.Context) -> list[str]:
281
+ """The usage line after the program's name: a group's own, or a command's without any.
282
+
283
+ Click's group ends it with "COMMAND [ARGS]...", which a script without subcommands (the
284
+ single-callback pattern) does not take: its usage line is its options and operands only.
285
+ """
286
+ if self.commands:
287
+ return super().collect_usage_pieces(ctx)
288
+ return click.Command.collect_usage_pieces(self, ctx)
289
+
290
+
291
+ class ScriptApp(typer.Typer):
292
+ """The Typer app of a script: every way a run ends is one docs/style.md names.
293
+
294
+ SIGHUP, SIGINT and SIGTERM unwind the run (`Interrupted`) and end it with 130, the report
295
+ written as a failure naming the signal. An exception that escapes the script is a bug: it
296
+ is logged at ERROR as "internal error: TYPE: MESSAGE", the report is written as a failure,
297
+ and the run exits 2; the traceback is logged at DEBUG only (`--log-level=DEBUG`).
298
+ """
299
+
300
+ def add_typer(self, typer_instance: typer.Typer, **kwargs: Any) -> None:
301
+ """Add a subcommand whose help, too, says first that a held script is held."""
302
+ kwargs.setdefault("cls", _ScriptGroup)
303
+ super().add_typer(typer_instance, **kwargs)
304
+
305
+ def __call__(self, *args: Any, **kwargs: Any) -> Any:
306
+ """Run the app under the signal handlers and the guard above."""
307
+ with _interruptions_raise():
308
+ try:
309
+ return super().__call__(*args, **kwargs)
310
+ except Interrupted as e:
311
+ message = f"interrupted by {e.signal_name}"
312
+ logger.warning("%s", message)
313
+ _write_failure(message, INTERRUPTED_STATUS)
314
+ sys.exit(INTERRUPTED_STATUS)
315
+ # The one place every exception a script lets escape is reported, whatever it is.
316
+ except Exception as e: # noqa: BLE001
317
+ message = f"internal error: {type(e).__name__}: {e}"
318
+ logger.error("%s", message)
319
+ logger.debug("traceback of the internal error", exc_info=e)
320
+ _write_failure(message, 2)
321
+ sys.exit(2)
322
+
323
+
324
+ def build_app(
325
+ *,
326
+ name: str,
327
+ category: str,
328
+ help_text: str | None = None,
329
+ subcommands: bool = False,
330
+ ) -> typer.Typer:
331
+ """Construct a Typer app primed for the single-callback pattern (a `ScriptApp`).
332
+
333
+ An option is read before or after an operand, as getopt(3) reads it ("getopt() permutes
334
+ the contents of argv as it scans") and as `args_parse_common` reads a shell script's
335
+ (docs/style.md, "Universal CLI flags"). Click stops a group's options at its first operand,
336
+ since that operand names a subcommand, so a script whose callback takes operands would refuse
337
+ `PATH --dry-run`; it lets them stand anywhere with `allow_interspersed_args`. An app with
338
+ subcommands (`subcommands=True`) keeps Click's rule: each subcommand reads its own options,
339
+ after its name, and the universal ones are declared at both levels.
340
+ """
341
+ settings: dict[str, Any] = {"help_option_names": ["-h", "--help"]}
342
+ if not subcommands:
343
+ settings["allow_interspersed_args"] = True
344
+ return ScriptApp(
345
+ cls=_ScriptGroup,
346
+ name=name,
347
+ help=help_text or f"{name}: utilifex/{category}",
348
+ add_completion=False,
349
+ no_args_is_help=False,
350
+ pretty_exceptions_show_locals=False,
351
+ context_settings=settings,
352
+ )
353
+
354
+
355
+ def prepare_context(
356
+ ctx: typer.Context,
357
+ *,
358
+ name: str,
359
+ category: str,
360
+ dry_run: bool,
361
+ json_report: Path | None,
362
+ log_level: str,
363
+ ) -> None:
364
+ """Populate `ctx.obj` and propagate dry-run / log-level side effects.
365
+
366
+ A held script (its header's `Status: held`) is said to be held, once, at WARN, before any
367
+ work, as `args_parse_common` says it of a shell script.
368
+
369
+ A `--json-report` path the run could not write at its end is refused here, before any
370
+ work, with exit 2 (`utilifex.files.check_destination`): a run never does its work and then
371
+ fails to deliver its result.
372
+ """
373
+ # utilifex.proc.run reads DRY_RUN: it must read what the command line decided.
374
+ os.environ["DRY_RUN"] = "1" if dry_run else "0"
375
+ configure_logging(name=name, level=log_level)
376
+ reason = held_reason()
377
+ if reason is not None:
378
+ logger.warning("held, not yet released: %s", reason)
379
+ if json_report is not None:
380
+ try:
381
+ check_destination(json_report)
382
+ except OutputRefusedError as e:
383
+ logger.error("--json-report: %s", e)
384
+ raise typer.Exit(code=2) from e
385
+ ctx.obj = CliContext(
386
+ name=name,
387
+ category=category,
388
+ dry_run=dry_run,
389
+ json_report=json_report,
390
+ log_level=log_level,
391
+ )
392
+ _RUN[:] = [ctx.obj]
393
+
394
+
395
+ def get_context(ctx: typer.Context) -> CliContext:
396
+ """Type-safe accessor for the `CliContext` populated by `prepare_context`."""
397
+ obj = ctx.obj
398
+ if not isinstance(obj, CliContext):
399
+ raise RuntimeError("CLI context is not initialized; call prepare_context() first")
400
+ return obj
401
+
402
+
403
+ # Imported here, after the definitions above: report.py needs none of them.
404
+ from utilifex.report import Report, Status, active_report # noqa: E402 - imported after them
405
+
406
+
407
+ def finalize_report(
408
+ report: Report,
409
+ status: Status,
410
+ exit_code: int = 0,
411
+ *,
412
+ json_report: Path | None = None,
413
+ ) -> None:
414
+ """Stamp the report and emit it if `--json-report` was set.
415
+
416
+ A report that cannot be written (a directory, a symbolic link or a missing directory at
417
+ `json_report`, or a failed write) is logged as an error naming the path and ends the run
418
+ with `typer.Exit(2)`: the run's result could not be delivered.
419
+ """
420
+ report.finalize(status, exit_code)
421
+ if json_report is not None:
422
+ try:
423
+ report.emit(json_report)
424
+ except OSError as e:
425
+ logger.error("could not write the report %s: %s", json_report, e)
426
+ raise typer.Exit(code=2) from e
427
+
428
+
429
+ def fail(
430
+ report: Report,
431
+ message: str,
432
+ *,
433
+ json_report: Path | None,
434
+ exit_code: int = 2,
435
+ ) -> NoReturn:
436
+ """End a run that could not do its job, as `fail` in `lib/bash/log.sh` does.
437
+
438
+ Logs `message` as an error, adds it to the report's errors, finalizes the
439
+ report as `failure` with `exit_code`, writes it when `json_report` is set,
440
+ and raises `typer.Exit(exit_code)`. Called inside an `except` block, the
441
+ exception being handled stays attached as the exit's context.
442
+ """
443
+ logger.error("%s", message)
444
+ report.add_error(message)
445
+ finalize_report(report, "failure", exit_code, json_report=json_report)
446
+ raise typer.Exit(code=exit_code)
447
+
448
+
449
+ def record_error(report: Report, message: str) -> None:
450
+ """Note one item that could not be read or done, and carry on, as `record_error` in bash.
451
+
452
+ Logs `message` as an error and adds it to the report's errors. The run goes on; the
453
+ caller finishes the rest and ends with exit status 2, through `fail` or
454
+ `finalize_report`.
455
+ """
456
+ logger.error("%s", message)
457
+ report.add_error(message)
utilifex/conditions.py ADDED
@@ -0,0 +1,46 @@
1
+ """Conditions of the form `NAME<op>VALUE`, as filter and matcher options take them.
2
+
3
+ `csv-transform --where`, `structured-log-grep --field` and the matchers of
4
+ `alertmanager-silence` all read a name, an operator from a fixed set and a
5
+ value. The value may itself hold operators (`expr=up!=1`), so the split is at
6
+ the first operator in the text; the operator set and what each operator means
7
+ stay with the caller.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from collections.abc import Sequence
13
+
14
+
15
+ def split_condition(text: str, operators: Sequence[str]) -> tuple[str, str, str]:
16
+ """Split `text` into `(name, operator, value)` at its first operator.
17
+
18
+ The split is at the first position where any of `operators` occurs, with
19
+ the longest operator that matches there, so `a>=1` with `>`, `>=` and `=`
20
+ gives `("a", ">=", "1")` and `expr=up!=1` with `=` and `!=` gives
21
+ `("expr", "=", "up!=1")`. Whitespace around the name and the value is
22
+ stripped; an empty value is returned as it is, for the caller to judge.
23
+
24
+ Args:
25
+ text: The condition as given on the command line.
26
+ operators: The operators the caller accepts.
27
+
28
+ Returns:
29
+ The name, the operator and the value.
30
+
31
+ Raises:
32
+ ValueError: No operator occurs in `text`, or the name before the
33
+ first one is empty. The message names `text`.
34
+ """
35
+ for position in range(len(text)):
36
+ matches = [op for op in operators if op and text.startswith(op, position)]
37
+ if not matches:
38
+ continue
39
+ operator = max(matches, key=len)
40
+ name = text[:position].strip()
41
+ if not name:
42
+ msg = f"empty name before {operator!r} in {text!r}"
43
+ raise ValueError(msg)
44
+ return name, operator, text[position + len(operator) :].strip()
45
+ msg = f"no operator ({', '.join(operators)}) in {text!r}"
46
+ raise ValueError(msg)