1
|
|
|
#!/usr/bin/env python3 |
2
|
|
|
|
3
|
|
|
import os |
4
|
|
|
import re |
5
|
|
|
import sys |
6
|
|
|
|
7
|
|
|
my_dir = os.path.dirname(os.path.realpath(__file__)) |
8
|
|
|
|
9
|
|
|
SETUP_CFG_FILENAME = 'setup.cfg' |
10
|
|
|
SETUP_CFG = os.path.join(my_dir, '../', SETUP_CFG_FILENAME) |
11
|
|
|
|
12
|
|
|
|
13
|
|
|
def main(): |
14
|
|
|
"""Get the package version string provided that the developer has setup indication how to find it. Reads the |
15
|
|
|
[semantic_release] section found in setup.cfg and then determines where is the actual version string |
16
|
|
|
""" |
17
|
|
|
# Automatically compute package version from the [semantic_release] section in setup.cfg |
18
|
|
|
with open(SETUP_CFG, 'r') as _file: |
19
|
|
|
regex = r"\[semantic_release\][\w\s=/\.:\d]+version_variable[\ \t]*=[\ \t]*([\w\.]+(?:/[\w\.]+)*):(\w+)" |
20
|
|
|
match = re.search(regex, _file.read(), re.MULTILINE) |
21
|
|
|
if match: |
22
|
|
|
file_with_version_string = os.path.join(my_dir, '../', match.group(1)) |
23
|
|
|
variable_holding_version_value = match.group(2) |
24
|
|
|
else: |
25
|
|
|
raise RuntimeError( |
26
|
|
|
f"Expected to find the '[semantic_release]' section, in the '{SETUP_CFG}' file, with key " |
27
|
|
|
f"'version_variable'.\nFor example:\n[semantic_release]\nversion_variable = " |
28
|
|
|
f"src/package_name/__init__.py:__version__\n indicated that the version string should be looked up in " |
29
|
|
|
f"the src/package_name/__init__.py file registered under the __version__ 'name'") |
30
|
|
|
|
31
|
|
|
# (it does not have to be a.py file) |
32
|
|
|
# to indicate that the version is stored in the '__version__' |
33
|
|
|
if not os.path.isfile(file_with_version_string): |
34
|
|
|
raise FileNotFoundError( |
35
|
|
|
f"Path '{file_with_version_string} does not appear to be valid. Please go to the '{SETUP_CFG}' file, at the" |
36
|
|
|
f" [semantic_release] section and set the 'version_variable' key with a valid file path (to look for the " |
37
|
|
|
f"version string)") |
38
|
|
|
|
39
|
|
|
reg_string = r'\s*=\s*[\'\"]([^\'\"]*)[\'\"]' |
40
|
|
|
|
41
|
|
|
with open(file_with_version_string, 'r') as _file: |
42
|
|
|
content = _file.read() |
43
|
|
|
reg = f'^{variable_holding_version_value}' + reg_string |
44
|
|
|
match = re.search(reg, content, re.MULTILINE) |
45
|
|
|
if match: |
46
|
|
|
_version = match.group(1) |
47
|
|
|
return _version |
48
|
|
|
raise AttributeError(f"Could not find a match for regex {reg} when applied to:\n{content}") |
49
|
|
|
|
50
|
|
|
|
51
|
|
|
if __name__ == '__main__': |
52
|
|
|
try: |
53
|
|
|
version_string = main() |
54
|
|
|
print(version_string) |
55
|
|
|
except (RuntimeError, FileNotFoundError, AttributeError) as exception: |
56
|
|
|
print(exception) |
57
|
|
|
sys.exit(1) |
58
|
|
|
|