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
VersionScreentake 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 fromCLI_ECOSYSTEM_PACKAGESeven when it sits under one of those packages, asclick_extra.__main__does in Click Extra’s own binary.- Return type:
- 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_THEMEand the background-sniffingautoalike, and drops its color under the monochromemanpagepalette. A style captured at import would paint every theme with one palette: the bright white program name ofdarkis 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.
- click_extra.version.unstyled(text)[source]¶
Identity style, for a segment left with no color of its own.
- Return type:
- class click_extra.version.VersionScreen(logo, tagline='', facts=<function default_facts>, gutter=' ')[source]¶
Bases:
objectA logo, and the facts to seat beside it, as
--versionshould 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
VersionOptionthrough itsscreenargument, or to a whole CLI throughdefault_params(screen=…).- logo: str | Sequence[str] | Callable[[], str | Sequence[str]]¶
The mark, pre-rendered, or a callable producing it. A string splits on newlines.
A callable defers the rendering to the first
--versionthat draws the screen, asfactsdoes for its values: a mark painted by code, from an image say, then costs nothing to the invocations that never ask for it.
- 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
--versionis asked for.
- 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.
- 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
--versioncannot drift apart on color.
- 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
Nonewhen 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 reportsshutil’s 80-column default, wide enough that a redirected-but-forced-color run still gets the screen it asked for.
- 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
autodefault, exactly asclick.echodoes when it decides whether to strip the codes itself.Note
The stream probed is
sys.stdout, not Click’s own resolution of it.click.echoreaches stdout through a private cached wrapper, which fixes the output encoding and delegatesisatty()to the stream beneath it, so both answer alike. Click deprecates the public accessor of that wrapper,click.get_text_stream().- Return type:
- 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 oftemplate, in order: the literal text before the field, the identifier the field resolves on the option (modulefor{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.
- 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:
ExtraOptionGathers 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
--versionoption 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 oftemplate_fields(for example{"version": "1.2.3"}).styles (
Mapping[str,Callable[[str],str] |None] |None) – mapping of template field name to itsStyle, merged overdefault_styles. PassNoneas a value to clear a field’s default style. Keys must be members oftemplate_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) – aVersionScreento draw instead of the one-line message, whenever the terminal can take it. Left unset,--versionprints the one-line message.
- Raises:
TypeError – when a key of
fieldsorstylesnames 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-providedstylesare 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 defaultdarkpalette,invoked_commandis bright white bold andsuccessis green.
- message: str = '{prog_name}, version {version}'¶
Default message template used to render the version string.
- pin_field(field_id, value)[source]¶
Pin a template field to a caller-supplied value.
The value shadows the
cached_propertythat would otherwise resolve the field, and is recorded soreset_resolution()can tell the two apart. Every caller that pins a field goes through here: a baresetattrsets the value without the record, and the next reset then discards it.
- 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
--versionexample 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:
- 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:
--versionis 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:
modulethen defers to the module of the root command’s callback.- Return type:
- 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 aCliRunnerdriven 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 owninvoke(), inside the Click ecosystem.The Sphinx
click:rundirective is that shape: without this, a documented--versionwould 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
Nonewhen the command has no callback (a bareclick.Group) or its module is not imported, leaving the walk’s own answer in place.- Return type:
- property module: ModuleType[source]¶
Returns the module in which the CLI resides.
- property module_file: str | None[source]¶
Returns the module’s file full path.
Nonefor a module with no file, like the__main__ofpython -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_versionproperty below, which uses the standard libraryimportlib.metadataAPI.Click’s own
version_optionreads the package metadata only (pallets/click#2598). Click Extra reads__version__too, for the scripts and codebases that set it.
- property package_version: str | None[source]¶
Returns the package version if installed.
Resolved from the distribution name (see
_distribution_name) viaimportlib.metadata.version(). ReturnsNoneif 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.Noneif 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.Noneif 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 -mruns it as__main__, while a console script or a compiled binary imports it aspackage.__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 like1.2.3.dev0+abc1234. This helps identify the exact commit a dev build was produced from. Whengit_short_hashfinds 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 like1.2.3.dev0+abc1234+xyz5678.
- property git_repo_path: Path | None[source]¶
Find the Git repository root directory.
Walks up from
_search_startto the first directory holding a.gitentry: seefind_git_root().
- property git_branch: str | None[source]¶
Returns the current Git branch name.
Checks for a pre-baked
__git_branch__dunder first, thengit 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, thengit 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, thengit 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, thengit show -s --format=%ci HEAD, then.git_archival.json(whosenode-dateis strict ISO 8601, like2021-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, thengit describe --tags --exact-match HEAD, then.git_archival.json.Returns
Noneif 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, thengit rev-list -1on the tag returned bygit_tag, then.git_archival.json. ReturnsNoneif 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 parsesgit describe --tags --long, then falls back to.git_archival.json.Nonewhen no tag is reachable or Git is unavailable.
- property git_dirty: str | None[source]¶
Work-tree state:
"dirty","clean"orNone.Checks for a pre-baked
__git_dirty__dunder first, then runsgit status --porcelain.Nonewhen not in a Git repository or Git is unavailable. There is no.git_archival.jsonfallback: 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: seeBUILD_RESOLVERSandresolve_build_time().
- property build_os: str | None[source]¶
The operating system the build ran on.
Reads the pre-baked
__build_os__dunder. Seeresolve_build_os().
- property build_target: str | None[source]¶
The platform a distribution built here installs on.
Reads the pre-baked
__build_target__dunder. Seeresolve_build_target().
- property build_target_arch: str | None[source]¶
The CPU architecture the build ran on.
Reads the pre-baked
__build_target_arch__dunder. Seeresolve_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.
multicalldispatch relies on that, running one CLI under many names in sequence, and aprog_namepassed tomain()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 nofield_idfor the style of the template’s literal segments, which ismessage_stylealone.
- colored_template(template=None)[source]¶
Insert ANSI styles to a message template.
Accepts a custom
templateas 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:
- render_message(template=None)[source]¶
Render the version string from the provided template.
Accepts a custom
templateas parameter, otherwise uses the defaultself.colored_template()produced by the instance.A CLI carrying a
VersionScreengets 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-coloror 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
--accessiblekeeps the plain message.
- Return type:
- click_extra.version.reset_version_resolution(command)[source]¶
Reset every
VersionOptionin 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--versioncallback, which resolves the very chain this function clears.- Return type: