click_extra.version_facts module

Resolvers for the facts a --version message reports.

Each function answers one fact on its own, with no option or command around it: the live Git state (GIT_RESOLVERS, run_git()), the build host (BUILD_RESOLVERS), the .git_archival.json and direct_url.json fallbacks, the core metadata of a distribution (resolve_author(), resolve_license()), and the interpreter and platform (default_facts(), env_summary()). VersionOption chains them into its template fields, and click-extra prebake all calls them to bake the values into a build.

click_extra.version_facts.distribution_of(package_name)[source]

Resolve an import package name to the installed distribution providing it.

An import (top-level module) name may differ from the distribution name (PIL vs Pillow, jwt vs PyJWT). A name already matching an installed distribution is returned as-is; otherwise it is resolved through importlib.metadata.packages_distributions(). Ambiguous mappings (one import name to several distributions) return None: pass package_name explicitly to disambiguate.

Returns None when nothing installed provides the name, which is what makes it usable as a test of whether a module belongs to a real distribution.

Return type:

str | None

click_extra.version_facts.GIT_FIELDS: dict[str, tuple[str, ...]] = {'git_branch': ('rev-parse', '--abbrev-ref', 'HEAD'), 'git_date': ('show', '-s', '--format=%ci', 'HEAD'), 'git_long_hash': ('rev-parse', 'HEAD'), 'git_short_hash': ('rev-parse', '--short', 'HEAD'), 'git_tag': ('describe', '--tags', '--exact-match', 'HEAD')}

Git fields whose live value is the stripped output of one static git subcommand, mapped to that subcommand’s args.

git_tag_sha, git_distance and git_dirty are excluded: their resolution is not a single static git invocation whose stripped output is the value. git_tag_sha dereferences the tag (git rev-list -1 <tag>), git_distance parses git describe and git_dirty maps the porcelain status to a label. See resolve_git_tag_sha(), resolve_git_distance() and resolve_git_dirty().

For the resolver of every pre-bakeable git field (these five plus the three computed ones), keyed uniformly by field ID, see GIT_RESOLVERS.

click_extra.version_facts.GIT_TIMEOUT: float = 5

Seconds run_git() lets a git command run before it gives up on it.

A local read answers in milliseconds. The bound is for a repository that blocks, like one on a network share that stopped answering.

click_extra.version_facts.run_git(*args, cwd=None, allow_empty=False, check=False, timeout=5)[source]

Run a git command and return its output, without the final newline.

A command that fails returns None: no git on the PATH, a non-zero exit status, like the one of a cwd outside a repository, or a command still running after timeout seconds. Set check to raise instead: an OSError when git does not start, a subprocess.CalledProcessError on a non-zero exit status, and a subprocess.TimeoutExpired when the time runs out.

By default an empty output returns None too, like a failure. Set allow_empty to keep the empty string, which some commands use meaningfully: git status --porcelain prints nothing for a clean work tree, and that is distinct from the command failing.

The output decodes as UTF-8, and a byte that is no UTF-8 becomes a replacement character: Git prints a ref name as the bytes it stores, which a repository can hold in any encoding.

Parameters:

cwd (Path | None) – the folder to run in. The current working directory when None.

Return type:

str | None

click_extra.version_facts.resolve_git_dirty(cwd=None)[source]

Report the work-tree state as "dirty", "clean" or None.

Returns "dirty" when git status --porcelain reports uncommitted changes, "clean" when it reports none, and None when the state cannot be determined (not a Git repository, or git is unavailable).

The empty output of a clean work tree is meaningful here, so the command is run with allow_empty to tell it apart from a failure.

Return type:

str | None

click_extra.version_facts.resolve_git_distance(cwd=None)[source]

Count commits since the most recent tag, as a string, or None.

Parses git describe --tags --long, whose output has the form <tag>-<distance>-g<short_hash>. Returns None when no tag is reachable, the directory is not a Git repository, or git is unavailable.

Return type:

str | None

click_extra.version_facts.resolve_git_tag_sha(cwd=None)[source]

Resolve the commit SHA the tag at HEAD points at, or None.

Runs git describe --tags --exact-match HEAD to find the tag, then git rev-list -1 <tag> to dereference it to a commit SHA. Returns None when HEAD is not at a tagged commit, the directory is not a Git repository, or git is unavailable.

