Passed
Push — dev ( 9d64c8...509a39 )
by Konstantinos
05:06 queued 03:44
created

parse_package_version.main()   B

Complexity

Conditions 6

Size

Total Lines 29
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 21
nop 0
dl 0
loc 29
rs 8.4426
c 0
b 0
f 0
1
import os
2
import re
3
import sys
4
5
my_dir = os.path.dirname(os.path.realpath(__file__))
6
7
setup_cfg_filename = 'setup.cfg'
8
SETUP_CFG = os.path.join(my_dir, '../', setup_cfg_filename)
9
10
11
def main():
12
    """Get the package version string provided that the developer has setup indication how to find it."""
13
    # Automatically compute package vesion from the [semantic_release] section in setup.cfg
14
    with open(SETUP_CFG, 'r') as f:
15
        regex = r"\[semantic_release\][\w\s=/\.:\d]+version_variable[\ \t]*=[\ \t]*([\w\.]+(?:/[\w\.]+)*):(\w+)"
16
        m = re.search(regex, f.read(), re.MULTILINE)
17
        if m:
18
            file_with_version_string = os.path.join(my_dir, '../', m.group(1))
19
            variable_holding_version_value = m.group(2)
20
        else:
21
            raise RuntimeError(
22
                f"Expected to find the '[semantic_release]' section, in the '{SETUP_CFG}' file, with key 'version_variable'."
23
                f"\nExample (it does not have to be a .py file) to indicate that the version is stored in the '__version__' string:\n[semantic_release]\nversion_variable = src/package_name/__init__.py:__version__")
24
25
    if not os.path.isfile(file_with_version_string):
26
        raise FileNotFoundError(
27
            f"Path '{file_with_version_string} does not appear to be valid. Please go to the '{SETUP_CFG}' file, at the [semantic_release] section and set the 'version_variable' key with a valid path (to look for the version string)")
28
29
    reg_string = r'\s*=\s*[\'\"]([^\'\"]*)[\'\"]'
30
31
    with open(file_with_version_string, 'r') as f:
32
        content = f.read()
33
        reg = f'^{variable_holding_version_value}' + reg_string
34
        m = re.search(reg, content, re.MULTILINE)
35
        if m:
36
            _version = m.group(1)
37
            return _version
38
        else:
39
            raise AttributeError(f"Could not find a match for regex {reg} when applied to:\n{content}")
40
41
42
if __name__ == '__main__':
43
    try:
44
        version_string = main()
45
        print(version_string)
46
    except (RuntimeError, FileNotFoundError, AttributeError) as e:
47
        print(e)
48
        sys.exit(1)
49