click_extra.version module

        classDiagram
  ExtraOption <|-- VersionOption
    

Introspect CLI metadata at runtime and print a colored --version string.

VersionOption gathers the executed CLI’s metadata (module and package names, distribution version, author and license, environment profile, and the live Git state) and renders them through a customizable, colorized message template.

Git fields (git_branch, git_short_hash, …) are resolved at runtime by shelling out to git, with three fallbacks for git-less environments: a pre-baked __<field>__ dunder in the CLI module or its package (injected before build by click_extra.prebake), then a committed .git_archival.json populated by git archive, then the commit an installer records for a distribution installed from a Git URL. The resolvers behind each field live in click_extra.version_facts.

click_extra.version.MUTED = Style(fg='bright_black')

The recessive style of what a version message says beside its name and version.

The tagline and the fact labels of a VersionScreen take it, and so do the template fields that locate a build rather than identify it: the repository path, the commit date, the build facts and the environment profile.

click_extra.version.is_main_module(module_name)[source]

Is module_name a __main__ entry point, of a package or of a script?

An entry point is where the interpreter started: python -m package, a console script, or a compiled binary. It is never plumbing a stack walk lands on after running out of user frames, so it is exempt from CLI_ECOSYSTEM_PACKAGES even when it sits under one of those packages, as click_extra.__main__ does in Click Extra’s own binary.

Return type:

bool

click_extra.version.theme_slot(slot)[source]

A style reading its palette slot off the active theme, on every call.

The lookup happens at call time, so the message follows --theme, CLICK_EXTRA_THEME and the background-sniffing auto alike, and drops its color under the monochrome manpage palette. A style captured at import would paint every theme with one palette: the bright white program name of dark is white on white on a light terminal.

get_current_theme() answers with the colorless theme outside an invocation, and with a full palette inside one, so no slot can come back missing.

Return type:

Callable[[str], str]

click_extra.version.unstyled(text)[source]

Identity style, for a segment left with no color of its own.

Return type:

str

class click_extra.version.VersionScreen(logo, tagline='', facts=<function default_facts>, gutter='   ')[source]

Bases: object

A logo, and the facts to seat beside it, as --version should draw them.

Owns the layout only. The artwork arrives already rendered, as a string or the lines of one, so a CLI is free to draw its mark however it likes, in ASCII line art, half-blocks or anything else, without this class knowing. Hand one to VersionOption through its screen argument, or to a whole CLI through default_params(screen=…).

The mark, pre-rendered, or a callable producing it. A string splits on newlines.

A callable defers the rendering to the first --version that draws the screen, as facts does for its values: a mark painted by code, from an image say, then costs nothing to the invocations that never ask for it.

tagline: str = ''

One line under the program name. Omitted, with its blank line, when empty.

facts()

Label-to-value rows under the tagline, or a callable producing them.

A callable defers the work to render time, which matters when a value costs something to compute: a CLI counting plugins should not pay for that on every invocation just to have the number ready in case --version is asked for.

Return type:

dict[str, str]

gutter: str = '   '

Blank columns between the mark and the facts, and between label and value.

property lines: tuple[str, ...]

The mark’s lines, every one padded out to width.

Padding here rather than asking for it is what lets a caller hand over whatever its renderer produced. Trailing blanks are invisible on a line by itself and ragged the moment anything is placed beside it, and a caller cannot repair that afterwards: pad_to() is what measures a styled line right and closes the style it left open.

property width: int

Columns the mark occupies, taken from its widest line.

rows(prog_name, version, styles)[source]

The column of facts, as (plain, styled) pairs.

Both forms are built together because the styled one cannot be measured: its escape sequences take columns that never reach the screen, and the plain twin is what render() sizes the layout against.

The program name and version take the same styles the plain message gives them, so the two renderings of --version cannot drift apart on color.

Return type:

tuple[tuple[str, str], ...]

render(prog_name, version, styles)[source]

Compose the mark and the facts into the screen, or decline to.

The facts are centred against the mark’s height, and either column may be the taller of the two: a line missing from one side simply renders blank.

Returns None when the terminal is too narrow to seat the two columns side by side, leaving the caller to fall back rather than emit a wrapped mess. The threshold is measured off the facts actually built, since their widest row grows with whatever a CLI chose to report. A non-interactive stream reports shutil’s 80-column default, wide enough that a redirected-but-forced-color run still gets the screen it asked for.

Return type:

str | None

click_extra.version.colors_reach_output()[source]

Will ANSI codes survive all the way to the user’s terminal?

Resolves Click Extra’s color tri-state, deferring to the output stream’s TTY status on its auto default, exactly as click.echo does when it decides whether to strip the codes itself.

Note