Return type:

str | None

click_extra.version_facts.GIT_RESOLVERS: dict[str, Callable[[Path | None], str | None]] = {'git_branch': <function _direct_git_resolver.<locals>.resolver>, 'git_date': <function _direct_git_resolver.<locals>.resolver>, 'git_dirty': <function resolve_git_dirty>, 'git_distance': <function resolve_git_distance>, 'git_long_hash': <function _direct_git_resolver.<locals>.resolver>, 'git_short_hash': <function _direct_git_resolver.<locals>.resolver>, 'git_tag': <function _direct_git_resolver.<locals>.resolver>, 'git_tag_sha': <function resolve_git_tag_sha>}

Canonical live resolver for every pre-bakeable git_* field.

Maps each field ID to a callable that takes an optional working directory and returns the field’s value by shelling out to git (or None when it cannot be resolved). This is the single source of truth for how each git field is computed live, shared by two consumers:

  • VersionOption’s runtime accessors, which wrap each resolver with the pre-baked-dunder and .git_archival.json fallbacks.

  • the click-extra prebake all command, which calls every resolver to bake values into source files at build time.

Keeping it here means adding a new git field is a one-line edit in this module, with no matching change needed in the CLI.

click_extra.version_facts.SOURCE_DATE_EPOCH = 'SOURCE_DATE_EPOCH'

Environment variable a reproducible build sets to pin every timestamp it writes.

See the reproducible-builds.org specification.

click_extra.version_facts.build_moment()[source]

The instant a build happens, in UTC.

Reads SOURCE_DATE_EPOCH when the build sets it, so two runs of a reproducible build stamp the same instant. Falls back to the current time.

Return type:

datetime

click_extra.version_facts.resolve_build_time()[source]

The moment the distribution is built, as an RFC 3339 UTC timestamp.

See build_moment() for where the instant comes from.

Return type:

str

click_extra.version_facts.resolve_build_os()[source]

The operating system the build runs on.

Return type:

str

click_extra.version_facts.resolve_build_target()[source]

The platform a distribution built here installs on.

This is the wheel platform tag (macosx-15.0-arm64, linux-x86_64, win-amd64), which is Python’s answer to the target triple shadow-rs bakes into a Rust binary. It states an ABI floor the two fields beside it cannot: macosx-15.0-arm64 says the binary needs macOS 15, where resolve_build_os() only says it was built on macOS.

Return type:

str

click_extra.version_facts.resolve_build_target_arch()[source]

The CPU architecture the build runs on.

Return type:

str

click_extra.version_facts.BUILD_RESOLVERS: dict[str, Callable[[], str]] = {'build_os': <function resolve_build_os>, 'build_target': <function resolve_build_target>, 'build_target_arch': <function resolve_build_target_arch>, 'build_time': <function resolve_build_time>}

Canonical resolver for every pre-bakeable build_* field.

These describe the machine and moment a distribution was built, which GIT_RESOLVERS and env_summary() both leave unanswered: git states what source went in, env_summary() states where the binary is running now, and neither one identifies the host that produced it. That gap is what a cross-built binary turns into a support question, and what shadow-rs answers for Rust with its BUILD_TIME, BUILD_OS and BUILD_TARGET constants.

A build fact has no live fallback, unlike a git one: nothing at runtime can recover the host a binary was compiled on, so click-extra prebake all is the only thing that ever writes these. A field left unbaked stays empty, and its VersionOption accessor answers None.

Adding a field here is a one-line edit, with no matching change in the CLI.

click_extra.version_facts.dunder_name(field_id)[source]

The module-level name a pre-baked template field is stored under.

git_branch is baked as __git_branch__: the one spelling VersionOption reads back, and click-extra prebake writes. Keeping the contract in one place is what lets the two sides stay agreed.

Return type:

str

click_extra.version_facts.find_git_root(start)[source]

Walk up from start to the first folder holding a .git entry.

The entry is a folder in a plain clone, and a file in a worktree or a submodule. Returns that folder, start included, or None.

Return type:

Path | None

click_extra.version_facts.find_archival_file(start)[source]

Walk up from start to find a .git_archival.json file.

Returns the first match in start or any of its parents, or None.

Return type:

Path | None

