|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import logging |
| 4 | +import os # noqa: TC003 |
| 5 | +import re |
| 6 | +from dataclasses import dataclass |
| 7 | +from email.parser import HeaderParser |
| 8 | +from pathlib import Path |
| 9 | +from typing import TYPE_CHECKING |
| 10 | + |
| 11 | +from setuptools_git_versioning.defaults import ( |
| 12 | + DEFAULT_DEV_TEMPLATE, |
| 13 | + DEFAULT_DIRTY_TEMPLATE, |
| 14 | + DEFAULT_TEMPLATE, |
| 15 | +) |
| 16 | +from setuptools_git_versioning.log import DEBUG, INFO |
| 17 | +from setuptools_git_versioning.subst import resolve_substitutions |
| 18 | + |
| 19 | +if TYPE_CHECKING: |
| 20 | + from packaging.version import Version |
| 21 | + |
| 22 | +ARCHIVAL_FILENAME = ".git_archival.txt" |
| 23 | +DESCRIBE_UNSUPPORTED = "%(describe" |
| 24 | +FORMAT_UNSUBSTITUTED = "$Format" |
| 25 | +DESCRIBE_PARTS = 3 # tag-N-gSHA |
| 26 | + |
| 27 | +REF_TAG_RE = re.compile(r"(?<=\btag: )([^,]+)\b") |
| 28 | +REF_HEAD_RE = re.compile(r"HEAD\s*->\s*([^,]+)") |
| 29 | +FULL_SHA_RE = re.compile(r"^([0-9a-f]{40}|[0-9a-f]{64})$") # SHA-1 or SHA-256 |
| 30 | + |
| 31 | +log = logging.getLogger(__name__) |
| 32 | + |
| 33 | + |
| 34 | +@dataclass |
| 35 | +class ArchivalData: |
| 36 | + tag: str |
| 37 | + ccount: int |
| 38 | + sha: str |
| 39 | + full_sha: str |
| 40 | + dirty: bool |
| 41 | + branch: str | None |
| 42 | + |
| 43 | + |
| 44 | +def parse_archival_file(path: str | os.PathLike) -> dict[str, str]: |
| 45 | + """Read a .git_archival.txt file and return its key/value pairs. |
| 46 | +
|
| 47 | + Keys are normalized to lowercase so lookups behave consistently |
| 48 | + regardless of whether the file uses `node:` or `Node:` etc. |
| 49 | + """ |
| 50 | + content = Path(path).read_text(encoding="utf-8") |
| 51 | + log.log(DEBUG, "'%s' content:\n%s", ARCHIVAL_FILENAME, content) |
| 52 | + message = HeaderParser().parsestr(content) |
| 53 | + |
| 54 | + # HeaderParser treats the first blank line as the end of headers. |
| 55 | + # Anything after it ends up in the message body and is silently |
| 56 | + # dropped from .items(). Warn the user instead of losing fields. |
| 57 | + payload = message.get_payload() |
| 58 | + if isinstance(payload, str) and payload.strip(): |
| 59 | + log.warning( |
| 60 | + "'%s' contains content after a blank line; those fields will be ignored", |
| 61 | + ARCHIVAL_FILENAME, |
| 62 | + ) |
| 63 | + |
| 64 | + return {key.lower(): value for key, value in message.items()} |
| 65 | + |
| 66 | + |
| 67 | +def _parse_describe(describe: str) -> tuple[str, int, str | None, bool]: |
| 68 | + """Parse a `git describe`-style string into (tag, ccount, short_sha, dirty).""" |
| 69 | + dirty = False |
| 70 | + if describe.endswith("-dirty"): |
| 71 | + dirty = True |
| 72 | + describe = describe[: -len("-dirty")] |
| 73 | + |
| 74 | + parts = describe.rsplit("-", 2) |
| 75 | + if len(parts) < DESCRIBE_PARTS: |
| 76 | + return describe, 0, None, dirty |
| 77 | + |
| 78 | + tag, ccount_str, gnode = parts |
| 79 | + try: |
| 80 | + ccount = int(ccount_str) |
| 81 | + except ValueError: |
| 82 | + return describe, 0, None, dirty |
| 83 | + |
| 84 | + short_sha = gnode[1:] if gnode.startswith("g") else gnode |
| 85 | + return tag, ccount, short_sha, dirty |
| 86 | + |
| 87 | + |
| 88 | +def _branch_from_ref_names(ref_names: str) -> str | None: |
| 89 | + match = REF_HEAD_RE.search(ref_names) |
| 90 | + if match: |
| 91 | + return match.group(1).strip() |
| 92 | + return None |
| 93 | + |
| 94 | + |
| 95 | +def archival_to_version_data(data: dict[str, str]) -> ArchivalData | None: |
| 96 | + """Convert parsed archival data into structured version info, or None. |
| 97 | +
|
| 98 | + Returns None when the file looks unsubstituted or otherwise unusable so |
| 99 | + the caller can fall through to live git. |
| 100 | + """ |
| 101 | + if any(FORMAT_UNSUBSTITUTED in value for value in data.values()): |
| 102 | + log.warning( |
| 103 | + "'%s' contains unprocessed '$Format:...$' placeholders, skipping", |
| 104 | + ARCHIVAL_FILENAME, |
| 105 | + ) |
| 106 | + return None |
| 107 | + |
| 108 | + node = data.get("node", "").strip() |
| 109 | + full_sha = node if FULL_SHA_RE.match(node) else "" |
| 110 | + ref_names = data.get("ref-names", "") |
| 111 | + branch = _branch_from_ref_names(ref_names) |
| 112 | + describe = data.get("describe-name", "").strip() |
| 113 | + |
| 114 | + describe_tag: str | None = None |
| 115 | + ccount = 0 |
| 116 | + short_sha = "" |
| 117 | + dirty = False |
| 118 | + |
| 119 | + if describe and DESCRIBE_UNSUPPORTED not in describe: |
| 120 | + describe_tag, ccount, parsed_sha, dirty = _parse_describe(describe) |
| 121 | + if parsed_sha: |
| 122 | + short_sha = parsed_sha |
| 123 | + elif describe: |
| 124 | + log.warning( |
| 125 | + "git archive did not expand %(describe...) (git <2.32), falling back to ref-names", |
| 126 | + ) |
| 127 | + |
| 128 | + if describe_tag is not None: |
| 129 | + tag = describe_tag |
| 130 | + else: |
| 131 | + tags = REF_TAG_RE.findall(ref_names) |
| 132 | + if not tags: |
| 133 | + log.log( |
| 134 | + INFO, |
| 135 | + "'%s' has no usable describe-name or tag in ref-names", |
| 136 | + ARCHIVAL_FILENAME, |
| 137 | + ) |
| 138 | + return None |
| 139 | + tag = tags[0].strip() |
| 140 | + |
| 141 | + # Prefer the full SHA when available so {sha} matches the live-git |
| 142 | + # path's `full_sha[:8]` rendering. Fall back to the short SHA from |
| 143 | + # describe-name only when no valid `node` field is present. |
| 144 | + if full_sha: |
| 145 | + short_sha = full_sha[:8] |
| 146 | + elif short_sha: |
| 147 | + full_sha = short_sha |
| 148 | + |
| 149 | + return ArchivalData( |
| 150 | + tag=tag, |
| 151 | + ccount=ccount, |
| 152 | + sha=short_sha[:8], |
| 153 | + full_sha=full_sha, |
| 154 | + dirty=dirty, |
| 155 | + branch=branch, |
| 156 | + ) |
| 157 | + |
| 158 | + |
| 159 | +def version_from_archival( |
| 160 | + project_root: str | os.PathLike, |
| 161 | + *, |
| 162 | + template: str = DEFAULT_TEMPLATE, |
| 163 | + dev_template: str = DEFAULT_DEV_TEMPLATE, |
| 164 | + dirty_template: str = DEFAULT_DIRTY_TEMPLATE, |
| 165 | +) -> Version | None: |
| 166 | + """Return a Version derived from .git_archival.txt, or None if unavailable.""" |
| 167 | + archival_path = Path(project_root).joinpath(ARCHIVAL_FILENAME) |
| 168 | + if not archival_path.exists(): |
| 169 | + log.log(DEBUG, "No '%s' present at '%s'", ARCHIVAL_FILENAME, project_root) |
| 170 | + return None |
| 171 | + |
| 172 | + log.log(INFO, "File '%s' is found, reading its content", archival_path) |
| 173 | + data = parse_archival_file(archival_path) |
| 174 | + info = archival_to_version_data(data) |
| 175 | + if info is None: |
| 176 | + return None |
| 177 | + |
| 178 | + log.log(DEBUG, "Parsed archival data: %r", info) |
| 179 | + |
| 180 | + if info.dirty: |
| 181 | + log.log(INFO, "Using template from 'dirty_template' option") |
| 182 | + chosen = dirty_template |
| 183 | + elif info.ccount > 0: |
| 184 | + log.log(INFO, "Using template from 'dev_template' option") |
| 185 | + chosen = dev_template |
| 186 | + else: |
| 187 | + log.log(INFO, "Using template from 'template' option") |
| 188 | + chosen = template |
| 189 | + |
| 190 | + # When ref-names is absent or doesn't reveal a current branch, default |
| 191 | + # to the literal "HEAD" so `{branch}` substitution mirrors what |
| 192 | + # `git rev-parse --abbrev-ref HEAD` produces in detached-HEAD state. |
| 193 | + branch = info.branch if info.branch is not None else "HEAD" |
| 194 | + |
| 195 | + rendered = resolve_substitutions( |
| 196 | + chosen, |
| 197 | + sha=info.sha, |
| 198 | + tag=info.tag, |
| 199 | + ccount=info.ccount, |
| 200 | + branch=branch, |
| 201 | + full_sha=info.full_sha, |
| 202 | + ) |
| 203 | + log.log(INFO, "Version number after resolving substitutions: %r", rendered) |
| 204 | + |
| 205 | + # Deferred to avoid a top-level circular import: |
| 206 | + # `version.py` imports `version_from_archival` from this module. |
| 207 | + from setuptools_git_versioning.version import sanitize_version |
| 208 | + |
| 209 | + return sanitize_version(rendered) |
0 commit comments