Skip to content

Commit 06343cf

Browse files
committed
Refactor _get_version in setup.py
1 parent f1956af commit 06343cf

File tree

1 file changed

+18
-7
lines changed

1 file changed

+18
-7
lines changed

setup.py

Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,14 @@
11
#!/usr/bin/env python
2+
from __future__ import annotations
23

34
import os
45
import re
56
import subprocess
67
import sys
78
import textwrap
89
import time
10+
from contextlib import suppress
11+
from itertools import starmap
912

1013
import setuptools
1114
from setuptools import _normalization
@@ -30,19 +33,27 @@
3033
package_data.setdefault('setuptools.command', []).extend(['*.xml'])
3134

3235

36+
_VERSION_FALLBACK = [
37+
("PKG-INFO", r"^Version: (\d+\.\d+\.\d+.*)$", "{match[1]}"), # sdist
38+
("NEWS.rst", r"^v(\d+\.\d+\.\d+)", "{match[1]}.dev+{timestamp}"), # latest version
39+
]
40+
41+
42+
def _extract_version(file: str, pattern: str, fmt: str) -> str | None:
43+
with suppress(FileNotFoundError), open(file, encoding="utf-8") as fp:
44+
if match := re.search(pattern, fp.read(), re.M):
45+
return fmt.format(match=match, timestamp=time.strftime("%Y%m%d"))
46+
return None
47+
48+
3349
def _get_version() -> str:
3450
cmd = ["git", "describe", "--abbrev", "--match", "v?[0-9]*", "--dirty"]
3551
try:
3652
version = subprocess.check_output(cmd, encoding="utf-8")
3753
return _normalization.best_effort_version(version, "{safe}.dev+{sanitized}")
3854
except subprocess.CalledProcessError: # e.g.: git not installed or history missing
39-
if os.path.exists("PKG-INFO"): # building wheel from sdist
40-
with open("PKG-INFO", encoding="utf-8") as fp:
41-
if match := re.search(r"^Version: (\d+\.\d+\.\d+.*)$", fp.read(), re.M):
42-
return match[1]
43-
with open("NEWS.rst", encoding="utf-8") as fp:
44-
match = re.search(r"v\d+\.\d+\.\d+", fp.read()) # latest version
45-
return f"{match[0] if match else '0.0.0'}.dev+{time.strftime('%Y%m%d')}"
55+
candidates = filter(None, starmap(_extract_version, _VERSION_FALLBACK))
56+
return next(candidates, f"0.0.0.dev+{time.strftime('%Y%m%d')}")
4657

4758

4859
def pypi_link(pkg_filename):

0 commit comments

Comments
 (0)