Skip to content

milc

MILC Objects

python class MILC(object)

MILC - An Opinionated Batteries Included Framework

__init__

python def __init__(name: Optional[str] = None, author: Optional[str] = None, version: Optional[str] = None, logger: Optional[logging.Logger] = None, env_prefix: Optional[str] = None) -> None

Initialize the MILC object.

subcommand_name

python @property def subcommand_name() -> Optional[str]

Returns the leaf CLI name of the active subcommand, e.g. 'add' for 'remote add'.

subcommand_path

python @property def subcommand_path() -> Optional[List[str]]

Returns the full subcommand path as a list, e.g. ['remote', 'add'].

argv_name

python def argv_name() -> str

Returns the name of our program by examining argv.

echo

python def echo(text: str, *args: Any, **kwargs: Any) -> None

Print colorized text to stdout.

ANSI color strings (such as {fg_blue}) will be converted into ANSI escape sequences, and the ANSI reset sequence will be added to all strings.

If args or *kwargs are passed they will be used to %-format the strings.

run

python def run(command: Sequence[str], capture_output: bool = True, combined_output: bool = False, text: bool = True, **kwargs: Any) -> Any

Run a command using subprocess.run, but using some different defaults.

Unlike subprocess.run you must supply a sequence of arguments. You can use shlex.split() to build this from a string.

The **kwargs arguments get passed directly to subprocess.run.

Arguments:

command A sequence where the first item is the command to run, and any remaining items are arguments to pass.

capture_output Set to False to have output written to the terminal instead of being available in the returned subprocess.CompletedProcess instance.

combined_output When true STDERR will be written to STDOUT. Equivalent to the shell construct 2>&1.

text Set to False to disable encoding and get bytes() from .stdout and .stderr.

Notes:

On msys2/cygwin (Windows with an MSYSTEM environment variable set), the command is automatically wrapped in a subshell. stdin is also defaulted to subprocess.DEVNULL because subprocess calls in that environment leave stdin in a broken state, which causes interactive features like cli.questions to stop working. Pass stdin= explicitly to override this default.

initialize_argparse

python def initialize_argparse() -> None

Prepare to process arguments from sys.argv.

python def print_help(*args: Any, **kwargs: Any) -> None

Print a help message for the main program or subcommand, depending on context.

python def print_usage(*args: Any, **kwargs: Any) -> None

Print brief description of how the main program or subcommand is invoked, depending on context.

log_deprecated_warning

python def log_deprecated_warning(item_type: str, name: str, reason: str) -> None

Logs a warning with a custom message if an argument or command is deprecated.

add_argument

python def add_argument(*args: Any, **kwargs: Any) -> None

Wrapper to add arguments and track whether they were passed on the command line.

initialize_logging

python def initialize_logging(logger: Optional[logging.Logger]) -> None

Prepare the defaults for the logging infrastructure.

initialize_arguments

python def initialize_arguments() -> None

Setup and add default arguments.

acquire_lock

python def acquire_lock(blocking: bool = True) -> bool

Acquire the MILC lock for exclusive access to properties.

release_lock

python def release_lock() -> None

Release the MILC lock.

find_config_file

python def find_config_file() -> Path

Locate the config file.

argument

python def argument(*args: Any, **kwargs: Any) -> Callable[[Callable[P, R]], Callable[P, R]]

Decorator to call self.add_argument or self..add_argument.

parse_args

python def parse_args() -> None

Parse the CLI args.

read_config_file

python def read_config_file() -> Tuple[Configuration, Configuration]

Read in the configuration file and return Configuration objects for it and the config_source.

initialize_config

python def initialize_config() -> None

Read in the configuration file and store it in self.config.

merge_args_into_config

python def merge_args_into_config() -> None

Merge CLI arguments into self.config to create the runtime configuration.

write_config_option

python def write_config_option(section: str, option: Any) -> None

Save a single config option to the config file.

save_config

python def save_config() -> None

Save the current configuration to the config file.

__call__

python def __call__() -> Any

Execute the entrypoint function.

entrypoint

python def entrypoint( description: str, deprecated: Optional[str] = None ) -> Callable[[Callable[P, R]], Callable[P, R]]

Decorator that marks the entrypoint used when a subcommand is not supplied.

Arguments:

description A one-line description to display in --help

deprecated Deprecation message. When set the subcommand will marked as deprecated and this message will be displayed in the help output.

