Debian Codegraph @

requirements/fragment.py

raw symbols SCIP
1 # encoding: utf-8
2
3 # This file is part of requirements-parser library.
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16 #
17 # SPDX-License-Identifier: Apache-2.0
18
19 import re
20 from typing import Dict, List, Optional, Tuple, cast
21
22 # Copied from pip
23 # https://github.com/pypa/pip/blob/281eb61b09d87765d7c2b92f6982b3fe76ccb0af/pip/index.py#L947
24 HASH_ALGORITHMS = set(['sha1', 'sha224', 'sha384', 'sha256', 'sha512', 'md5'])
25
26 extras_require_search = re.compile(r'(?P<name>.+)\[(?P<extras>[^\]]+)\]')
27
28
29 def parse_fragment(fragment_string: str) -> Dict[str, str]:
30 """Takes a fragment string nd returns a dict of the components"""
31 fragment_string = fragment_string.lstrip('#')
32
33 try:
34 return dict(cast(Tuple[str, str], tuple(key_value_string.split('='))) for key_value_string in
35 fragment_string.split('&'))
36 except ValueError:
37 raise ValueError(f'Invalid fragment string {fragment_string}')
38
39
40 def get_hash_info(d: Dict[str, str]) -> Tuple[Optional[str], Optional[str]]:
41 """Returns the first matching hashlib name and value from a dict"""
42 for key in d.keys():
43 if key.lower() in HASH_ALGORITHMS:
44 return key, d[key]
45
46 return None, None
47
48
49 def parse_extras_require(egg: Optional[str]) -> Tuple[Optional[str], List[str]]:
50 if egg is not None:
51 match = extras_require_search.search(egg)
52 if match is not None:
53 name = match.group('name')
54 extras = match.group('extras')
55 return name, [extra.strip() for extra in extras.split(',')]
56 return egg, []