Skip to content

Core Classes

Internal Click subclasses and configuration objects. Exposed publicly for advanced use cases such as subclassing or type-checking.

PycliferOption

Extends click.Option with is_global, context, and env-var binding support.

  • is_global=True — propagates this option to all subcommands automatically.
  • context=True — marks the option as a context option: its value is passed to the context_factory callable on @app_group, and it is accepted at any position in the command chain (even after a subcommand name).
  • show_in_subcommand_help=True — when context=True, controls whether the option appears in subcommand --help under the Context Options panel. Set to False to hide an option from subcommand help while keeping its anywhere-passable behaviour.

pyclifer.PycliferOption

Bases: StoreInMetaMixin, Option

Custom Click Option that can be marked as global for propagation.

Source code in src/pyclifer/core/classes.py
class PycliferOption(StoreInMetaMixin, click_extra.Option):
    """Custom Click Option that can be marked as global for propagation."""

    def __init__(
        self,
        *args: Any,
        is_global: bool = False,
        context: bool = False,
        show_in_subcommand_help: bool = True,
        **kwargs: Any,
    ) -> None:
        """Initialize the option.

        Args:
            *args: Positional arguments for click.Option.
            is_global: If True, this option will be propagated to subcommands.
            context: If True, this option feeds ctx.obj construction and is
                accepted at any position in the command chain.
            show_in_subcommand_help: If True, this option appears in subcommand help.
            **kwargs: Keyword arguments for click.Option.
        """
        self.is_global = is_global
        self.context = context
        self.show_in_subcommand_help = show_in_subcommand_help
        super().__init__(*args, **kwargs)

    def resolve_envvar_value(self, ctx: click_extra.Context) -> str | None:
        """Find the environment variable value, a global option using the one of the root.

        A global option is the same option in every command, so it has one variable name: the one
        of the root group (CLI_REGION for an application named cli), not one built from the path of
        the command that receives it (CLI_LEAF_REGION). Without this, the variable depended on how
        the help is drawn, because click-extra writes the name of the root onto the option and
        rich-click does not.

        Args:
            ctx: The context of the command that parses this option.

        Returns:
            The value of the variable, or None when it is not set.
        """
        if self.is_global and ctx.parent is not None:
            ctx = ctx.find_root()
        return super().resolve_envvar_value(ctx)

__init__(*args, is_global=False, context=False, show_in_subcommand_help=True, **kwargs)

Initialize the option.

Parameters:

Name Type Description Default
*args Any

Positional arguments for click.Option.

()
is_global bool

If True, this option will be propagated to subcommands.

False
context bool

If True, this option feeds ctx.obj construction and is accepted at any position in the command chain.

False
show_in_subcommand_help bool

If True, this option appears in subcommand help.

True
**kwargs Any

Keyword arguments for click.Option.

{}
Source code in src/pyclifer/core/classes.py
def __init__(
    self,
    *args: Any,
    is_global: bool = False,
    context: bool = False,
    show_in_subcommand_help: bool = True,
    **kwargs: Any,
) -> None:
    """Initialize the option.

    Args:
        *args: Positional arguments for click.Option.
        is_global: If True, this option will be propagated to subcommands.
        context: If True, this option feeds ctx.obj construction and is
            accepted at any position in the command chain.
        show_in_subcommand_help: If True, this option appears in subcommand help.
        **kwargs: Keyword arguments for click.Option.
    """
    self.is_global = is_global
    self.context = context
    self.show_in_subcommand_help = show_in_subcommand_help
    super().__init__(*args, **kwargs)

resolve_envvar_value(ctx)

Find the environment variable value, a global option using the one of the root.

A global option is the same option in every command, so it has one variable name: the one of the root group (CLI_REGION for an application named cli), not one built from the path of the command that receives it (CLI_LEAF_REGION). Without this, the variable depended on how the help is drawn, because click-extra writes the name of the root onto the option and rich-click does not.

