Debian Codegraph @

requirements/requirement.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 from __future__ import unicode_literals
20
21 import re
22 from typing import Any, Dict, List, Match, Optional, Tuple, cast
23
24 from packaging.requirements import Requirement as Req
25
26 from .fragment import get_hash_info, parse_extras_require, parse_fragment
27 from .vcs import VCS, VCS_SCHEMES
28
29 URI_REGEX = re.compile(
30 r'^(?P<scheme>https?|file|ftps?)://(?P<path>[^#]+)'
31 r'(#(?P<fragment>\S+))?'
32 )
33
34 VCS_OPTIONAL_NAME_REGEX = r'(?:(?P<name>[\w\[\]_\-,]+)\s*@)?\s*'
35 VCS_SCHEMES_REGEX = r'|'.join([scheme.replace('+', r'\+') for scheme in VCS_SCHEMES])
36 VCS_REGEX = re.compile(
37 rf'^{VCS_OPTIONAL_NAME_REGEX}(?P<scheme>{VCS_SCHEMES_REGEX})://((?P<login>[^/@]+)@)?'
38 r'(?P<path>[^#@]+)(@(?P<revision>[^#]+))?(#(?P<fragment>\S+))?'
39 )
40
41 # This matches just about everything
42 LOCAL_REGEX = re.compile(r'^((?P<scheme>file)://)?(?P<path>[^#]+)#(?P<fragment>\S+)?')
43
44
45 class Requirement:
46 """
47 Represents a single requirement
48
49 Typically instances of this class are created with ``Requirement.parse``.
50 For local file requirements, there's no verification that the file
51 exists. This class attempts to be *dict-like*.
52
53 See: http://www.pip-installer.org/en/latest/logic.html
54
55 **Members**:
56
57 * ``line`` - the actual requirement line being parsed
58 * ``editable`` - a boolean whether this requirement is "editable"
59 * ``local_file`` - a boolean whether this requirement is a local file/path
60 * ``specifier`` - a boolean whether this requirement used a requirement
61 specifier (eg. "django>=1.5" or "requirements")
62 * ``vcs`` - a string specifying the version control system
63 * ``revision`` - a version control system specifier
64 * ``name`` - the name of the requirement
65 * ``uri`` - the URI if this requirement was specified by URI
66 * ``subdirectory`` - the subdirectory fragment of the URI
67 * ``path`` - the local path to the requirement
68 * ``hash_name`` - the type of hashing algorithm indicated in the line
69 * ``hash`` - the hash value indicated by the requirement line
70 * ``extras`` - a list of extras for this requirement
71 (eg. "mymodule[extra1, extra2]")
72 * ``specs`` - a list of specs for this requirement
73 (eg. "mymodule>1.5,<1.6" => [('>', '1.5'), ('<', '1.6')])
74 """
75
76 def __init__(self, line: str) -> None:
77 # Do not call this private method
78 self.line = line
79 self.editable = False
80 self.local_file = False
81 self.specifier = False
82 self.vcs = None
83 self.name = None
84 self.subdirectory = None
85 self.uri = None
86 self.path = None
87 self.revision = None
88 self.hash_name = None
89 self.hash = None
90 self.extras: List[str] = []
91 self.specs: List[Tuple[str, str]] = []
92
93 def __repr__(self) -> str:
94 return f'<Requirement: "{self.line}">'
95
96 def __getitem__(self, key: str) -> Any:
97 return getattr(self, key)
98
99 def __eq__(self, other: object) -> bool:
100 if isinstance(other, Requirement):
101 return all([
102 self.name == other.name,
103 set(self.specs) == set(other.specs),
104 self.editable == other.editable,
105 self.specifier == other.specifier,
106 self.revision == other.revision,
107 self.hash_name == other.hash_name,
108 self.hash == other.hash,
109 set(self.extras) == set(other.extras),
110 ])
111 return False
112
113 def __ne__(self, other: object) -> bool:
114 return not self == other
115
116 def keys(self) -> Any:
117 return self.__dict__.keys()
118
119 @classmethod
120 def parse_editable(cls, line: str) -> 'Requirement':
121 """
122 Parses a Requirement from an "editable" requirement which is either
123 a local project path or a VCS project URI.
124
125 See: pip/req.py:from_editable()
126
127 :param line: an "editable" requirement
128 :returns: a Requirement instance for the given line
129 :raises: ValueError on an invalid requirement
130 """
131
132 req = cls(f'-e {line}')
133 req.editable = True
134
135 if ' #' in line:
136 line = line[:line.find(' #')]
137
138 vcs_match: Optional[Match[str]] = VCS_REGEX.match(line)
139 local_match: Optional[Match[str]] = LOCAL_REGEX.match(line)
140
141 if vcs_match is not None:
142 groups: Dict[str, str] = vcs_match.groupdict()
143 if groups.get('login'):
144 req.uri = f'{groups["scheme"]}://{groups["login"]}@{groups["path"]}' # type: ignore
145 else:
146 req.uri = f'{groups["scheme"]}://{groups["path"]}' # type: ignore
147 req.revision = groups['revision'] # type: ignore
148 if groups['fragment']:
149 fragment = parse_fragment(groups['fragment'])
150 egg = cast(str, fragment.get('egg'))
151 req.name, req.extras = parse_extras_require(egg) # type: ignore
152 req.hash_name, req.hash = get_hash_info(fragment) # type: ignore
153 req.subdirectory = fragment.get('subdirectory') # type: ignore
154 if groups['name']:
155 req.name, req.extras = parse_extras_require(groups['name']) # type: ignore
156 for vcs in VCS:
157 if str(req.uri).startswith(vcs):
158 req.vcs = vcs # type: ignore
159 elif local_match is not None:
160 groups = local_match.groupdict()
161 req.local_file = True
162 if groups['fragment']:
163 fragment = parse_fragment(groups['fragment'])
164 egg = cast(str, fragment.get('egg'))
165 req.name, req.extras = parse_extras_require(egg) # type: ignore
166 req.hash_name, req.hash = get_hash_info(fragment) # type: ignore
167 req.subdirectory = fragment.get('subdirectory') # type: ignore
168 req.path = cast(str, groups['path']) # type: ignore
169 else:
170 req.local_file = True
171 req.path, _, req.name = line.rpartition('/') # type: ignore
172
173 return req
174
175 @classmethod
176 def parse_line(cls, line: str) -> 'Requirement':
177 """
178 Parses a Requirement from a non-editable requirement.
179
180 See: pip/req.py:from_line()
181
182 :param line: a "non-editable" requirement
183 :returns: a Requirement instance for the given line
184 :raises: ValueError on an invalid requirement
185 """
186
187 req = cls(line)
188
189 vcs_match: Optional[Match[str]] = VCS_REGEX.match(line)
190 uri_match: Optional[Match[str]] = URI_REGEX.match(line)
191 local_match: Optional[Match[str]] = LOCAL_REGEX.match(line)
192
193 if vcs_match is not None:
194 groups = vcs_match.groupdict()
195 if groups.get('login'):
196 req.uri = f'{groups["scheme"]}://{groups["login"]}@{groups["path"]}' # type: ignore
197 else:
198 req.uri = f'{groups["scheme"]}://{groups["path"]}' # type: ignore
199 req.revision = groups['revision'] # type: ignore
200 if groups['fragment']:
201 fragment = parse_fragment(groups['fragment'])
202 egg = fragment.get('egg')
203 req.name, req.extras = parse_extras_require(egg) # type: ignore
204 req.hash_name, req.hash = get_hash_info(fragment) # type: ignore
205 req.subdirectory = fragment.get('subdirectory') # type: ignore
206 for vcs in VCS:
207 if str(req.uri).startswith(vcs):
208 req.vcs = vcs # type: ignore
209 if groups['name']:
210 req.name, req.extras = parse_extras_require(groups['name']) # type: ignore
211 elif uri_match is not None:
212 groups = uri_match.groupdict()
213 req.uri = f'{groups["scheme"]}://{groups["path"]}' # type: ignore
214 if groups['fragment']:
215 fragment = parse_fragment(groups['fragment'])
216 egg = fragment.get('egg')
217 req.name, req.extras = parse_extras_require(egg) # type: ignore
218 req.hash_name, req.hash = get_hash_info(fragment) # type: ignore
219 req.subdirectory = fragment.get('subdirectory') # type: ignore
220 if groups['scheme'] == 'file':
221 req.local_file = True
222 elif '#egg=' in line:
223 # Assume a local file match
224 assert local_match is not None, 'This should match everything'
225 groups = local_match.groupdict()
226 req.local_file = True
227 if groups['fragment']:
228 fragment = parse_fragment(groups['fragment'])
229 egg = fragment.get('egg')
230 name, extras = parse_extras_require(egg)
231 req.name = fragment.get('egg') # type: ignore
232 req.hash_name, req.hash = get_hash_info(fragment) # type: ignore
233 req.subdirectory = fragment.get('subdirectory') # type: ignore
234 req.path = groups['path'] # type: ignore
235 else:
236 # This is a requirement specifier.
237 # Delegate to packaging.requirements and hope for the best
238 req.specifier = True
239 line_without_comment = re.sub('#.*', '', line)
240 pkg_req = Req(line_without_comment)
241 req.name = pkg_req.name # type: ignore
242 req.extras = [x.lower() for x in list(pkg_req.extras)]
243 # Convert packaging.specifiers.SpecifierSet into
244 # pkg_resources specs, i.e., a list of (op,version) tuples
245 specs = []
246 for specifier in pkg_req.specifier:
247 spec = re.split('([=<>~!]+)', str(specifier), maxsplit=1)
248 spec = list(filter(None, spec))
249 specs.append(tuple(spec))
250 req.specs = specs # type: ignore
251 return req
252
253 @classmethod
254 def parse(cls, line: str) -> 'Requirement':
255 """
256 Parses a Requirement from a line of a requirement file.
257
258 :param line: a line of a requirement file
259 :returns: a Requirement instance for the given line
260 :raises: ValueError on an invalid requirement
261 """
262
263 if line.startswith('-e') or line.startswith('--editable'):
264 # Editable installs are either a local project path
265 # or a VCS project URI
266 return cls.parse_editable(
267 re.sub(r'^(-e|--editable=?)\s*', '', line))
268
269 if ' --hash=' in line:
270 line = line[:line.find(' --hash=')]
271 if ' \\' in line:
272 line = line[:line.find(' \\')]
273
274 return cls.parse_line(line)