|
| 1 | +# SPDX-License-Identifier: MPL-2.0 |
| 2 | +"""CLI.""" |
| 3 | + |
| 4 | +from __future__ import annotations |
| 5 | + |
| 6 | +import sys |
| 7 | +from argparse import ArgumentParser, Namespace |
| 8 | +from argparse import BooleanOptionalAction as Ba |
| 9 | +from types import ModuleType |
| 10 | +from typing import Literal, get_args |
| 11 | +from unittest.mock import patch |
| 12 | + |
| 13 | +from . import _repr, session_info |
| 14 | + |
| 15 | +Format = Literal["text", "markdown", "html", "json"] |
| 16 | + |
| 17 | + |
| 18 | +class Args(Namespace): |
| 19 | + """CLI arguments.""" |
| 20 | + |
| 21 | + packages: list[str] |
| 22 | + os: bool |
| 23 | + cpu: bool |
| 24 | + gpu: bool |
| 25 | + format: Format |
| 26 | + |
| 27 | + @classmethod |
| 28 | + def parser(cls) -> ArgumentParser: |
| 29 | + """Return argument parser.""" |
| 30 | + parser = ArgumentParser() |
| 31 | + parser.add_argument("packages", nargs="*", help="packages to import") |
| 32 | + parser.add_argument( |
| 33 | + "--os", default=True, action=Ba, help="include OS name and version" |
| 34 | + ) |
| 35 | + parser.add_argument( |
| 36 | + "--cpu", default=True, action=Ba, help="include number of CPU cores" |
| 37 | + ) |
| 38 | + parser.add_argument( |
| 39 | + "--gpu", |
| 40 | + default=False, |
| 41 | + action=Ba, |
| 42 | + help="include information per supported GPU (disabled by default)", |
| 43 | + ) |
| 44 | + parser.add_argument( |
| 45 | + "-f", |
| 46 | + "--format", |
| 47 | + default="text", |
| 48 | + choices=get_args(Format), |
| 49 | + help="output format", |
| 50 | + ) |
| 51 | + return parser |
| 52 | + |
| 53 | + @classmethod |
| 54 | + def parse(cls, args: list[str] | None = None) -> Args: |
| 55 | + """Parse CLI arguments.""" |
| 56 | + return cls.parser().parse_args(args, cls()) |
| 57 | + |
| 58 | + |
| 59 | +def main(args_: list[str] | None = None, /) -> None: |
| 60 | + """Run CLI.""" |
| 61 | + args = Args.parse(args_) |
| 62 | + |
| 63 | + modules = {name: __import__(name) for name in args.packages} |
| 64 | + |
| 65 | + with patch.dict(sys.modules, __main__=type("__main__", (ModuleType,), modules)): |
| 66 | + si = session_info(cpu=True, dependencies=True) |
| 67 | + |
| 68 | + match args.format: |
| 69 | + case "text": |
| 70 | + print(si) |
| 71 | + case "markdown": |
| 72 | + print(_repr.repr_markdown(si)) |
| 73 | + case "html": |
| 74 | + print(_repr.repr_html(si)) |
| 75 | + case "json": |
| 76 | + print(_repr.repr_json(si)) |
| 77 | + case _: |
| 78 | + raise AssertionError |
0 commit comments