Parameters:

Name Type Description Default
ctx Context

The context of the command that parses this option.

required

Returns:

Type Description
str | None

The value of the variable, or None when it is not set.

Source code in src/pyclifer/core/classes.py
def resolve_envvar_value(self, ctx: click_extra.Context) -> str | None:
    """Find the environment variable value, a global option using the one of the root.

    A global option is the same option in every command, so it has one variable name: the one
    of the root group (CLI_REGION for an application named cli), not one built from the path of
    the command that receives it (CLI_LEAF_REGION). Without this, the variable depended on how
    the help is drawn, because click-extra writes the name of the root onto the option and
    rich-click does not.

    Args:
        ctx: The context of the command that parses this option.

    Returns:
        The value of the variable, or None when it is not set.
    """
    if self.is_global and ctx.parent is not None:
        ctx = ctx.find_root()
    return super().resolve_envvar_value(ctx)

PycliferGroup

Base Click group class used by app_group and group. Composes EventsMixin + HandleResponseMixin + GlobalOptionsMixin.

pyclifer.PycliferGroup = PycliferExtraGroup module-attribute


CustomConfigOption

Extends click-extra's config option with multi-location Linux config file search (/etc/<app>/, ~/.config/<app>/, etc.). It also emits the config.loaded event on its group once the configuration is resolved (see Lifecycle events).

pyclifer.CustomConfigOption

Bases: StoreInMetaMixin, ConfigOption

Custom ConfigOption to add support for /etc/ on Linux systems.

This class extends the default click-extra ConfigOption to include system-wide configuration directories following Linux conventions while maintaining cross-platform compatibility.

