Debian Codegraph @

tasks/deps/_suggest/_latest_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 Model for req file containing latest versions of dependencies
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
29 # pylint: disable = import-outside-toplevel
30
31 logger = _logging.getLogger("deps.suggest.latest_file")
32
33
34 class LatestFile(object):
35 """
36 Dependency file container
37
38 Attributes:
39 name (str):
40 The filename
41 """
42
43 # pylint: disable = too-many-instance-attributes
44
45 def __init__(self, filename, pattern, prefix, suffix, latest, not_latest):
46 """
47 Initialization
48
49 Parameters:
50 filename (str):
51 The filename
52
53 pattern (str):
54 Pattern to find the place where to insert the latest deps
55
56 prefix (str):
57 Prefix line for the latest deps
58
59 suffix (str):
60 Suffix line for the latest deps
61
62 latest (dict):
63 normname -> update-info
64
65 not_latest (set):
66 Not in latest (possibly anymore)
67 """
68 # pylint: disable = too-many-positional-arguments
69
70 self.name = _shell.relative(filename)
71 self._fullname = _shell.native(filename)
72 self._pattern = pattern
73 self._prefix, self._suffix = prefix, suffix
74 self._add, self._remove = [], []
75 self._pre, self._post = None, None
76 self._latest, self._not_latest = latest, not_latest
77 error = self.load()
78 if error:
79 logger.debug("%s", error)
80
81 def __repr__(self):
82 """
83 Create debug representation
84
85 Returns:
86 str: The repr of the container
87 """
88 return "%s(%r, %r, %r, %r, %r, %r)" % (
89 self.__class__.__name__,
90 self.name,
91 self._pattern,
92 self._prefix,
93 self._suffix,
94 self._latest,
95 self._not_latest,
96 )
97
98 def __str__(self):
99 """
100 The reconstructed file
101
102 Returns:
103 str: The file as string
104 """
105 pre = "".join(self._pre) + "\n"
106 add = "".join(self._add)
107 prefix = (
108 self._prefix + "\n" if add and self._prefix is not None else ""
109 )
110 suffix = (
111 self._suffix + "\n" if add and self._suffix is not None else ""
112 )
113 return pre + prefix + add + suffix + self._post
114
115 def as_patch_info(self):
116 """
117 Create jsonable patch information
118
119 Returns:
120 dict: {"add": [], "remove": []} or None
121 """
122 if set(self._add) == set(self._remove):
123 return None
124 return dict(add=list(self._add), remove=list(self._remove))
125
126 def as_changed(self):
127 """
128 Create jsonable patch information
129
130 Returns:
131 dict: Name -> new version
132 """
133 patched = self.as_patch_info()
134 if not patched:
135 return {}
136
137 removed = {}
138 changed = {}
139 for line in patched["remove"]:
140 req = _parse.requirement(line)
141 ops = set(spec.operator for spec in req.specifier)
142 versions = [spec.version for spec in req.specifier]
143 if ops in ({"=="}, {"~="}):
144 removed[_parse.normalize(req.name)] = versions[0]
145
146 for line in patched["add"]:
147 req = _parse.requirement(line)
148 ops = set(spec.operator for spec in req.specifier)
149 versions = [spec.version for spec in req.specifier]
150 if ops in ({"=="}, {"~="}):
151 name = _parse.normalize(req.name)
152 if removed.get(name) != versions[0]:
153 changed[name] = versions[0]
154
155 return changed
156
157 def load(self):
158 """
159 (Re-)load the file
160
161 Returns:
162 str: Error message if any. ``None`` if it was successful.
163 """
164 try:
165 with open(self._fullname, "rb") as fp:
166 content = fp.read().decode("latin-1")
167 except IOError as e:
168 return "Could not read file %r: %s" % (self._fullname, e)
169
170 search = _re.compile("(%s)" % (self._pattern,), _re.M).search
171 found = search(content)
172 if not found:
173 return "Pattern %r not found in %r" % (self._pattern, self.name)
174
175 cut = ""
176 pre = content[: found.start(1)]
177 post = content[found.start(1) :]
178 while pre and not pre.endswith("\n"):
179 cut += pre[-1]
180 pre = pre[:-1]
181 self._pre = pre.splitlines(True)
182 self._post = "".join(reversed(cut)) + post
183
184 # Find lines to remove and lines to add
185 add = []
186 for item in sorted(self._latest.values(), key=lambda x: x["new"]):
187 add.append(item["new"].rstrip() + "\n")
188 self._add, self._remove = add, self._remove_previous()
189
190 return None
191
192 def _remove_previous(self):
193 """
194 Remove previous "latest" dependencies from pre
195
196 Returns:
197 list: The removed dependencies
198 """
199 # pylint: disable = too-many-branches
200
201 pre = self._pre
202 prefix, suffix = self._prefix or "", self._suffix
203 is_req = _re.compile(_parse.regex.full_spec()).match
204 remove = []
205
206 while pre:
207 # skip empty lines
208 if not pre[-1].strip():
209 pre.pop()
210 continue
211
212 # skip suffix
213 if suffix is not None and pre[-1].strip() == suffix.strip():
214 pre.pop()
215 continue
216
217 # if we hit the prefix, we're done.
218 if prefix and pre[-1].strip() == prefix.strip():
219 pre.pop()
220 break
221
222 # we hit otherwise a line, which does not look like a requirement
223 if not is_req(pre[-1]):
224 if not prefix:
225 break
226
227 # Scan upwards and look out for the prefix line, skip until
228 # then
229 idx = 0
230 for idx, line in enumerate(reversed(pre), start=1):
231 if line.strip() == prefix.strip():
232 break
233 else:
234 break
235 for _ in range(idx):
236 pre.pop()
237 break
238
239 # Finally we've hit something parsable
240 # stop if it's not in our list, except if there's a prefix to be
241 # found, then continue scanning
242 key = _parse.normalize(_parse.requirement(pre[-1]).name)
243 if key not in self._latest and key not in self._not_latest:
244 for line in reversed(pre):
245 if line.strip() == prefix.strip():
246 break
247 else:
248 break
249
250 remove.append(pre.pop())
251
252 # skip any empty lines
253 while pre and not pre[-1].strip():
254 pre.pop()
255 return remove
256
257 def write(self):
258 """Write back the file"""
259 # Try to assemble the file before opening it for writing
260 result = str(self).encode("latin-1")
261
262 with open(self._fullname, "wb") as fp:
263 fp.write(result)