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 (
PILvsPillow,jwtvsPyJWT). A name already matching an installed distribution is returned as-is; otherwise it is resolved throughimportlib.metadata.packages_distributions(). Ambiguous mappings (one import name to several distributions) returnNone: passpackage_nameexplicitly to disambiguate.Returns
Nonewhen nothing installed provides the name, which is what makes it usable as a test of whether a module belongs to a real distribution.
- 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
gitsubcommand, mapped to that subcommand’s args.git_tag_sha,git_distanceandgit_dirtyare excluded: their resolution is not a single staticgitinvocation whose stripped output is the value.git_tag_shadereferences the tag (git rev-list -1 <tag>),git_distanceparsesgit describeandgit_dirtymaps the porcelain status to a label. Seeresolve_git_tag_sha(),resolve_git_distance()andresolve_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 agitcommand 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
gitcommand and return its output, without the final newline.A command that fails returns
None: nogiton thePATH, a non-zero exit status, like the one of acwdoutside a repository, or a command still running aftertimeoutseconds. Setcheckto raise instead: anOSErrorwhengitdoes not start, asubprocess.CalledProcessErroron a non-zero exit status, and asubprocess.TimeoutExpiredwhen the time runs out.By default an empty output returns
Nonetoo, like a failure. Setallow_emptyto keep the empty string, which some commands use meaningfully:git status --porcelainprints 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.
- click_extra.version_facts.resolve_git_dirty(cwd=None)[source]¶
Report the work-tree state as
"dirty","clean"orNone.Returns
"dirty"whengit status --porcelainreports uncommitted changes,"clean"when it reports none, andNonewhen the state cannot be determined (not a Git repository, orgitis unavailable).The empty output of a clean work tree is meaningful here, so the command is run with
allow_emptyto tell it apart from a failure.
- 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>. ReturnsNonewhen no tag is reachable, the directory is not a Git repository, orgitis unavailable.
- click_extra.version_facts.resolve_git_tag_sha(cwd=None)[source]¶
Resolve the commit SHA the tag at
HEADpoints at, orNone.Runs
git describe --tags --exact-match HEADto find the tag, thengit rev-list -1 <tag>to dereference it to a commit SHA. ReturnsNonewhenHEADis not at a tagged commit, the directory is not a Git repository, orgitis unavailable.
- 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(orNonewhen 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.jsonfallbacks.the
click-extra prebake allcommand, 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.
- click_extra.version_facts.build_moment()[source]¶
The instant a build happens, in UTC.
Reads
SOURCE_DATE_EPOCHwhen the build sets it, so two runs of a reproducible build stamp the same instant. Falls back to the current time.- Return type:
- 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:
- click_extra.version_facts.resolve_build_os()[source]¶
The operating system the build runs on.
- Return type:
- 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-arm64says the binary needs macOS 15, whereresolve_build_os()only says it was built on macOS.- Return type:
- click_extra.version_facts.resolve_build_target_arch()[source]¶
The CPU architecture the build runs on.
- Return type:
- 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_RESOLVERSandenv_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 itsBUILD_TIME,BUILD_OSandBUILD_TARGETconstants.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 allis the only thing that ever writes these. A field left unbaked stays empty, and itsVersionOptionaccessor answersNone.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_branchis baked as__git_branch__: the one spellingVersionOptionreads back, andclick-extra prebakewrites. Keeping the contract in one place is what lets the two sides stay agreed.- Return type:
- click_extra.version_facts.find_git_root(start)[source]¶
Walk up from start to the first folder holding a
.gitentry.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.
- click_extra.version_facts.find_archival_file(start)[source]¶
Walk up from start to find a
.git_archival.jsonfile.Returns the first match in start or any of its parents, or
None.
- click_extra.version_facts.read_archival(path)[source]¶
Parse a
.git_archival.jsonfile into a string mapping.Returns an empty mapping when the file is missing, unreadable, or not a valid JSON object.
- click_extra.version_facts.archival_field(data, field_id)[source]¶
Resolve a
git_*field from parsed.git_archival.jsondata.data follows the setuptools-scm archival schema:
node(full hash),node-date,describe-nameandref-names. The same file is read by setuptools-scm and Dunamai, so a single committed.git_archival.jsonserves all three.Returns
Nonewhen the field is absent, empty, or still holds an unsubstituted$Format:…$placeholder. That last case is what a plain checkout contains:git archiveperforms 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.
- click_extra.version_facts.read_direct_url(distribution)[source]¶
Parse the
direct_url.jsonrecord 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://...orpip 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.
- click_extra.version_facts.direct_url_field(data, field_id)[source]¶
Resolve a
git_*field from a parseddirect_url.jsonrecord.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 answersgit_long_hash, and its first 7 charactersgit_short_hash.Every other field answers
None. Thevcs_info.requested_revisionthe record may also hold names a branch, a tag or a commit, with nothing to tell which.
- 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.
- click_extra.version_facts.meta_value(meta, *keys)[source]¶
Return the first non-empty value among core-metadata keys.
Each key is tested with
inbefore[]reads it:[]on a missing key returnsNonewith aDeprecationWarning, and is to raiseKeyError.
- click_extra.version_facts.resolve_author(meta)[source]¶
Return the author(s) from meta’s core metadata, or
None.Prefers the
Authorfield, then theMaintainerfield, then the display name parsed out of theAuthor-email/Maintainer-emailfields (Name <email>). ReturnsNonewhen meta isNoneor no author can be determined.
- click_extra.version_facts.resolve_license(meta)[source]¶
Return the license from meta’s core metadata, or
None.Prefers the SPDX
License-Expressionfield (core metadata 2.4+). Falls back to the human-readable name of the firstLicense ::trove classifier, then to the free-formLicensefield (which may hold the full license text). ReturnsNonewhen meta isNoneor no license can be determined.
- click_extra.version_facts.platform_label()[source]¶
Current platform and CPU architecture, as displayed to the user.
- Return type:
- 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 factsdefault_facts()puts on the version screen, joined for a CLI that would rather spend one line of its plain--versionon them than draw a screen at all:@version_option(message="{prog_name} {version} (" + env_summary() + ")").- Return type:
- 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:
- 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,
dictpreserving 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