Debian Codegraph @

tasks/deps/_inspect/_req_file.py

raw symbols SCIP
1 # -*- coding: ascii -*-
2 #
3 # Copyright 2018 - 2025
4 # Andr\xe9 Malo or his licensors, as applicable
5 #
6 # Licensed under the Apache License, Version 2.0 (the "License");
7 # you may not use this file except in compliance with the License.
8 # You may obtain a copy of the License at
9 #
10 # http://www.apache.org/licenses/LICENSE-2.0
11 #
12 # Unless required by applicable law or agreed to in writing, software
13 # distributed under the License is distributed on an "AS IS" BASIS,
14 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 # See the License for the specific language governing permissions and
16 # limitations under the License.
17 """
18 Requirement file container
19 ~~~~~~~~~~~~~~~~~~~~~~~~~~
20
21 """
22
23 import logging as _logging
24 import os as _os
25 import re as _re
26
27 from .. import _parse
28
29 logger = _logging.getLogger("deps.inspect.req_file")
30
31 REQUIREMENT = "requirement"
32 CONSTRAINT = "constraint"
33 EDITABLE = "editable"
34 INDEX = "index"
35
36
37 def tokens(filenames, base=None):
38 """
39 Walk over requirement tokens from a list of req files
40
41 Parameters:
42 filenames (iterable):
43 List of filenames to parse
44
45 base (str):
46 Base path. If omitted or ``None``, the CWD is used.
47
48 Returns:
49 iterable: List of token objects found
50 """
51 base = _os.path.normpath(_os.path.abspath(base or _os.getcwd()))
52 req_match = _re.compile(r"^(?:-r|--requirement)\s+(\S.*)").match
53 con_match = _re.compile(r"^(?:-c|--constraint)\s+(\S+)").match
54 edit_match = _re.compile(r"^(?:-e|--editable)\s+(\S.*)").match
55 idx_match = _re.compile(r"^(?:-i|--index)\s+(\S+)").match
56 name_match = _re.compile(r"^(?:%s)" % (_parse.regex.idre)).match
57
58 stack = FileIterator(base, filenames)
59 for line in stack:
60 content = line.content.strip()
61 if not content or content.startswith("#"):
62 continue
63
64 match = req_match(content)
65 if match:
66 req = match.group(1)
67 logger.debug("Found requirement reference %r", req)
68 if req.lower().startswith(("http://", "https://")):
69 logger.debug("Skipping remote requirement file")
70 continue
71
72 if req.lower().startswith("file://"):
73 req = req[len("file://") :]
74 req = _os.path.normpath(
75 _os.path.join(_os.path.dirname(line.file), req)
76 )
77 stack.push_file(req)
78 continue
79
80 match = con_match(content)
81 if match:
82 con = match.group(1)
83 if con.lower().startswith("file://"):
84 con = con[len("file://") :]
85 if not con.startswith(("http://", "https://")):
86 con = _os.path.normpath(
87 _os.path.join(_os.path.dirname(line.file), con)
88 )
89
90 logger.debug("Returning constraint file %r", con)
91 yield Token.constraint(con.rstrip(), line)
92 continue
93
94 match = edit_match(content)
95 if match:
96 value = match.group(1).rstrip()
97 logger.debug("Returning editable install %r", value)
98 yield Token.editable(value, line)
99 continue
100
101 match = idx_match(content)
102 if match:
103 value = match.group(1).rstrip()
104 logger.debug("Returning index %r", value)
105 yield Token.index(value, line)
106 continue
107
108 if name_match(content):
109 logger.debug("Returning requirement %r", content)
110 yield Token.requirement(_parse.requirement(content), line)
111 continue
112
113 logger.debug(
114 "Ignoring line %s in %s: %r", line.lineno, line.file, content
115 )
116
117
118 class Token(object):
119 """
120 Container for parsed requirement file tokens
121
122 Attributes:
123 value (any):
124 The token. Type depends on the token type. Typically a string, but
125 it's an requirement object for type == REQUIREMENT
126
127 line (Line):
128 The line object
129
130 type (str):
131 The token type
132 """
133
134 # pylint: disable = redefined-builtin
135 def __init__(self, value, line, type):
136 """
137 Initialization
138
139 Parameters:
140 value (any):
141 The token value
142
143 line (Line):
144 The line
145
146 type (str):
147 The token type:
148 - CONSTRAINT
149 - REQUIREMENT
150 - EDITABLE
151 - INDEX
152 """
153 self.value = value
154 self.line = line
155 self.type = type
156
157 def __repr__(self):
158 """
159 Create string representation
160
161 Returns:
162 str: String representation
163 """
164 return "%s(%r, line=%r, type=%s)" % (
165 self.__class__.__name__,
166 self.value,
167 self.line,
168 self.type.upper(),
169 )
170
171 @classmethod
172 def constraint(cls, value, line):
173 """
174 Create CONSTRAINT token
175
176 Parameters:
177 value (str):
178 The token value (constraint file reference)
179
180 line (Line):
181 The line
182
183 Returns:
184 Token: New Token instance
185 """
186 return cls(value, line, CONSTRAINT)
187
188 @classmethod
189 def requirement(cls, value, line):
190 """
191 Create REQUIREMENT token
192
193 Parameters:
194 value (parsed requirement):
195 The token value (the parsed requirement object)
196
197 line (Line):
198 The line
199
200 Returns:
201 Token: New Token instance
202 """
203 return cls(value, line, REQUIREMENT)
204
205 @classmethod
206 def editable(cls, value, line):
207 """
208 Create EDITABLE token
209
210 Parameters:
211 value (str):
212 The token value (editable reference, a folder or a URL)
213
214 line (Line):
215 The line
216
217 Returns:
218 Token: New Token instance
219 """
220 return cls(value, line, EDITABLE)
221
222 @classmethod
223 def index(cls, value, line):
224 """
225 Create INDEX token
226
227 Parameters:
228 value (str):
229 The token value (the index URL)
230
231 line (Line):
232 The line
233
234 Returns:
235 Token: New Token instance
236 """
237 return cls(value, line, INDEX)
238
239
240 class FileIterator(object):
241 """
242 Iterator over file lines
243
244 The file list can be extended while iterating over the lines. The file
245 added latest will be processed first.
246 """
247
248 def __init__(self, base, filenames=None):
249 """
250 Initialization
251
252 Parameters:
253 base (str):
254 The base path if relative file names are given
255
256 filenames (iterable):
257 The initial list of file names to iterate over
258 """
259 self._base = base
260 self._stack = []
261 self._seen = set()
262 if filenames is not None:
263 for filename in reversed(list(filenames)):
264 self.push_file(filename)
265
266 def push_file(self, filename):
267 """
268 Add a new file to iterate over
269
270 The file will not be added if it has been seen already.
271
272 Parameters:
273 filename (str):
274 The file name
275 """
276 filename = _os.path.normpath(_os.path.join(self._base, filename))
277 key = _os.path.relpath(filename, self._base)
278 if key in self._seen:
279 logger.debug("Skipping file %r (already seen)", key)
280 return
281 self._seen.add(key)
282
283 if not _os.path.isfile(filename):
284 logger.debug("Skipping non-file %r", key)
285 return
286
287 logger.debug("Adding %r to the stack", key)
288 lines = iter(File(filename))
289 self._stack.append(getattr(lines, "__next__", None) or lines.next)
290
291 def __iter__(self):
292 """
293 Iterate over lines
294
295 Returns:
296 iterable: All lines in LIFO (files) / FIFO (lines) order
297 """
298 while self._stack:
299 try:
300 yield self._stack[-1]()
301 except StopIteration:
302 self._stack.pop()
303
304
305 class File(object):
306 """
307 Requirement or constraints file
308
309 Attributes:
310 name (str):
311 File name
312 """
313
314 def __init__(self, name):
315 """
316 Initialization
317
318 Parameters:
319 name (str):
320 File name
321 """
322 self.name = name
323 with open(self.name, "rb") as fp:
324 self._lines = [
325 Line(name, lineno, line.decode("latin-1"))
326 for lineno, line in enumerate(fp, start=1)
327 ]
328
329 def __repr__(self):
330 """
331 Create string representation
332
333 Returns:
334 str: String representation
335 """
336 return "%s(%r)" % (
337 self.__class__.__name__,
338 self.name,
339 )
340
341 def __iter__(self):
342 """
343 Create line iterator
344
345 Returns:
346 iterable: Line iterator
347 """
348 return iter(self._lines)
349
350
351 class Line(object):
352 """
353 Line in a file
354
355 Attributes:
356 file (str):
357 File name
358
359 lineno (int):
360 Line number
361
362 content (str):
363 The line
364 """
365
366 def __init__(self, file, lineno, content):
367 """
368 Initialization
369
370 Parameters:
371 file (str):
372 File name
373
374 lineno (int):
375 Line number
376
377 content (str):
378 The line
379 """
380 self.file = file
381 self.lineno = lineno
382 self.content = content
383
384 def __repr__(self):
385 """
386 Create string representation
387
388 Returns:
389 str: String representation
390 """
391 return "%s(%r, %r, %r)" % (
392 self.__class__.__name__,
393 self.file,
394 self.lineno,
395 self.content,
396 )