Source code in src/pyclifer/core/classes.py
class CustomConfigOption(StoreInMetaMixin, ConfigOption):
    """Custom ConfigOption to add support for /etc/<cli_name> on Linux systems.

    This class extends the default click-extra ConfigOption to include system-wide
    configuration directories following Linux conventions while maintaining
    cross-platform compatibility.
    """

    def __init__(self, *args: Any, is_global: bool = False, **kwargs: Any) -> None:
        """Initialize the custom config option.

        Args:
            *args: Positional arguments.
            is_global: If True, this option will be propagated to subcommands.
            **kwargs: Keyword arguments.
        """
        self.is_global = is_global
        super().__init__(*args, **kwargs)

    def load_conf(
        self, ctx: click_extra.Context, param: click_extra.Parameter, path_pattern: Any
    ) -> None:
        """Load the configuration, then emit config.loaded on the owning group.

        Args:
            ctx: The context of the group that owns this option.
            param: The parameter being processed.
            path_pattern: The configuration path pattern, or the no-config sentinel.
        """
        super().load_conf(ctx, param, path_pattern)
        if ctx.resilient_parsing or not isinstance(ctx.command, EventsMixin):
            return
        # A bare call can visit this option twice (click-extra preloads it to read
        # default subcommands), so each command path is emitted only once.
        emitted = ctx.meta.setdefault(_CONFIG_LOADED_EMITTED, set())
        if ctx.command_path in emitted:
            return
        try:
            ctx.command.emit(CONFIG_LOADED, ctx)
        except click_extra.ClickException as error:
            # click-extra swallows this on a bare call: keep it for the group to report.
            ctx.meta[PENDING_ERROR_META] = error
            raise
        emitted.add(ctx.command_path)

    def get_default(self, ctx, call=True):
        """Override get_default to fix rich-click help rendering.

        rich-click fetches the default with call=False during help generation,
        which returns the raw bound method. We intercept this and force
        evaluation to display the actual path cleanly.
        """
        default = super().get_default(ctx, call=call)
        if not call and callable(default):
            # noinspection PyBroadException
            try:
                return default()
            except Exception:  # rich-click may pass an unresolvable callable — swallow silently
                pass
        return default

    def default_pattern(self) -> str:
        """Generate the default configuration search pattern.

        Creates search patterns for configuration files, prioritizing Linux system
        directories when running on Linux platforms. Falls back to standard
        user configuration directories on other platforms.

        Patterns are joined with "|" so that wcmatch's SPLIT flag (active on
        click-extra's ConfigOption) treats each path as a separate glob target.

        Returns:
            The pipe-separated glob pattern covering all config locations.

        Raises:
            RuntimeError: If no click, context is available to determine CLI name.
        """
        all_patterns = self._get_all_config_patterns()

        if not all_patterns:
            return self._get_fallback_pattern()

        return "|".join(all_patterns)

    def search_and_read_file(self, pattern: str) -> Iterator[tuple[Path | URL, str, str | None]]:
        """Search each pipe-separated sub-pattern in order to preserve priority.

        click-extra sorts the matches of a single pattern alphabetically, which would
        override the priority order built by default_pattern (system before user).
        Searching sub-patterns one at a time keeps that order.

        Args:
            pattern: Pipe-separated glob patterns, or a single pattern or URL.

        Yields:
            Triples of location, raw content and media type, in sub-pattern order.

        Raises:
            FileNotFoundError: When no sub-pattern matches any file.
        """
        found = False
        for sub_pattern in pattern.split("|"):
            try:
                for result in super().search_and_read_file(sub_pattern):
                    found = True
                    yield result
            except FileNotFoundError:
                # This sub-pattern matched nothing; the next one may still match.
                continue
        if not found:
            raise FileNotFoundError(f"No file found matching {pattern}")

    def read_and_parse_conf(self, pattern: str) -> tuple[Path | URL | None, dict[str, Any] | None]:
        """Read every matching file and deep-merge them, the last one winning.

        Sub-patterns are read in order, from the lowest to the highest priority
        (system before user), and the files of one directory are read in
        alphabetical order. Each file overrides the keys of the previous ones.

        Args:
            pattern: Pipe-separated glob patterns, or a single pattern or URL.

        Returns:
            The location of the highest priority file and the merged configuration.

        Raises:
            FileNotFoundError: When no file matches the pattern.
        """
        # Deferred import: keeps deepmerge off the startup path of every CLI.
        from deepmerge import always_merger

        layers = []
        for sub_pattern in pattern.split("|"):
            try:
                layers.extend(self.read_and_parse_all_conf(sub_pattern))
            except FileNotFoundError:
                # This location holds no file; the next one may still match.
                continue
        if not layers:
            # Nothing parseable: let click-extra raise or report blank files itself.
            return super().read_and_parse_conf(pattern)
        merged: dict[str, Any] = {}
        for _location, conf in layers:
            merged = always_merger.merge(merged, copy.deepcopy(conf))
        return layers[-1][0], merged

    def _get_extension_pattern(self) -> str:
        """Build a file extension pattern from supported formats.

        Creates a glob-compatible extension pattern from the configured
        formats, using either single extension or brace notation for
        multiple extensions.

        Returns:
            str: Extension pattern for glob matching (e.g., 'toml' or '{toml,yaml,json}').
        """
        extensions = []

        if self.file_format_patterns:
            patterns = unique(flatten(self.file_format_patterns.values()))
            # Keep only generic extensions (e.g., "*.toml" -> "toml")
            # and ignore specific file patterns like "pyproject.toml"
            extensions.extend(pat[2:] for pat in patterns if pat.startswith("*."))

        extensions = unique([ext for ext in extensions if ext])

        if not extensions:
            return "*"

        if len(extensions) == 1:
            return extensions[0]
        return f"{{{','.join(extensions)}}}"

    def _get_all_config_patterns(self) -> list[str]:
        """Get all configuration search patterns in priority order.

        Constructs file search patterns for different configuration locations
        based on the current platform and supported file formats.

        Returns:
            List of glob patterns for configuration file search, ordered by
            priority (system-wide first, then user-specific).

        Raises:
            RuntimeError: If no click, context is available to determine CLI name.
        """
        patterns = []

        ext_pattern = self._get_extension_pattern()

        try:
            ctx = get_current_context()
            cli_name = ctx.find_root().info_name
        except RuntimeError:
            # No click context available - this can happen during testing
            # or when called outside a click command context
            return []

        if not cli_name:
            return []

        if is_linux():
            system_config_dir = Path(f"/etc/{cli_name}")
            system_pattern = str(system_config_dir / f"*.{ext_pattern}")
            patterns.append(system_pattern)

        try:
            roaming = getattr(self, "roaming", False)
            force_posix = getattr(self, "force_posix", False)
            app_dir = Path(
                get_app_dir(cli_name, roaming=roaming, force_posix=force_posix)
            ).resolve()
            user_pattern = str(app_dir / f"*.{ext_pattern}")
            patterns.append(user_pattern)
        except (OSError, ValueError, TypeError) as e:
            # Handle specific exceptions that can be raised by get_app_dir or Path operations:
            # - OSError: File system-related errors (permissions, path issues, etc.)
            # - ValueError: Invalid arguments passed to get_app_dir or Path
            # - TypeError: Type-related issues with arguments
            logger = logging.getLogger(__name__)
            logger.debug(f"Failed to get user config directory: {e}")
            # Continue without user config pattern - system config may still work

        return patterns

    def _get_fallback_pattern(self) -> str:
        """Get a fallback configuration pattern when normal detection fails.

        Provides a basic configuration search pattern for cases where
        the click context is not available or CLI name cannot be determined.

        Returns:
            str: A basic configuration file search pattern.
        """
        ext_pattern = self._get_extension_pattern()
        return f"*.{ext_pattern}"