The stream probed is sys.stdout, not Click’s own resolution of it. click.echo reaches stdout through a private cached wrapper, which fixes the output encoding and delegates isatty() to the stream beneath it, so both answer alike. Click deprecates the public accessor of that wrapper, click.get_text_stream().

Return type:

bool

click_extra.version.template_segments(template)[source]

Split a version message template into its literal and field segments.

Yields one (literal, field_id, field) triple per field of template, in order: the literal text before the field, the identifier the field resolves on the option (module for {module.__name__}, the part before any index or attribute), and the field as written, braces and format spec included. A doubled brace of a literal comes back single. Literal text left after the last field comes in a final triple carrying no field.

Return type:

Iterator[tuple[str, str | None, str | None]]

class click_extra.version.VersionOption(param_decls=None, *, message=None, fields=None, styles=None, message_style=None, screen=None, is_flag=True, expose_value=False, is_eager=True, help='Show the version and exit.', **kwargs)[source]

Bases: ExtraOption

Gathers CLI metadata and prints a colored version string.

Note

This is not a drop-in replacement for the standard @click.version_option() decorator.

It addresses the following Click issues:

  • click#2324, to allow its use with the declarative params= argument.

  • click#2331, by distinguishing the module from the package.

  • click#1756, by allowing path and Python version.

Preconfigured as a --version option flag.

Parameters:
  • message (str | None) – the message template to print, in format string syntax. Defaults to {prog_name}, version {version}.

  • fields (Mapping[str, Any] | None) – mapping of template field name to a forced value, overriding the value auto-computed for that field. Keys must be members of template_fields (for example {"version": "1.2.3"}).

  • styles (Mapping[str, Callable[[str], str] | None] | None) – mapping of template field name to its Style, merged over default_styles. Pass None as a value to clear a field’s default style. Keys must be members of template_fields.

  • message_style (Callable[[str], str] | None) – fallback style for the message literals and for any field that has no style of its own.

  • screen (VersionScreen | None) – a VersionScreen to draw instead of the one-line message, whenever the terminal can take it. Left unset, --version prints the one-line message.

Raises:

TypeError – when a key of fields or styles names no template field.

template_fields: tuple[str, ...] = ('module', 'module_name', 'module_file', 'module_version', 'package_name', 'package_version', 'author', 'license', 'exec_name', 'version', 'git_repo_path', 'git_branch', 'git_long_hash', 'git_short_hash', 'git_date', 'git_tag', 'git_tag_sha', 'git_distance', 'git_dirty', 'build_time', 'build_os', 'build_target', 'build_target_arch', 'prog_name')

List of field IDs recognized by the message template.

default_styles: ClassVar[dict[str, Callable[[str], str]]] = {'build_os': Style(fg='bright_black'), 'build_target': Style(fg='bright_black'), 'build_target_arch': Style(fg='bright_black'), 'build_time': Style(fg='bright_black'), 'exec_name': <function theme_slot.<locals>.apply>, 'git_branch': Style(fg='cyan'), 'git_date': Style(fg='bright_black'), 'git_dirty': Style(fg='red'), 'git_distance': <function theme_slot.<locals>.apply>, 'git_long_hash': Style(fg='yellow'), 'git_repo_path': Style(fg='bright_black'), 'git_short_hash': Style(fg='yellow'), 'git_tag': Style(fg='cyan'), 'git_tag_sha': Style(fg='yellow'), 'module_name': <function theme_slot.<locals>.apply>, 'module_version': <function theme_slot.<locals>.apply>, 'package_name': <function theme_slot.<locals>.apply>, 'package_version': <function theme_slot.<locals>.apply>, 'prog_name': <function theme_slot.<locals>.apply>, 'version': <function theme_slot.<locals>.apply>}

Default style for each template field.

Fields absent from this mapping render with no style of their own and fall back to message_style (or no color when that is unset). User-provided styles are merged over these defaults.

The name and version fields read their style off the active palette through theme_slot() rather than naming a color, so the message follows --theme. Under the default dark palette, invoked_command is bright white bold and success is green.

message: str = '{prog_name}, version {version}'

Default message template used to render the version string.

styles: dict[str, Callable[[str], str] | None]
pin_field(field_id, value)[source]

Pin a template field to a caller-supplied value.

The value shadows the cached_property that would otherwise resolve the field, and is recorded so reset_resolution() can tell the two apart. Every caller that pins a field goes through here: a bare setattr sets the value without the record, and the next reset then discards it.

Parameters:
  • field_id (str) – Name of the template field to pin.

  • value (Any) – Value the field reports from now on.

Raises:

TypeError – when field_id names no template field.

Return type:

None

reset_resolution()[source]

Drop every memoized field, so the next read resolves from scratch.

The resolution chain starts on a stack walk, and the option is built once at decoration time, so the first read in a process fixes the answer for every later one. That is what a CLI wants: one invocation, one process, one walk.

