Skip to content

toolr._parser

Parser

Bases: Struct

Singleton parser class that wraps argparse.

parse_args

parse_args(argv: list[str] | None = None) -> Namespace

Parse CLI.

Source code in python/toolr/_parser.py
def parse_args(self, argv: list[str] | None = None) -> Namespace:
    """
    Parse CLI.
    """
    if TYPE_CHECKING:
        assert self.context is not None
        assert self.parser is not None

    # Log the argv getting executed
    self.context.debug(f"Tools executing 'sys.argv': {sys.argv}")
    # Process registered imports to allow other modules to register commands
    # self._process_registered_tool_modules()
    options = self.parser.parse_args(argv)
    verbosity = ConsoleVerbosity.NORMAL
    if options.quiet:
        verbosity = ConsoleVerbosity.QUIET
        logging.root.setLevel(logging.CRITICAL + 1)
    elif options.debug:
        verbosity = ConsoleVerbosity.VERBOSE
        logging.root.setLevel(logging.DEBUG)
    else:
        logging.root.setLevel(logging.INFO)
    if options.timestamps:
        for handler in logging.root.handlers:
            handler.setFormatter(_logs.TIMESTAMP_FORMATTER)
    else:
        for handler in logging.root.handlers:
            handler.setFormatter(_logs.NO_TIMESTAMP_FORMATTER)

    # Late import to avoid circular import issues
    from toolr.utils._console import Consoles  # noqa: PLC0415

    # Reset verbosity and consoles after parsing the CLI
    consoles = Consoles.setup(verbosity)
    structs.force_setattr(self.context, "verbosity", verbosity)
    structs.force_setattr(self.context, "_console_stderr", consoles.stderr)
    structs.force_setattr(self.context, "_console_stdout", consoles.stdout)
    if "func" not in options:
        self.context.exit(1, "No command was passed.")
    structs.force_setattr(self, "options", options)
    log.debug("CLI parsed options %s", options)
    return options

run

run() -> None

Run the command.

Source code in python/toolr/_parser.py
def run(self) -> None:
    """
    Run the command.
    """
    if self.options is None:
        err_msg = "parser.parse_args() was not called."
        raise RuntimeError(err_msg)
    self.options.func(self.context, self.options)
    self.exit(0)

__getattr__

__getattr__(attr: str) -> Any

Proxy unknown attributes to the parser instance.

Source code in python/toolr/_parser.py
def __getattr__(self, attr: str) -> Any:
    """
    Proxy unknown attributes to the parser instance.
    """
    if attr == "options":
        return self.__getattribute__(attr)
    return getattr(self.parser, attr)