Coverage for src/livingproof_common/versioning.py: 90%

126 statements  

« prev     ^ index     » next       coverage.py v7.18.0, created at 2026-12-02 11:49 +0000

1"""Display source identity separately from Hatch-VCS's PEP 440 package version.""" 

2import hashlib 

3import json 

4import os 

5import re 

6import subprocess 

7from importlib import metadata 

8from dataclasses import dataclass 

9from pathlib import Path 

10 

11PROVENANCE = "_build_provenance.json" 

12 

13 

14@dataclass(frozen=True) 

15class Consumer: 

16 """A caller's distribution and package location, never the common library's. 

17 

18 ``package_dir`` is the consumer module directory (typically derived from its 

19 own ``__file__``). Only the direct ``root/src/package`` layout probes live Git. 

20 Public origins are exact approved URLs; default output hides branch names. 

21 """ 

22 

23 distribution: str 

24 package_dir: Path 

25 public_origins: tuple[str, ...] = () 

26 

27 def __post_init__(self): 

28 if not re.fullmatch(r"[A-Za-z0-9]+(?:[._-][A-Za-z0-9]+)*", self.distribution): 

29 raise ValueError("Expected a Python distribution name") 

30 object.__setattr__(self, "package_dir", Path(self.package_dir).resolve()) 

31 

32 

33RELEASE = r"(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)" 

34 

35 

36def git(root, *args): 

37 """Read this root only, without inherited Git redirection or optional writes.""" 

38 env = {k: v for k, v in os.environ.items() if not k.startswith("GIT_")} 

39 env["GIT_OPTIONAL_LOCKS"] = "0" 

40 try: 

41 result = subprocess.run( 

42 ["git", "-c", "core.fsmonitor=false", "-C", str(root), *args], 

43 capture_output=True, text=True, encoding="utf-8", errors="replace", 

44 timeout=5, env=env, check=False) 

45 except (OSError, subprocess.TimeoutExpired): 

46 return None 

47 return result.stdout.strip() if result.returncode == 0 else None 

48 

49 

50def branch_slug(name): 

51 """Bound output and disambiguate names with the same normalized prefix.""" 

52 prefix = re.sub(r"[^a-z0-9-]+", "-", name.lower()).strip("-")[:24] or "branch" 

53 return prefix + "-" + hashlib.sha256(name.encode()).hexdigest()[:8] 

54 

55 

56def public_branch(root, public_origins): 

57 # Never publish a private local branch name or remote URL. Tracking refs are 

58 # local observations of this public origin, not authenticated provenance. 

59 branch = git(root, "symbolic-ref", "--quiet", "--short", "HEAD") 

60 origin = git(root, "config", "--get", "remote.origin.url") 

61 if origin is None or origin.lower() not in {url.lower() for url in public_origins}: 

62 return "local" if branch else "detached" 

63 if branch: 

64 if git(root, "show-ref", "--verify", "--quiet", f"refs/remotes/origin/{branch}") == "": 

65 return branch_slug(branch) 

66 return "local" 

67 refs = git(root, "for-each-ref", "--points-at=HEAD", "--format=%(refname)", 

68 "refs/remotes/origin/") 

69 names = [ref.removeprefix("refs/remotes/origin/") for ref in (refs or "").splitlines() 

70 if ref != "refs/remotes/origin/HEAD"] 

71 return branch_slug(names[0]) if len(names) == 1 else "detached" 

72 

73 

74def unknown(): 

75 return {"format_version": 1, "base_version": None, "distance": None, "commit": None, 

76 "branch": "unknown", "state": "unknown", "history": "unavailable"} 

77 

78 

79def source_identity(root, public_origins=()): 

80 """Return live identity or None; never inspect a parent or caller's repository.""" 

81 root = Path(root).resolve() 

82 if not (root / ".git").exists(): 

83 return None 

84 top = git(root, "rev-parse", "--show-toplevel") 

85 if top is None or Path(top).resolve() != root: 

86 return None 

87 status = git(root, "status", "--porcelain=v1", "--untracked-files=normal") 

88 if status is None: 

89 return None 

90 result = unknown() 

91 result.update(branch=public_branch(root, public_origins), state="dirty" if status else "clean") 

92 commit = git(root, "rev-parse", "--verify", "HEAD") 

93 if commit is None: 

94 result.update(history="empty", distance=0) 

95 return result 

96 result["commit"] = commit 

97 if git(root, "rev-parse", "--is-shallow-repository") == "true": 

98 result["history"] = "shallow" 

99 return result 

100 # Git --match accepts globs, not regular expressions. Filter tag names 

101 # before describe so a nearer prerelease cannot hide an older release. 

102 tags = git(root, "tag", "--list", "v*") 

103 releases = [tag for tag in (tags or "").splitlines() 

104 if re.fullmatch(rf"v{RELEASE}", tag)] 

105 description = (git(root, "describe", "--tags", "--long", "--abbrev=12", 

106 *(f"--match={tag}" for tag in releases)) if releases else None) 