__init__(*args, is_global=False, **kwargs)

Initialize the custom config option.

Parameters:

Name Type Description Default
*args Any

Positional arguments.

()
is_global bool

If True, this option will be propagated to subcommands.

False
**kwargs Any

Keyword arguments.

{}
Source code in src/pyclifer/core/classes.py
def __init__(self, *args: Any, is_global: bool = False, **kwargs: Any) -> None:
    """Initialize the custom config option.

    Args:
        *args: Positional arguments.
        is_global: If True, this option will be propagated to subcommands.
        **kwargs: Keyword arguments.
    """
    self.is_global = is_global
    super().__init__(*args, **kwargs)

load_conf(ctx, param, path_pattern)

Load the configuration, then emit config.loaded on the owning group.

Parameters:

Name Type Description Default
ctx Context

The context of the group that owns this option.

required
param Parameter

The parameter being processed.

required
path_pattern Any

The configuration path pattern, or the no-config sentinel.

required
Source code in src/pyclifer/core/classes.py
def load_conf(
    self, ctx: click_extra.Context, param: click_extra.Parameter, path_pattern: Any
) -> None:
    """Load the configuration, then emit config.loaded on the owning group.

    Args:
        ctx: The context of the group that owns this option.
        param: The parameter being processed.
        path_pattern: The configuration path pattern, or the no-config sentinel.
    """
    super().load_conf(ctx, param, path_pattern)
    if ctx.resilient_parsing or not isinstance(ctx.command, EventsMixin):
        return
    # A bare call can visit this option twice (click-extra preloads it to read
    # default subcommands), so each command path is emitted only once.
    emitted = ctx.meta.setdefault(_CONFIG_LOADED_EMITTED, set())
    if ctx.command_path in emitted:
        return
    try:
        ctx.command.emit(CONFIG_LOADED, ctx)
    except click_extra.ClickException as error:
        # click-extra swallows this on a bare call: keep it for the group to report.
        ctx.meta[PENDING_ERROR_META] = error
        raise
    emitted.add(ctx.command_path)

get_default(ctx, call=True)

Override get_default to fix rich-click help rendering.

rich-click fetches the default with call=False during help generation, which returns the raw bound method. We intercept this and force evaluation to display the actual path cleanly.