prerun

python def prerun( *args: Any, **kwargs: Any ) -> Union[Callable[..., Any], Callable[[Callable[..., Any]], Callable[..., Any]]]

Decorator to register a function to run after initialization and before dispatch.

The decorated function is called with cli as the first argument. Any args/*kwargs passed to this decorator are forwarded directly to the decorated function at runtime.

add_subcommand

python def add_subcommand(handler: Callable[P, R], description: str, hidden: bool = False, deprecated: Optional[str] = None, parent: Optional[Callable[..., Any]] = None, name: Optional[str] = None, **kwargs: Any) -> Callable[P, R]

Register a subcommand.

Arguments:

handler The function to execute for this subcommand.

description A one-line description to display in --help

hidden When True don't display this command in --help

deprecated Deprecation message. When set the subcommand will be marked as deprecated and this message will be displayed in help output.

parent The parent subcommand function. When provided, this subcommand is registered as a child of that subcommand (enabling nested commands like 'prog remote add'). Must be a function object previously registered as a subcommand.

name Override the CLI token for this subcommand. Defaults to the handler's function name in kebab-case.

subcommand

python def subcommand(description: str, hidden: bool = False, parent: Optional[Callable[..., Any]] = None, name: Optional[str] = None, **kwargs: Any) -> Callable[[Callable[P, R]], Callable[P, R]]

Decorator to register a subcommand.

Arguments:

description A one-line description to display in --help

hidden When True don't display this command in --help

parent The parent subcommand function. When provided, this subcommand is registered as a child of that subcommand.

name Override the CLI token for this subcommand.

setup_logging

python def setup_logging() -> None

Called by call() to setup the logging configuration.

is_spinner

python def is_spinner(name: str) -> bool

Returns true if name is a valid spinner.

add_spinner

python def add_spinner(name: str, spinner: Dict[str, Union[int, Sequence[str]]]) -> None

Adds a new spinner to the list of spinners.

A spinner is a dictionary with two keys:

interval
    An integer that sets how long (in ms) to wait between frames.

frames
    A list of frames for this spinner

spinner

python def spinner(text: str, *args: Any, spinner: Optional[Union[str, Dict[str, Union[int, Sequence[str]]]]] = None, animation: str = 'ellipsed', placement: str = 'left', color: str = 'blue', interval: int = -1, stream: Any = sys.stdout, enabled: bool = sys.stdout.isatty(), **kwargs: Any) -> Halo

Create a spinner object for showing activity to the user.

This uses halo https://github.com/ManrajGrover/halo behind the scenes, most of the arguments map to Halo objects 1:1.

There are 3 basic ways to use this:

  • Instantiating a spinner and then using .start() and .stop() on your object.
  • Using a context manager (with cli.spinner(...):)
  • Decorate a function (@cli.spinner(...))

Instantiating a spinner

```python spinner = cli.spinner(text='Loading', spinner='dots') spinner.start()

Do something here

spinner.stop() ```

Using a context manager

python with cli.spinner(text='Loading', spinner='dots'): # Do something here

Decorate a function

python @cli.spinner(text='Loading', spinner='dots') def long_running_function(): # Do something here

Arguments

text
    The text to display next to the spinner. ANSI color strings
    (such as {fg_blue}) will be converted into ANSI escape
    sequences, and the ANSI reset sequence will be added to the
    end of the string.

    If *args or **kwargs are passed they will be used to
    %-format the text.

spinner
    The name of the spinner to use, or a dict with `interval`
    (int, ms) and `frames` (list of str) keys to use directly
    as the spinner definition. Available names are here:
    <https://raw.githubusercontent.com/sindresorhus/cli-spinners/dac4fc6571059bb9e9bc204711e9dfe8f72e5c6f/spinners.json>

animation
    The animation to apply to the text if it doesn't fit the
    terminal. One of `ellipsed`, `bounce`, `marquee`.

placement
    Which side of the text to display the spinner on. One of
    `left`, `right`.

color
    Color of the spinner. One of `blue`, `grey`, `red`, `green`,
    `yellow`, `magenta`, `cyan`, `white`

interval
    How long in ms to wait between frames. Defaults to the spinner interval (recommended.)

stream
    Stream to write the output. Defaults to sys.stdout.

enabled
    Enable or disable the spinner. Defaults to `sys.stdout.isatty()`.