Parse the package dependencies listed in a requirements file but strips specific versioning information. Args: fname (str): path to requirements file with_version (bool, default=False): if True include version specs Returns: list[str]: list of requirements items
(fname='requirements.txt', with_version=True)
| 2 | |
| 3 | |
| 4 | def parse_requirements(fname='requirements.txt', with_version=True): |
| 5 | """Parse the package dependencies listed in a requirements file but strips |
| 6 | specific versioning information. |
| 7 | |
| 8 | Args: |
| 9 | fname (str): path to requirements file |
| 10 | with_version (bool, default=False): if True include version specs |
| 11 | |
| 12 | Returns: |
| 13 | list[str]: list of requirements items |
| 14 | |
| 15 | CommandLine: |
| 16 | python -c "import setup; print(setup.parse_requirements())" |
| 17 | """ |
| 18 | import re |
| 19 | import sys |
| 20 | from os.path import exists |
| 21 | require_fpath = fname |
| 22 | |
| 23 | def parse_line(line): |
| 24 | """Parse information from a line in a requirements text file.""" |
| 25 | if line.startswith('-r '): |
| 26 | # Allow specifying requirements in other files |
| 27 | target = line.split(' ')[1] |
| 28 | for info in parse_require_file(target): |
| 29 | yield info |
| 30 | else: |
| 31 | info = {'line': line} |
| 32 | if line.startswith('-e '): |
| 33 | info['package'] = line.split('#egg=')[1] |
| 34 | else: |
| 35 | # Remove versioning from the package |
| 36 | pat = '(' + '|'.join(['>=', '==', '>']) + ')' |
| 37 | parts = re.split(pat, line, maxsplit=1) |
| 38 | parts = [p.strip() for p in parts] |
| 39 | |
| 40 | info['package'] = parts[0] |
| 41 | if len(parts) > 1: |
| 42 | op, rest = parts[1:] |
| 43 | if ';' in rest: |
| 44 | # Handle platform specific dependencies |
| 45 | # http://setuptools.readthedocs.io/en/latest/setuptools.html#declaring-platform-specific-dependencies |
| 46 | version, platform_deps = map(str.strip, |
| 47 | rest.split(';')) |
| 48 | info['platform_deps'] = platform_deps |
| 49 | else: |
| 50 | version = rest # NOQA |
| 51 | info['version'] = (op, version) |
| 52 | yield info |
| 53 | |
| 54 | def parse_require_file(fpath): |
| 55 | with open(fpath, 'r') as f: |
| 56 | for line in f.readlines(): |
| 57 | line = line.strip() |
| 58 | if line and not line.startswith('#'): |
| 59 | for info in parse_line(line): |
| 60 | yield info |
| 61 |
no test coverage detected