Source code in src/pyclifer/core/classes.py
def get_default(self, ctx, call=True):
    """Override get_default to fix rich-click help rendering.

    rich-click fetches the default with call=False during help generation,
    which returns the raw bound method. We intercept this and force
    evaluation to display the actual path cleanly.
    """
    default = super().get_default(ctx, call=call)
    if not call and callable(default):
        # noinspection PyBroadException
        try:
            return default()
        except Exception:  # rich-click may pass an unresolvable callable — swallow silently
            pass
    return default

default_pattern()

Generate the default configuration search pattern.

Creates search patterns for configuration files, prioritizing Linux system directories when running on Linux platforms. Falls back to standard user configuration directories on other platforms.

Patterns are joined with "|" so that wcmatch's SPLIT flag (active on click-extra's ConfigOption) treats each path as a separate glob target.

Returns:

Type Description
str

The pipe-separated glob pattern covering all config locations.

Raises:

Type Description
RuntimeError

If no click, context is available to determine CLI name.

Source code in src/pyclifer/core/classes.py
def default_pattern(self) -> str:
    """Generate the default configuration search pattern.

    Creates search patterns for configuration files, prioritizing Linux system
    directories when running on Linux platforms. Falls back to standard
    user configuration directories on other platforms.

    Patterns are joined with "|" so that wcmatch's SPLIT flag (active on
    click-extra's ConfigOption) treats each path as a separate glob target.

    Returns:
        The pipe-separated glob pattern covering all config locations.

    Raises:
        RuntimeError: If no click, context is available to determine CLI name.
    """
    all_patterns = self._get_all_config_patterns()

    if not all_patterns:
        return self._get_fallback_pattern()

    return "|".join(all_patterns)

search_and_read_file(pattern)

Search each pipe-separated sub-pattern in order to preserve priority.

click-extra sorts the matches of a single pattern alphabetically, which would override the priority order built by default_pattern (system before user). Searching sub-patterns one at a time keeps that order.

Parameters:

Name Type Description Default
pattern str

Pipe-separated glob patterns, or a single pattern or URL.

required

Yields:

Type Description
tuple[Path | URL, str, str | None]

Triples of location, raw content and media type, in sub-pattern order.

Raises:

Type Description
FileNotFoundError

When no sub-pattern matches any file.

Source code in src/pyclifer/core/classes.py
def search_and_read_file(self, pattern: str) -> Iterator[tuple[Path | URL, str, str | None]]:
    """Search each pipe-separated sub-pattern in order to preserve priority.

    click-extra sorts the matches of a single pattern alphabetically, which would
    override the priority order built by default_pattern (system before user).
    Searching sub-patterns one at a time keeps that order.

    Args:
        pattern: Pipe-separated glob patterns, or a single pattern or URL.

    Yields:
        Triples of location, raw content and media type, in sub-pattern order.

    Raises:
        FileNotFoundError: When no sub-pattern matches any file.
    """
    found = False
    for sub_pattern in pattern.split("|"):
        try:
            for result in super().search_and_read_file(sub_pattern):
                found = True
                yield result
        except FileNotFoundError:
            # This sub-pattern matched nothing; the next one may still match.
            continue
    if not found:
        raise FileNotFoundError(f"No file found matching {pattern}")

read_and_parse_conf(pattern)

Read every matching file and deep-merge them, the last one winning.

Sub-patterns are read in order, from the lowest to the highest priority (system before user), and the files of one directory are read in alphabetical order. Each file overrides the keys of the previous ones.

Parameters:

Name Type Description Default
pattern str

Pipe-separated glob patterns, or a single pattern or URL.

required

Returns:

Type Description
tuple[Path | URL | None, dict[str, Any] | None]

The location of the highest priority file and the merged configuration.

Raises:

Type Description
FileNotFoundError

When no file matches the pattern.

