Completed
Push — appveyor ( 280314...2c0e2c )
by Konstantinos
02:09
created

parse_package_version.main()   B

Complexity

Conditions 6

Size

Total Lines 31
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 21
nop 0
dl 0
loc 31
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. Reads the
13
    [semantic_release] section found in setup.cfg and then determines where is the actual version string
14
    """
15
    # Automatically compute package vesion from the [semantic_release] section in setup.cfg
16
    with open(SETUP_CFG, 'r') as f:
17
        regex = r"\[semantic_release\][\w\s=/\.:\d]+version_variable[\ \t]*=[\ \t]*([\w\.]+(?:/[\w\.]+)*):(\w+)"
18
        m = re.search(regex, f.read(), re.MULTILINE)
19
        if m:
20
            file_with_version_string = os.path.join(my_dir, '../', m.group(1))
21
            variable_holding_version_value = m.group(2)
22
        else:
23
            raise RuntimeError(
24
                f"Expected to find the '[semantic_release]' section, in the '{SETUP_CFG}' file, with key 'version_variable'."
25
                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__")
26
27
    if not os.path.isfile(file_with_version_string):
28
        raise FileNotFoundError(
29
            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)")
30
31
    reg_string = r'\s*=\s*[\'\"]([^\'\"]*)[\'\"]'
32
33
    with open(file_with_version_string, 'r') as f:
34
        content = f.read()
35
        reg = f'^{variable_holding_version_value}' + reg_string
36
        m = re.search(reg, content, re.MULTILINE)
37
        if m:
38
            _version = m.group(1)
39
            return _version
40
        else:
41
            raise AttributeError(f"Could not find a match for regex {reg} when applied to:\n{content}")
42
43
44
if __name__ == '__main__':
45
    try:
46
        version_string = main()
47
        print(version_string)
48
    except (RuntimeError, FileNotFoundError, AttributeError) as e:
49
        print(e)
50
        sys.exit(1)
51