click_extra.version_facts.read_archival(path)[source]

Parse a .git_archival.json file into a string mapping.

Returns an empty mapping when the file is missing, unreadable, or not a valid JSON object.

Return type:

dict[str, str]

click_extra.version_facts.archival_field(data, field_id)[source]

Resolve a git_* field from parsed .git_archival.json data.

data follows the setuptools-scm archival schema: node (full hash), node-date, describe-name and ref-names. The same file is read by setuptools-scm and Dunamai, so a single committed .git_archival.json serves all three.

Returns None when the field is absent, empty, or still holds an unsubstituted $Format:…$ placeholder. That last case is what a plain checkout contains: git archive performs the substitution, so values are real only inside an exported archive (including GitHub’s source tarballs).

There is no entry for git_dirty: an archive has no work tree, so its state is unknowable.

Return type:

str | None

click_extra.version_facts.read_direct_url(distribution)[source]

Parse the direct_url.json record of an installed distribution.

PEP 610 has installers write this record beside the metadata of a distribution installed from a URL, like uvx --from git+https://... or pip install git+https://....

Returns an empty mapping when the distribution is not installed, carries no record, or holds a record that is not a JSON object.

Return type:

dict[str, Any]

click_extra.version_facts.direct_url_field(data, field_id)[source]

Resolve a git_* field from a parsed direct_url.json record.

Only an install from a Git URL records a commit: the full hash of the checkout the installer built, in vcs_info.commit_id. It answers git_long_hash, and its first 7 characters git_short_hash.

Every other field answers None. The vcs_info.requested_revision the record may also hold names a branch, a tag or a commit, with nothing to tell which.

Return type:

str | None

click_extra.version_facts.resolve_distribution(names)[source]

Return the first installed distribution among names, or None.

Probes each candidate name in order with importlib.metadata.distribution() and returns the first that resolves to an installed distribution. Used to pick a distribution from a set of plausible spellings (like the program name with - / _ variants) before reading its metadata.

Return type:

str | None

click_extra.version_facts.meta_value(meta, *keys)[source]

Return the first non-empty value among core-metadata keys.

Each key is tested with in before [] reads it: [] on a missing key returns None with a DeprecationWarning, and is to raise KeyError.

Return type:

str | None

click_extra.version_facts.resolve_author(meta)[source]

Return the author(s) from meta’s core metadata, or None.

Prefers the Author field, then the Maintainer field, then the display name parsed out of the Author-email / Maintainer-email fields (Name <email>). Returns None when meta is None or no author can be determined.

Return type:

str | None

click_extra.version_facts.resolve_license(meta)[source]

Return the license from meta’s core metadata, or None.

Prefers the SPDX License-Expression field (core metadata 2.4+). Falls back to the human-readable name of the first License :: trove classifier, then to the free-form License field (which may hold the full license text). Returns None when meta is None or no license can be determined.

Return type:

str | None

click_extra.version_facts.platform_label()[source]

Current platform and CPU architecture, as displayed to the user.

Return type:

str

click_extra.version_facts.env_summary()[source]

One-line interpreter and platform summary.

Reads Python 3.14.7, macOS ARM64 (AArch64) on an Apple Silicon Mac: the same two facts default_facts() puts on the version screen, joined for a CLI that would rather spend one line of its plain --version on them than draw a screen at all: @version_option(message="{prog_name} {version} (" + env_summary() + ")").

Return type:

str

click_extra.version_facts.dependency_versions()[source]

The Click and Cloup releases this install is sitting on.

Worth a row on a screen whose main job is to be pasted into a bug report: Click Extra subclasses both, so which of the three is at fault is the first question any such report raises. Not a default fact, since a CLI built on Click Extra may reasonably consider that its own business rather than its user’s.

Read from the installed distributions: Click deprecates its own __version__ attribute.

Return type:

str

click_extra.version_facts.default_facts()[source]

The facts every version screen carries, as an ordered label-to-value map.

A mapping rather than a sequence of pairs so a CLI can adjust one row without restating the rest, dict preserving insertion order and replacement keeping a key where it already sat:

default_facts() | {"Platform": my_own_label}   # replaces, in place
default_facts() | {"Docs": DOCS_URL}           # appends, at the end
Return type:

dict[str, str]