Return a PEP 440 version derived from git state. If HEAD is at a tag, use it (stripping a leading 'v'). Otherwise return ``base_version + '+g '`` as a PEP 440 local version label. Falls back to base_version if git is unavailable or source_dir is not a git repository (e.g.
(source_dir, base_version)
| 108 | |
| 109 | |
| 110 | def compute_version(source_dir, base_version): |
| 111 | """Return a PEP 440 version derived from git state. |
| 112 | |
| 113 | If HEAD is at a tag, use it (stripping a leading 'v'). Otherwise return |
| 114 | ``base_version + '+g<shorthash>'`` as a PEP 440 local version label. |
| 115 | Falls back to base_version if git is unavailable or source_dir is not a |
| 116 | git repository (e.g. source tarball, missing .git, no git on PATH). |
| 117 | """ |
| 118 | if source_dir is None or not (source_dir / ".git").exists(): |
| 119 | return base_version |
| 120 | try: |
| 121 | tags = subprocess.run( |
| 122 | ["git", "-C", str(source_dir), "tag", "--points-at", "HEAD"], |
| 123 | capture_output=True, text=True, check=True, |
| 124 | ).stdout.strip().splitlines() |
| 125 | if tags: |
| 126 | tag = tags[0] |
| 127 | return tag[1:] if tag.startswith("v") else tag |
| 128 | short = subprocess.run( |
| 129 | ["git", "-C", str(source_dir), "rev-parse", "--short", "HEAD"], |
| 130 | capture_output=True, text=True, check=True, |
| 131 | ).stdout.strip() |
| 132 | if short: |
| 133 | return f"{base_version}+g{short}" |
| 134 | except (subprocess.CalledProcessError, FileNotFoundError): |
| 135 | pass |
| 136 | return base_version |
| 137 | |
| 138 | |
| 139 | def get_cache_version_override(build_dir): |