Source code in src/pyclifer/core/classes.py
def read_and_parse_conf(self, pattern: str) -> tuple[Path | URL | None, dict[str, Any] | None]:
    """Read every matching file and deep-merge them, the last one winning.

    Sub-patterns are read in order, from the lowest to the highest priority
    (system before user), and the files of one directory are read in
    alphabetical order. Each file overrides the keys of the previous ones.

    Args:
        pattern: Pipe-separated glob patterns, or a single pattern or URL.

    Returns:
        The location of the highest priority file and the merged configuration.

    Raises:
        FileNotFoundError: When no file matches the pattern.
    """
    # Deferred import: keeps deepmerge off the startup path of every CLI.
    from deepmerge import always_merger

    layers = []
    for sub_pattern in pattern.split("|"):
        try:
            layers.extend(self.read_and_parse_all_conf(sub_pattern))
        except FileNotFoundError:
            # This location holds no file; the next one may still match.
            continue
    if not layers:
        # Nothing parseable: let click-extra raise or report blank files itself.
        return super().read_and_parse_conf(pattern)
    merged: dict[str, Any] = {}
    for _location, conf in layers:
        merged = always_merger.merge(merged, copy.deepcopy(conf))
    return layers[-1][0], merged

PycliferTimerOption

Internal option class powering timer=True on @app_group. Subclasses click-extra's TimerOption to integrate with pyclifer's output format: suppresses the text echo in json/yaml mode and injects timing fields into Response.data via returns_response.

pyclifer.core.classes.PycliferTimerOption

Bases: TimerOption

TimerOption integrated with pyclifer output format.

Skips the text echo in json/yaml mode — timing data is injected directly into the Response by returns_response instead.

Source code in src/pyclifer/core/classes.py
class PycliferTimerOption(TimerOption):
    """TimerOption integrated with pyclifer output format.

    Skips the text echo in json/yaml mode — timing data is injected directly
    into the Response by returns_response instead.
    """

    # noinspection PyAttributeOutsideInit
    def init_timer(
        self, ctx: click_extra.Context, param: click_extra.Parameter, value: bool
    ) -> None:
        """Register the timer and store the context for deferred format check."""
        if not value:
            return
        self.start_time = perf_counter()
        self._close_ctx = ctx
        ctx.meta["click_extra.start_time"] = self.start_time
        ctx.call_on_close(self.print_timer)

    def print_timer(self) -> None:
        """Print elapsed time unless the output format is json or yaml.

        Output format is read at close time so that eager option processing
        order does not matter — meta is fully populated by then.
        """
        output_format = self._close_ctx.find_root().meta.get("pyclifer.output_format", "table")
        if output_format in ("json", "yaml"):
            return
        elapsed = perf_counter() - self.start_time
        click_extra.echo(f"Execution time: {elapsed:.3f} seconds.")

init_timer(ctx, param, value)

Register the timer and store the context for deferred format check.

Source code in src/pyclifer/core/classes.py
def init_timer(
    self, ctx: click_extra.Context, param: click_extra.Parameter, value: bool
) -> None:
    """Register the timer and store the context for deferred format check."""
    if not value:
        return
    self.start_time = perf_counter()
    self._close_ctx = ctx
    ctx.meta["click_extra.start_time"] = self.start_time
    ctx.call_on_close(self.print_timer)

print_timer()

Print elapsed time unless the output format is json or yaml.

Output format is read at close time so that eager option processing order does not matter — meta is fully populated by then.

Source code in src/pyclifer/core/classes.py
def print_timer(self) -> None:
    """Print elapsed time unless the output format is json or yaml.

    Output format is read at close time so that eager option processing
    order does not matter — meta is fully populated by then.
    """
    output_format = self._close_ctx.find_root().meta.get("pyclifer.output_format", "table")
    if output_format in ("json", "yaml"):
        return
    elapsed = perf_counter() - self.start_time
    click_extra.echo(f"Execution time: {elapsed:.3f} seconds.")