A documentation build breaks the assumption. It renders many commands in one process, and a render that carries no CLI frame (writing roff for a command tree, say) resolves the chain from a stack the walk cannot read. The wrong answer then stands for the rest of the build, and a later --version example publishes it. Clearing the memo hands the next reader its own walk, at the cost of repeating one.

A field the caller pinned through fields= is not a resolution and survives: see _field_overrides.

Return type:

None

static cli_frame()[source]

Returns the frame in which the CLI is implemented.

Walks the execution stack from the innermost frame outwards, to find the package in which the user’s CLI is implemented. The walk reads the module and the function name of each frame off the frame itself, with no source lookup: --version is eager, so every CLI pays for this walk at startup.

Returns the frame itself. When every frame belongs to the Click ecosystem and none is an entry point, returns the outermost frame, which has no caller: module then defers to the module of the root command’s callback.

Return type:

FrameType

static command_module(ctx)[source]

Returns the module implementing the root command’s callback.

The stack walk in cli_frame() can only find the CLI when the CLI’s own module is on the stack. That holds for a normal invocation, and for a CliRunner driven from the test module that declares the command, but not when a runner invokes a command it merely imported: the walk then finds no user frame at all and stops on the runner’s own invoke(), inside the Click ecosystem.

The Sphinx click:run directive is that shape: without this, a documented --version would render the version of the ecosystem package owning the runner in place of the CLI’s own.

A launcher is the other shape. A console script or a compiled binary whose entry point is a command object, like orchard.cli:cli, leaves no frame of that module on the stack: the walk ends on the launcher itself.

A command’s callback names its defining module directly and needs no stack, so it settles the case the walk cannot see. Returns None when the command has no callback (a bare click.Group) or its module is not imported, leaving the walk’s own answer in place.

Return type:

ModuleType | None

property module: ModuleType[source]

Returns the module in which the CLI resides.

property module_name: str[source]

Returns the full module name or __main__.

property module_file: str | None[source]

Returns the module’s file full path.

None for a module with no file, like the __main__ of python -c.

property module_version: str | None[source]

Returns the string found in the local __version__ variable.

Hint

__version__ is a convention from early Python packaging. It is not a standard variable and is not defined in the packaging PEPs.

Prefer the package_version property below, which uses the standard library importlib.metadata API.

