cmds.projects.CmdCreateFile: Fix --format help
All checks were successful
CI / Packaging - Kali Linux (pull_request) Successful in 4m42s
CI / Packaging - OpenSUSE Tumbleweed (pull_request) Successful in 4m30s
CI / Packaging test (pull_request) Successful in 0s
CI / Packaging - Kali Linux (push) Successful in 4m17s
CI / Packaging - OpenSUSE Tumbleweed (push) Successful in 4m24s
CI / Packaging test (push) Successful in 0s

The possible values of --format are defined by an Enum which is never
really used as such. Derive them from class introspection instead, i.e.
offer all formats that have a corresponding render_<format>() name.

Also, turn the option into real argparse-backed choices, and make the
argument mandatory, because that reflects the reality of the implementation
- there is no default.

Signed-off-by: Jan Lindemann <jan@janware.com>
This commit is contained in:
Jan Lindemann 2026-09-12 17:56:40 +02:00
commit a197e9c50d
Signed by: Jan Lindemann
GPG key ID: 3750640C9E25DD61
2 changed files with 19 additions and 13 deletions

View file

@ -1,8 +1,12 @@
from __future__ import annotations
import sys
from argparse import ArgumentParser, ArgumentTypeError, Namespace
from enum import Enum, auto
from typing import override
from typing import TYPE_CHECKING, override
if TYPE_CHECKING:
from typing import Iterable
from ...lib.log import WARNING, log
from ...lib.version.base import Syntax
@ -17,10 +21,6 @@ def key_value(s: str) -> tuple[str, str]:
raise ArgumentTypeError('Expected KEY=VALUE')
return key, value
# TODO: Put the more elaborate stuff into lib
class Fmt(Enum):
Pyright = auto()
class CmdCreateFile(Cmd): # export
def __jw_required(
@ -50,6 +50,11 @@ class CmdCreateFile(Cmd): # export
ret = [module, *ret]
return ret
@property
def __format_choices(self) -> Iterable[str]:
p = 'render_'
return [name.removeprefix(p) for name in dir(self) if name.startswith(p)]
def __render(
self,
template_name: str,
@ -100,12 +105,12 @@ class CmdCreateFile(Cmd): # export
@override
def add_arguments(self, parser: ArgumentParser) -> None:
super().add_arguments(parser)
format_choices = self.__format_choices
parser.add_argument(
'--format',
help = (
'Output format, for example: '
', '.join([fmt.name.lower() for fmt in Fmt])
)
choices = format_choices,
required = True,
help = 'Output format, one of: ' + ', '.join(format_choices)
)
parser.add_argument(
'--search-path',
@ -132,6 +137,6 @@ class CmdCreateFile(Cmd): # export
@override
async def _run(self, args: Namespace) -> None:
method = getattr(self, 'render_' + args.format, None)
if method is None: # Should be prevented by choices=[] but keeps linter happy
if method is None: # choices already restricts this; keeps the linter happy
raise Exception(f'Unsupported output format {args.format}')
sys.stdout.write(method(args.module, args.field))