Coverage for diagrams / code_diagrams / _timestamp.py: 100.00%

19 statements  

« prev     ^ index     » next       coverage.py v7.13.5, created at 2026-09-14 22:07 +0000

1"""Generation-time metadata shared by every code-diagram artifact.""" 

2 

3from __future__ import annotations 

4 

5import os 

6import re 

7from datetime import UTC, datetime 

8 

9_COMMIT_RE = re.compile(r"[0-9a-fA-F]{40}") 

10 

11 

12def generation_timestamp_utc() -> str: 

13 """Return one ISO-8601 UTC timestamp for a generator invocation. 

14 

15 ``SOURCE_DATE_EPOCH`` makes regeneration reproducible when supplied; 

16 otherwise the current UTC time records when the artifacts were produced. 

17 Timestamps intentionally use whole seconds and a trailing ``Z`` so they 

18 remain compact and unambiguous in HTML, PNGs, READMEs, and source markers. 

19 """ 

20 source_date_epoch = os.environ.get("SOURCE_DATE_EPOCH") 

21 if source_date_epoch is None: 

22 generated_at = datetime.now(UTC) 

23 else: 

24 try: 

25 generated_at = datetime.fromtimestamp(int(source_date_epoch), UTC) 

26 except (OSError, OverflowError, ValueError) as exc: 

27 raise ValueError( 

28 "SOURCE_DATE_EPOCH must be an integer Unix timestamp", 

29 ) from exc 

30 return generated_at.strftime("%Y-%m-%dT%H:%M:%SZ") 

31 

32 

33def generation_source_commit() -> str: 

34 """Return the explicit Git commit whose charted source is being rendered. 

35 

36 A generated artifact cannot embed the SHA of the same commit that contains 

37 it without becoming self-referential. Canonical generation therefore uses 

38 a source commit supplied by the caller and commits derived artifacts in a 

39 later commit. The generator separately verifies every target against this 

40 revision after stripping generated marker blocks. 

41 """ 

42 value = os.environ.get("GCO_DIAGRAM_SOURCE_COMMIT", "").strip() 

43 if not _COMMIT_RE.fullmatch(value): 

44 raise ValueError("GCO_DIAGRAM_SOURCE_COMMIT must be an exact 40-character Git commit SHA") 

45 return value.lower()