Click’s own version_option reads the package metadata only (pallets/click#2598). Click Extra reads __version__ too, for the scripts and codebases that set it.

property package_name: str | None[source]

Returns the package name.

property package_version: str | None[source]

Returns the package version if installed.

Resolved from the distribution name (see _distribution_name) via importlib.metadata.version(). Returns None if the package is not installed or cannot be resolved.

property author: str | None[source]

Returns the package author(s) from its core metadata.

See resolve_author() for the fields read, in order. None if no author can be determined.

property license: str | None[source]

Returns the package license from its core metadata.

See resolve_license() for the fields read, in order. None if no license can be determined.

property exec_name: str[source]

User-friendly name of the executed CLI.

Returns the module name. But if the module is a __main__ entry point, returns the package name: python -m runs it as __main__, while a console script or a compiled binary imports it as package.__main__.

If not packaged, the CLI is assumed to be a simple standalone script, and the returned name is the script’s file name (including its extension). Code with no file, like a CLI run by python -c, keeps the __main__ module name.

property version: str | None[source]

Return the version of the CLI.

Returns the module version if a __version__ variable is set alongside the CLI in its module.

Else returns the package version if the CLI is implemented in a package, using importlib.metadata.version().

For development versions (containing .dev), automatically appends the Git short hash as a PEP 440 local version identifier, producing versions like 1.2.3.dev0+abc1234. This helps identify the exact commit a dev build was produced from. When git_short_hash finds no commit, the plain dev version is returned.

Versions that already contain a + (a pre-baked local version identifier, typically set at build time by CI pipelines) are returned as-is to avoid producing invalid double-suffixed versions like 1.2.3.dev0+abc1234+xyz5678.

property git_repo_path: Path | None[source]

Find the Git repository root directory.

Walks up from _search_start to the first directory holding a .git entry: see find_git_root().

property git_branch: str | None[source]

Returns the current Git branch name.

Checks for a pre-baked __git_branch__ dunder first, then git rev-parse --abbrev-ref HEAD, then .git_archival.json.

property git_long_hash: str | None[source]

Returns the full Git commit hash.

Checks for a pre-baked __git_long_hash__ dunder first, then git rev-parse HEAD, then .git_archival.json, then the commit recorded for an install from a Git URL.

property git_short_hash: str | None[source]

Returns the short Git commit hash.

Checks for a pre-baked __git_short_hash__ dunder first, then git rev-parse --short HEAD, then .git_archival.json, then the commit recorded for an install from a Git URL. Both fallbacks derive it from the first 7 characters of the full hash.

Hint

The short hash is usually the first 7 characters of the full hash, but this is not guaranteed to be the case.

But it is at least guaranteed to be unique within the repository, and a minimum of 4 characters.

property git_date: str | None[source]

Returns the commit date in ISO format: YYYY-MM-DD HH:MM:SS +ZZZZ.

Checks for a pre-baked __git_date__ dunder first, then git show -s --format=%ci HEAD, then .git_archival.json (whose node-date is strict ISO 8601, like 2021-01-01T12:00:00+00:00).

property git_tag: str | None[source]

Returns the Git tag pointing at HEAD, if any.

Checks for a pre-baked __git_tag__ dunder first, then git describe --tags --exact-match HEAD, then .git_archival.json.

Returns None if HEAD is not at a tagged commit.

property git_tag_sha: str | None[source]

Returns the commit SHA that the current tag points at.

Checks for a pre-baked __git_tag_sha__ dunder first, then git rev-list -1 on the tag returned by git_tag, then .git_archival.json. Returns None if HEAD is not at a tag.

property git_distance: str | None[source]

Number of commits since the most recent tag, or None.

Checks for a pre-baked __git_distance__ dunder first, then parses git describe --tags --long, then falls back to .git_archival.json. None when no tag is reachable or Git is unavailable.

property git_dirty: str | None[source]

Work-tree state: "dirty", "clean" or None.

Checks for a pre-baked __git_dirty__ dunder first, then runs git status --porcelain. None when not in a Git repository or Git is unavailable. There is no .git_archival.json fallback: an archive has no work tree, so its state is unknowable.

property build_time: str | None[source]

When the distribution was built, as an RFC 3339 UTC timestamp.

Reads the pre-baked __build_time__ dunder, the only source of a build fact: see BUILD_RESOLVERS and resolve_build_time().

property build_os: str | None[source]

The operating system the build ran on.

Reads the pre-baked __build_os__ dunder. See resolve_build_os().

property build_target: str | None[source]

The platform a distribution built here installs on.

Reads the pre-baked __build_target__ dunder. See resolve_build_target().

property build_target_arch: str | None[source]

The CPU architecture the build ran on.

Reads the pre-baked __build_target_arch__ dunder. See resolve_build_target_arch().

property prog_name: str | None

Return the name of the CLI, from Click’s point of view.

Get the info_name of the root command.

Note

Unlike its siblings, this field is resolved on every access instead of being cached on the instance: it is the one template field whose value legitimately varies between invocations of the same option instance sharing a process. multicall dispatch relies on that, running one CLI under many names in sequence, and a prog_name passed to main() varies it without any multicall at all. A cached value would pin the first name seen forever.

field_style(field_id=None)[source]

Style painting the field_id segment of a rendered message.

A field carrying no style of its own falls back to message_style, and one left unset by the caller too renders bare. Call with no field_id for the style of the template’s literal segments, which is message_style alone.

Return type:

Callable[[str], str]

colored_template(template=None)[source]

Insert ANSI styles to a message template.

Accepts a custom template as parameter, otherwise uses the default message defined on the Option instance.

The template is linearized so the ANSI codes apply to its string segments: an ANSI directive cannot be nested within another, unlike a markup tag of HTML.

Return type:

str

render_message(template=None)[source]

Render the version string from the provided template.

Accepts a custom template as parameter, otherwise uses the default self.colored_template() produced by the instance.

A CLI carrying a VersionScreen gets that drawn instead, whenever three conditions hold. Failing any one of them falls back to the plain template unchanged, which is a deliberate guarantee rather than a default: that form is the one every machine reader parses.

  • Color reaches the output. A flat-shaded mark carries its shape in its colors, and color is the one lever a caller already has. A redirected --version, or one run under --no-color or NO_COLOR, is asking for something parseable.

  • The terminal is wide enough to seat the facts beside the mark without wrapping them.

  • Accessible mode is off. A mark read out character by character is noise to a screen reader, so --accessible keeps the plain message.

Return type:

str

print_debug_message()[source]

Render in debug logs all template fields in color.

Return type:

None

print_and_exit(ctx, param, value)[source]

Print the version string and exits.

Also stores all version string elements in the Context’s meta dict.

Return type:

None

click_extra.version.reset_version_resolution(command)[source]

Reset every VersionOption in a command tree.

Walks the tree once, cycle-safe, and calls VersionOption.reset_resolution() on each option it finds.

Written for a documentation build, which renders many commands in one process where a CLI renders one. See that method for what a stale resolution costs a published page.

Note

The walk reads the subcommands each group has registered, rather than going through iter_subcommand_contexts() like the renderers do. A lazy subcommand not imported yet holds no resolution to reset, and the context that function builds for each subcommand runs its --version callback, which resolves the very chain this function clears.

Return type:

None