Debian Codegraph @

tasks/deps/_suggest/_dep_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 Shared code for dependency files
19 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
20
21 """
22
23 import logging as _logging
24 import re as _re
25
26 from ..._inv import shell as _shell
27 from .. import _parse
28 from . import _file_model
29
30 # pylint: disable = import-outside-toplevel
31
32 logger = _logging.getLogger("deps.suggest.dep_file")
33
34
35 class DepFile(object):
36 """
37 Dependency file container
38
39 Attributes:
40 name (str):
41 The filename
42 """
43
44 @property
45 def type(self):
46 """
47 The dep file type
48
49 :Type: str
50 """
51 return self._model.type
52
53 def __init__(self, filename, model):
54 """
55 Initialization
56
57 Parameters:
58 filename (str):
59 The filename
60 """
61 self.name = _shell.relative(filename)
62 self._fullname = _shell.native(filename)
63 self._model = model
64
65 @classmethod
66 def by_type(cls, type, filename): # pylint: disable = redefined-builtin
67 """
68 Return dep file instance by type and name
69
70 This factory returns the found initialized dep file ``None``.
71
72 Parameters:
73 type (str):
74 The file type
75
76 filename (str):
77 The file name
78
79 Returns:
80 DepFile: new instance
81 """
82 # pylint: disable = used-before-assignment
83 # pylint: disable = unnecessary-lambda-assignment
84 find_subs = lambda cls: set(cls.__subclasses__()).union(
85 s for c in cls.__subclasses__() for s in find_subs(c)
86 )
87 for sub in find_subs(_file_model.Model):
88 if sub.type == type:
89 return cls(filename, sub.by_name(filename))
90 return None
91
92 def __repr__(self):
93 """
94 Create debug representation
95
96 Returns:
97 str: The repr of the container
98 """
99 return "%s(%r, %r)" % (
100 self.__class__.__name__,
101 self.name,
102 self._model,
103 )
104
105 def __hash__(self):
106 """
107 Hash function based on the filename
108
109 Returns:
110 int: The hash
111 """
112 return hash(self.name)
113
114 def __eq__(self, other):
115 """
116 Equality - based on the name
117
118 Returns:
119 bool: Is it equal?
120 """
121 return isinstance(other, self.__class__) and other.name == self.name
122
123 def __ne__(self, other):
124 """
125 Non-Equality - based on the name
126
127 Returns:
128 bool: Is it not equal?
129 """
130 return not self == other
131
132 def __lt__(self, other):
133 """
134 Less-than comparision - based on the name
135
136 Returns:
137 bool: Is it smaller than other?
138 """
139 return isinstance(other, self.__class__) and self.name < other.name
140
141 def __contains__(self, name):
142 """
143 Check if package is referenced
144
145 Parameters:
146 name (str):
147 The package name to look for
148
149 Returns:
150 bool: Is it referenced?
151 """
152 for _ in self.find(name):
153 return True
154 return False
155
156 def __str__(self):
157 """
158 The reconstructed file
159
160 Returns:
161 str: The file as string
162 """
163 return "".join(map(str, self._model.parts))
164
165 def write(self):
166 """Write back the file"""
167 with open(self._fullname, "wb") as fp:
168 fp.write(str(self).encode(self._model.encoding))
169
170 def find(self, name, require_version=None):
171 """
172 Find requirements for `name`
173
174 Parameters:
175 name (str):
176 The name to look for
177
178 require_version (bool):
179 Require the version to be present? If omitted or ``None``, the
180 default is picked from the file model.
181
182 Returns:
183 iterable: Iterator over found specs
184 """
185 if require_version is None:
186 require_version = self._model.require_version
187
188 find = _re.compile(
189 _parse.regex.full_spec(name, require_version=require_version)
190 ).finditer
191
192 for part in self._model.parts:
193 if part.is_literal:
194 continue
195 for match in find(part.content):
196 yield match.group("spec")
197
198 def patch(self, patches):
199 """
200 Patch the file
201
202 Parameters:
203 patches (dict):
204 The changeset to apply
205
206 Returns:
207 ReqFile: A new container instance with possibly patched content
208 """
209 parts = []
210 for part in self._model.parts:
211 if not part.is_literal:
212 part = part.__class__(
213 part.raw, part.quote, self._patch(part.content, patches)
214 )
215 parts.append(part)
216 return self.__class__(self._fullname, self._model.__class__(parts))
217
218 @staticmethod
219 def _patch(string, patches):
220 """
221 Patch a single string - helper
222
223 Parameters:
224 string (str):
225 The string to patch
226
227 patches (dict):
228 Changeset (``{'changes': {name: {'new': 'spec'}, ...}}``)
229
230 Returns:
231 str: The patched string
232 """
233
234 def valid(req):
235 """Check if it's valid to patch"""
236 req = _parse.requirement(str(req))
237 if req.marker and not req.marker.evaluate():
238 return False
239 return True
240
241 result = string
242 for name, patchlist in patches["changes"].items():
243 for patch in patchlist:
244 result = _re.sub(
245 _parse.regex.full_spec(name, require_version=True),
246 lambda m, n=patch["new"]: (
247 "%s%s" % (m.group("space"), n)
248 if valid(m.group("spec"))
249 else m.group(0)
250 ),
251 result,
252 )
253
254 return result