107 match = re.fullmatch(rf"v({RELEASE})-(\d+)-g[0-9a-f]+", description or "") 

108 if match: 

109 result.update(base_version=match[1], distance=int(match[5]), history="tagged") 

110 else: 

111 count = git(root, "rev-list", "--count", "HEAD") 

112 result.update(history="untagged", distance=int(count) if count else None) 

113 return result 

114 

115 

116def display(identity): 

117 """SemVer display; development values are identification, not release ordering.""" 

118 base = identity["base_version"] or "0.0.0" 

119 history, state = identity["history"], identity["state"] 

120 if history == "tagged" and identity["distance"] == 0 and state == "clean": 

121 return base 

122 if history == "unavailable": 

123 return "0.0.0-dev.unknown+nogit.unknown" 

124 distance = identity["distance"] 

125 development = (str(distance) if history == "tagged" else 

126 f"untagged.{distance}" if history == "untagged" and distance is not None else 

127 "empty" if history == "empty" else "unknown") 

128 commit = "g" + identity["commit"][:12] if identity["commit"] else "empty" 

129 suffix = ".shallow" if history == "shallow" else "" 

130 return f"{base}-dev.{development}+branch.{identity['branch']}.{commit}.{state}{suffix}" 

131 

132 

133def read_provenance(path, distribution): 

134 """Read a validated snapshot bound to exactly this consumer distribution.""" 

135 try: 

136 value = json.loads(Path(path).read_text(encoding="utf-8")) 

137 identity = value["identity"] 

138 if (value.get("distribution") != distribution 

139 or value["format_version"] != 1 or identity["format_version"] != 1 

140 or not isinstance(value.get("package_version"), str) 

141 or not re.fullmatch(r"[A-Za-z0-9.+!-]{1,100}", value["package_version"]) 

142 or identity["history"] not in {"tagged", "untagged", "empty", "shallow", "unavailable"} 

143 or identity["state"] not in {"clean", "dirty", "unknown"} 

144 or not re.fullmatch(r"[a-z0-9-]{1,40}", identity["branch"]) 

145 or (identity["base_version"] is not None 

146 and not re.fullmatch(RELEASE, identity["base_version"])) 

147 or (identity["commit"] is not None 

148 and not re.fullmatch(r"(?:[0-9a-f]{40}|[0-9a-f]{64})", identity["commit"])) 

149 or (identity["distance"] is not None 

150 and (type(identity["distance"]) is not int or identity["distance"] < 0))): 

151 return None 

152 if identity["history"] == "tagged" and any( 

153 identity[key] is None for key in ("base_version", "distance", "commit")): 

154 return None 

155 return value 

156 except (OSError, ValueError, KeyError, TypeError): 

157 return None 

158 

159 

160def build_provenance(root, package_version, consumer): 

161 """Capture identity at build time, preserving a matching sdist snapshot.""" 

162 root = Path(root).resolve() 

163 if not consumer.package_dir.is_relative_to(root): 

164 raise ValueError("Consumer package directory must be inside the build root") 

165 identity = source_identity(root, consumer.public_origins) 

166 if identity is None and (root / ".git").exists(): 

167 identity = unknown() 

168 if identity is None: 

169 saved = read_provenance(consumer.package_dir / PROVENANCE, consumer.distribution) 

170 identity = saved["identity"] if saved else unknown() 

171 return {"format_version": 1, "distribution": consumer.distribution, 

172 "package_version": package_version, "identity": identity} 

173 

174 

175def record_build(root, package_version, consumer): 

176 """Write a build snapshot and return its root-relative artifact path. 

177 

178 Add the returned path to your build backend's artifacts. Ignore this file in 

179 Git so a previous build does not itself mark the checkout dirty. 

180 """ 

181 snapshot = build_provenance(root, package_version, consumer) 

182 path = consumer.package_dir / PROVENANCE 

183 path.write_text(json.dumps(snapshot, sort_keys=True, indent=2) + "\n", encoding="utf-8") 

184 return path.relative_to(Path(root).resolve()).as_posix() 

185 

186 

187def current_version(consumer): 

188 """Return (display identity, installed PEP 440 version, identity source). 

189 

190 A wheel uses its recorded snapshot even when the caller runs inside an 

191 unrelated checkout. An editable src layout probes its own Git root each call. 

192 Missing Git in a checkout is explicit, not masked by a stale snapshot. 

193 """ 

194 package_dir = consumer.package_dir 

195 saved = read_provenance(package_dir / PROVENANCE, consumer.distribution) 

196 try: 

197 package_version = metadata.version(consumer.distribution) 

198 except metadata.PackageNotFoundError: 

199 package_version = saved["package_version"] if saved else "unavailable" 

200 root = package_dir.parent.parent 

201 if package_dir.parent.name == "src" and (root / ".git").exists(): 

202 identity = source_identity(root, consumer.public_origins) 

203 return display(identity or unknown()), package_version, ( 

204 "checkout" if identity else "checkout-unavailable") 

205 if saved: 

206 return display(saved["identity"]), package_version, "recorded-build" 

207 return display(unknown()), package_version, "unavailable"