Gentoo Archives: gentoo-commits

From: Sam James <sam@g.o>
To: gentoo-commits@l.g.o
Subject: [gentoo-commits] proj/portage:master commit in: lib/portage/, lib/_emerge/
Date: Sun, 27 Mar 2022 23:07:19
Message-Id: 1648422408.18e5a8170c69aecd10f162918de571d85055ae81.sam@gentoo
1 commit: 18e5a8170c69aecd10f162918de571d85055ae81
2 Author: Kenneth Raplee <kenrap <AT> kennethraplee <DOT> com>
3 AuthorDate: Fri Mar 25 22:06:22 2022 +0000
4 Commit: Sam James <sam <AT> gentoo <DOT> org>
5 CommitDate: Sun Mar 27 23:06:48 2022 +0000
6 URL: https://gitweb.gentoo.org/proj/portage.git/commit/?id=18e5a817
7
8 Miscellaneous refactors and cleanups
9
10 Signed-off-by: Kenneth Raplee <kenrap <AT> kennethraplee.com>
11 Closes: https://github.com/gentoo/portage/pull/796
12 Signed-off-by: Sam James <sam <AT> gentoo.org>
13
14 lib/_emerge/main.py | 10 ++--
15 lib/portage/__init__.py | 14 ++---
16 lib/portage/_global_updates.py | 36 ++++++-------
17 lib/portage/checksum.py | 17 ++----
18 lib/portage/data.py | 34 +++++-------
19 lib/portage/dispatch_conf.py | 2 +-
20 lib/portage/getbinpkg.py | 115 ++++++++++++++++++-----------------------
21 lib/portage/glsa.py | 4 +-
22 8 files changed, 91 insertions(+), 141 deletions(-)
23
24 diff --git a/lib/_emerge/main.py b/lib/_emerge/main.py
25 index 01dc1b419..d22da1926 100644
26 --- a/lib/_emerge/main.py
27 +++ b/lib/_emerge/main.py
28 @@ -1235,12 +1235,10 @@ def emerge_main(args=None):
29 1: dev_null.fileno(),
30 2: dev_null.fileno(),
31 }
32 - if (
33 - portage.process.spawn_bash(
34 - "[[ $(< <(echo foo) ) == foo ]]", fd_pipes=fd_pipes
35 - )
36 - != 0
37 - ):
38 + exit_code = portage.process.spawn_bash(
39 + "[[ $(< <(echo foo) ) == foo ]]", fd_pipes=fd_pipes
40 + )
41 + if exit_code != 0:
42 writemsg_level(
43 "Failed to validate a sane '/dev'.\n"
44 "bash process substitution doesn't work; this may be an "
45
46 diff --git a/lib/portage/__init__.py b/lib/portage/__init__.py
47 index e6dff28ee..3f1f29f08 100644
48 --- a/lib/portage/__init__.py
49 +++ b/lib/portage/__init__.py
50 @@ -260,7 +260,6 @@ class _unicode_func_wrapper:
51 self._encoding = encoding
52
53 def _process_args(self, args, kwargs):
54 -
55 encoding = self._encoding
56 wrapped_args = [
57 _unicode_encode(x, encoding=encoding, errors="strict") for x in args
58 @@ -276,7 +275,6 @@ class _unicode_func_wrapper:
59 return (wrapped_args, wrapped_kwargs)
60
61 def __call__(self, *args, **kwargs):
62 -
63 encoding = self._encoding
64 wrapped_args, wrapped_kwargs = self._process_args(args, kwargs)
65
66 @@ -360,7 +358,6 @@ class _eintr_func_wrapper:
67 self._func = func
68
69 def __call__(self, *args, **kwargs):
70 -
71 while True:
72 try:
73 rval = self._func(*args, **kwargs)
74 @@ -383,10 +380,7 @@ _os_overrides = {
75 }
76
77
78 -try:
79 - _os_overrides[id(_os.mkfifo)] = _os.mkfifo
80 -except AttributeError:
81 - pass # Jython
82 +_os_overrides[id(_os.mkfifo)] = _os.mkfifo
83
84 if hasattr(_os, "statvfs"):
85 _os_overrides[id(_os.statvfs)] = _os.statvfs
86 @@ -498,9 +492,9 @@ if platform.system() in ("FreeBSD",):
87
88
89 def load_mod(name):
90 - modname = ".".join(name.split(".")[:-1])
91 - mod = __import__(modname)
92 components = name.split(".")
93 + modname = ".".join(components[:-1])
94 + mod = __import__(modname)
95 for comp in components[1:]:
96 mod = getattr(mod, comp)
97 return mod
98 @@ -573,7 +567,6 @@ def _eapi_is_deprecated(eapi):
99
100 def eapi_is_supported(eapi):
101 eapi = str(eapi).strip()
102 -
103 return eapi in _supported_eapis
104
105
106 @@ -794,7 +787,6 @@ _legacy_global_var_names = (
107
108
109 def _reset_legacy_globals():
110 -
111 global _legacy_globals_constructed
112 _legacy_globals_constructed = set()
113 for k in _legacy_global_var_names:
114
115 diff --git a/lib/portage/_global_updates.py b/lib/portage/_global_updates.py
116 index d7117d36b..59e0b263e 100644
117 --- a/lib/portage/_global_updates.py
118 +++ b/lib/portage/_global_updates.py
119 @@ -89,7 +89,7 @@ def _do_global_updates(trees, prev_mtimes, quiet=False, if_mtime_changed=True):
120 if not update_notice_printed:
121 update_notice_printed = True
122 writemsg_stdout("\n")
123 - writemsg_stdout(colorize("GOOD", _("Performing Global Updates\n")))
124 + writemsg_stdout(colorize("GOOD", "Performing Global Updates\n"))
125 writemsg_stdout(
126 _(
127 "(Could take a couple of minutes if you have a lot of binary packages.)\n"
128 @@ -236,38 +236,32 @@ def _do_global_updates(trees, prev_mtimes, quiet=False, if_mtime_changed=True):
129 # until after _all_ of the above updates have
130 # been processed because the mtimedb will
131 # automatically commit when killed by ctrl C.
132 - for mykey, mtime in timestamps.items():
133 - prev_mtimes[mykey] = mtime
134 + prev_mtimes.update(timestamps)
135
136 - do_upgrade_packagesmessage = False
137 # We gotta do the brute force updates for these now.
138 - if True:
139 + def onUpdate(_maxval, curval):
140 + if curval > 0:
141 + writemsg_stdout("#")
142
143 - def onUpdate(_maxval, curval):
144 - if curval > 0:
145 - writemsg_stdout("#")
146 + if quiet:
147 + onUpdate = None
148
149 - if quiet:
150 - onUpdate = None
151 - vardb.update_ents(repo_map, onUpdate=onUpdate)
152 - if bindb:
153 + vardb.update_ents(repo_map, onUpdate=onUpdate)
154
155 - def onUpdate(_maxval, curval):
156 - if curval > 0:
157 - writemsg_stdout("*")
158 + if bindb:
159
160 - if quiet:
161 - onUpdate = None
162 - bindb.update_ents(repo_map, onUpdate=onUpdate)
163 - else:
164 - do_upgrade_packagesmessage = 1
165 + def onUpdate(_maxval, curval):
166 + if curval > 0:
167 + writemsg_stdout("*")
168 +
169 + bindb.update_ents(repo_map, onUpdate=onUpdate)
170
171 # Update progress above is indicated by characters written to stdout so
172 # we print a couple new lines here to separate the progress output from
173 # what follows.
174 writemsg_stdout("\n\n")
175
176 - if do_upgrade_packagesmessage and bindb and bindb.cpv_all():
177 + if bindb and bindb.cpv_all():
178 writemsg_stdout(
179 _(
180 " ** Skipping packages. Run 'fixpackages' or set it in FEATURES to fix the tbz2's in the packages directory.\n"
181
182 diff --git a/lib/portage/checksum.py b/lib/portage/checksum.py
183 index 72d20525a..b4644da04 100644
184 --- a/lib/portage/checksum.py
185 +++ b/lib/portage/checksum.py
186 @@ -344,11 +344,8 @@ if os.path.exists(PRELINK_BINARY):
187
188
189 def is_prelinkable_elf(filename):
190 - f = _open_file(filename)
191 - try:
192 + with _open_file(filename) as f:
193 magic = f.read(17)
194 - finally:
195 - f.close()
196 return (
197 len(magic) == 17
198 and magic.startswith(b"\x7fELF")
199 @@ -444,11 +441,11 @@ def _apply_hash_filter(digests, hash_filter):
200 @type hash_filter: callable
201 """
202
203 - verifiable_hash_types = set(digests).intersection(hashfunc_keys)
204 - verifiable_hash_types.discard("size")
205 + verifiable_hash_types = frozenset(digests).intersection(hashfunc_keys)
206 modified = False
207 if len(verifiable_hash_types) > 1:
208 - for k in list(verifiable_hash_types):
209 + verifiable_hash_types.discard("size")
210 + for k in verifiable_hash_types:
211 if not hash_filter(k):
212 modified = True
213 verifiable_hash_types.remove(k)
214 @@ -456,11 +453,7 @@ def _apply_hash_filter(digests, hash_filter):
215 break
216
217 if modified:
218 - digests = {
219 - k: v
220 - for (k, v) in digests.items()
221 - if k == "size" or k in verifiable_hash_types
222 - }
223 + digests = {k: v for k, v in digests.items() if k in verifiable_hash_types}
224
225 return digests
226
227
228 diff --git a/lib/portage/data.py b/lib/portage/data.py
229 index b73fa8882..c783d76d0 100644
230 --- a/lib/portage/data.py
231 +++ b/lib/portage/data.py
232 @@ -8,6 +8,7 @@ import platform
233 import pwd
234
235 import portage
236 +from portage.localization import _
237
238 portage.proxy.lazyimport.lazyimport(
239 globals(),
240 @@ -16,14 +17,11 @@ portage.proxy.lazyimport.lazyimport(
241 "portage.util.path:first_existing",
242 "subprocess",
243 )
244 -from portage.localization import _
245
246 ostype = platform.system()
247 -userland = None
248 +userland = "GNU"
249 if ostype == "DragonFly" or ostype.endswith("BSD"):
250 userland = "BSD"
251 -else:
252 - userland = "GNU"
253
254 lchown = getattr(os, "lchown", None)
255
256 @@ -140,7 +138,6 @@ def _get_global(k):
257 return globals()[k]
258
259 if k == "secpass":
260 -
261 unprivileged = False
262 if hasattr(portage, "settings"):
263 unprivileged = "unprivileged" in portage.settings.features
264 @@ -254,11 +251,10 @@ def _get_global(k):
265 # Avoid instantiating portage.settings when the desired
266 # variable is set in os.environ.
267 elif k in ("_portage_grpname", "_portage_username"):
268 - v = None
269 + v = "portage"
270 + env_key = "PORTAGE_USERNAME"
271 if k == "_portage_grpname":
272 env_key = "PORTAGE_GRPNAME"
273 - else:
274 - env_key = "PORTAGE_USERNAME"
275
276 if env_key in os.environ:
277 v = os.environ[env_key]
278 @@ -290,9 +286,6 @@ def _get_global(k):
279 pass
280 else:
281 v = pwd_struct.pw_name
282 -
283 - if v is None:
284 - v = "portage"
285 else:
286 raise AssertionError("unknown name: %s" % k)
287
288 @@ -302,7 +295,6 @@ def _get_global(k):
289
290
291 class _GlobalProxy(portage.proxy.objectproxy.ObjectProxy):
292 -
293 __slots__ = ("_name",)
294
295 def __init__(self, name):
296 @@ -340,17 +332,15 @@ def _init(settings):
297 # from grp.getgrnam() with PyPy
298 native_string = platform.python_implementation() == "PyPy"
299
300 - v = settings.get("PORTAGE_GRPNAME", "portage")
301 - if native_string:
302 - v = portage._native_string(v)
303 - globals()["_portage_grpname"] = v
304 - _initialized_globals.add("_portage_grpname")
305 -
306 - v = settings.get("PORTAGE_USERNAME", "portage")
307 if native_string:
308 - v = portage._native_string(v)
309 - globals()["_portage_username"] = v
310 - _initialized_globals.add("_portage_username")
311 + grpname = settings.get("PORTAGE_GRPNAME", "portage")
312 + grpname = portage._native_string(grpname)
313 + globals()["_portage_grpname"] = grpname
314 + _initialized_globals.add("_portage_grpname")
315 + username = settings.get("PORTAGE_USERNAME", "portage")
316 + username = portage._native_string(username)
317 + globals()["_portage_username"] = username
318 + _initialized_globals.add("_portage_username")
319
320 if "secpass" not in _initialized_globals:
321 v = 0
322
323 diff --git a/lib/portage/dispatch_conf.py b/lib/portage/dispatch_conf.py
324 index d682a9ad0..6dbb1885e 100644
325 --- a/lib/portage/dispatch_conf.py
326 +++ b/lib/portage/dispatch_conf.py
327 @@ -40,7 +40,7 @@ def diffstatusoutput(cmd, file1, file2):
328 args = (portage._unicode_encode(x, errors="strict") for x in args)
329 proc = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
330 output = portage._unicode_decode(proc.communicate()[0])
331 - if output and output[-1] == "\n":
332 + if output and output.endswith("\n"):
333 # getstatusoutput strips one newline
334 output = output[:-1]
335 return (proc.wait(), output)
336
337 diff --git a/lib/portage/getbinpkg.py b/lib/portage/getbinpkg.py
338 index f357a91df..ea9ee1d0a 100644
339 --- a/lib/portage/getbinpkg.py
340 +++ b/lib/portage/getbinpkg.py
341 @@ -21,11 +21,11 @@ import tempfile
342 import base64
343 import warnings
344
345 -_all_errors = [NotImplementedError, ValueError, socket.error]
346 -
347 from html.parser import HTMLParser as html_parser_HTMLParser
348 from urllib.parse import unquote as urllib_parse_unquote
349
350 +_all_errors = [NotImplementedError, ValueError, socket.error]
351 +
352 try:
353 import ftplib
354 except ImportError as e:
355 @@ -47,7 +47,6 @@ _all_errors = tuple(_all_errors)
356
357
358 def make_metadata_dict(data):
359 -
360 warnings.warn(
361 "portage.getbinpkg.make_metadata_dict() is deprecated",
362 DeprecationWarning,
363 @@ -82,7 +81,6 @@ class ParseLinks(html_parser_HTMLParser):
364 page and provide suffix and prefix limitors"""
365
366 def __init__(self):
367 -
368 warnings.warn(
369 "portage.getbinpkg.ParseLinks is deprecated",
370 DeprecationWarning,
371 @@ -96,19 +94,15 @@ class ParseLinks(html_parser_HTMLParser):
372 return self.PL_anchors
373
374 def get_anchors_by_prefix(self, prefix):
375 - newlist = []
376 - for x in self.PL_anchors:
377 - if x.startswith(prefix):
378 - if x not in newlist:
379 - newlist.append(x[:])
380 + newlist = [
381 + x for x in self.PL_anchors if x.startswith(prefix) and x not in newlist
382 + ]
383 return newlist
384
385 def get_anchors_by_suffix(self, suffix):
386 - newlist = []
387 - for x in self.PL_anchors:
388 - if x.endswith(suffix):
389 - if x not in newlist:
390 - newlist.append(x[:])
391 + newlist = [
392 + x for x in self.PL_anchors if x.endswith(suffix) and x not in newlist
393 + ]
394 return newlist
395
396 def handle_endtag(self, tag):
397 @@ -140,16 +134,13 @@ def create_conn(baseurl, conn=None):
398 raise ValueError(
399 _("Provided URI does not " "contain protocol identifier. '%s'") % baseurl
400 )
401 - protocol, url_parts = parts
402 + protocol, url = parts
403 del parts
404
405 - url_parts = url_parts.split("/")
406 - host = url_parts[0]
407 - if len(url_parts) < 2:
408 - address = "/"
409 - else:
410 - address = "/" + "/".join(url_parts[1:])
411 - del url_parts
412 + url_split = url.split("/", 1)
413 + host = url_split[0]
414 + address = f"/{url_split[1]}"
415 + del url, url_split
416
417 userpass_host = host.split("@", 1)
418 if len(userpass_host) == 1:
419 @@ -160,13 +151,14 @@ def create_conn(baseurl, conn=None):
420 userpass = userpass_host[0].split(":")
421 del userpass_host
422
423 - if len(userpass) > 2:
424 + userpass_size = len(userpass)
425 + if userpass_size > 2:
426 raise ValueError(_("Unable to interpret username/password provided."))
427 - elif len(userpass) == 2:
428 - username = userpass[0]
429 +
430 + username = userpass[0]
431 + if userpass_size == 2:
432 password = userpass[1]
433 - elif len(userpass) == 1:
434 - username = userpass[0]
435 + elif userpass_size == 1:
436 password = None
437 del userpass
438
439 @@ -243,7 +235,6 @@ def make_ftp_request(conn, address, rest=None, dest=None):
440 )
441
442 try:
443 -
444 if dest:
445 fstart_pos = dest.tell()
446
447 @@ -268,10 +259,9 @@ def make_ftp_request(conn, address, rest=None, dest=None):
448 else:
449 break
450
451 + data_size = len(mydata)
452 if dest:
453 data_size = fstart_pos - dest.tell()
454 - else:
455 - data_size = len(mydata)
456
457 mysocket.close()
458 conn.voidresp()
459 @@ -296,7 +286,7 @@ def make_http_request(conn, address, _params={}, headers={}, dest=None):
460
461 rc = 0
462 response = None
463 - while (rc == 0) or (rc == 301) or (rc == 302):
464 + while rc in (0, 301, 302):
465 try:
466 if rc != 0:
467 conn = create_conn(address)[0]
468 @@ -309,9 +299,9 @@ def make_http_request(conn, address, _params={}, headers={}, dest=None):
469 rc = response.status
470
471 # 301 means that the page address is wrong.
472 - if (rc == 301) or (rc == 302):
473 - ignored_data = response.read()
474 - del ignored_data
475 + if rc in (301, 302):
476 + # This response reading is ignored on purpose.
477 + _ = response.read()
478 for x in str(response.msg).split("\n"):
479 parts = x.split(": ", 1)
480 if parts[0] == "Location":
481 @@ -326,7 +316,7 @@ def make_http_request(conn, address, _params={}, headers={}, dest=None):
482 address = parts[1]
483 break
484
485 - if (rc != 200) and (rc != 206):
486 + if rc not in (200, 206):
487 return (
488 None,
489 rc,
490 @@ -355,26 +345,28 @@ def match_in_array(array, prefix="", suffix="", match_both=1, allow_overlap=0):
491
492 for x in array:
493 add_p = 0
494 - if prefix and (len(x) >= len(prefix)) and (x[: len(prefix)] == prefix):
495 + x_size = len(x)
496 + prefix_size = len(prefix)
497 + if prefix and x_size >= prefix_size and x[:prefix_size] == prefix:
498 add_p = 1
499
500 if match_both:
501 if prefix and not add_p: # Require both, but don't have first one.
502 continue
503 - else:
504 - if add_p: # Only need one, and we have it.
505 - myarray.append(x[:])
506 - continue
507 + elif add_p: # Only need one, and we have it.
508 + myarray.append(x[:])
509 + continue
510
511 + suffix_size = len(suffix)
512 if not allow_overlap: # Not allow to overlap prefix and suffix
513 - if len(x) >= (len(prefix) + len(suffix)):
514 + if x_size >= (prefix_size + suffix_size):
515 pass
516 else:
517 continue # Too short to match.
518 else:
519 pass # Do whatever... We're overlapping.
520
521 - if suffix and (len(x) >= len(suffix)) and (x[-len(suffix) :] == suffix):
522 + if suffix and x_size >= suffix_size and x[-len(suffix) :] == suffix:
523 myarray.append(x) # It matches
524 else:
525 continue # Doesn't match.
526 @@ -393,9 +385,8 @@ def dir_get_list(baseurl, conn=None):
527 stacklevel=2,
528 )
529
530 - if not conn:
531 - keepconnection = 0
532 - else:
533 + keepconnection = 0
534 + if conn:
535 keepconnection = 1
536
537 conn, protocol, address, params, headers = create_conn(baseurl, conn)
538 @@ -419,7 +410,7 @@ def dir_get_list(baseurl, conn=None):
539 raise portage.exception.PortageException(
540 _("Unable to get listing: %s %s") % (rc, msg)
541 )
542 - elif protocol in ["ftp"]:
543 + elif protocol == "ftp":
544 if address[-1] == "/":
545 olddir = conn.pwd()
546 conn.cwd(address)
547 @@ -450,10 +441,9 @@ def file_get_metadata(baseurl, conn=None, chunk_size=3000):
548 stacklevel=2,
549 )
550
551 - if not conn:
552 + keepconnection = 1
553 + if conn:
554 keepconnection = 0
555 - else:
556 - keepconnection = 1
557
558 conn, protocol, address, params, headers = create_conn(baseurl, conn)
559
560 @@ -532,7 +522,7 @@ def file_get(
561 variables["URI"] = baseurl
562
563 if "FILE" not in variables:
564 - if filename is None:
565 + if not filename:
566 filename = os.path.basename(variables["URI"])
567 variables["FILE"] = filename
568
569 @@ -565,9 +555,8 @@ def file_get_lib(baseurl, dest, conn=None):
570 stacklevel=2,
571 )
572
573 - if not conn:
574 - keepconnection = 0
575 - else:
576 + keepconnection = 0
577 + if conn:
578 keepconnection = 1
579
580 conn, protocol, address, params, headers = create_conn(baseurl, conn)
581 @@ -608,22 +597,20 @@ def file_get_lib(baseurl, dest, conn=None):
582 def dir_get_metadata(
583 baseurl, conn=None, chunk_size=3000, verbose=1, usingcache=1, makepickle=None
584 ):
585 -
586 warnings.warn(
587 "portage.getbinpkg.dir_get_metadata() is deprecated",
588 DeprecationWarning,
589 stacklevel=2,
590 )
591
592 - if not conn:
593 + keepconnection = 1
594 + if conn:
595 keepconnection = 0
596 - else:
597 - keepconnection = 1
598
599 cache_path = "/var/cache/edb"
600 metadatafilename = os.path.join(cache_path, "remote_metadata.pickle")
601
602 - if makepickle is None:
603 + if not makepickle:
604 makepickle = "/var/cache/edb/metadata.idx.most_recent"
605
606 try:
607 @@ -896,7 +883,7 @@ class PackageIndex:
608 ):
609
610 self._pkg_slot_dict = None
611 - if allowed_pkg_keys is not None:
612 + if allowed_pkg_keys:
613 self._pkg_slot_dict = slot_dict_class(allowed_pkg_keys)
614
615 self._default_header_data = default_header_data
616 @@ -914,11 +901,9 @@ class PackageIndex:
617 self.modified = True
618
619 def _readpkgindex(self, pkgfile, pkg_entry=True):
620 -
621 + d = {}
622 allowed_keys = None
623 - if self._pkg_slot_dict is None or not pkg_entry:
624 - d = {}
625 - else:
626 + if self._pkg_slot_dict and pkg_entry:
627 d = self._pkg_slot_dict()
628 allowed_keys = d.allowed_keys
629
630 @@ -964,7 +949,7 @@ class PackageIndex:
631 if self._inherited_keys:
632 for k in self._inherited_keys:
633 v = self.header.get(k)
634 - if v is not None:
635 + if v:
636 d.setdefault(k, v)
637 self.packages.append(d)
638
639 @@ -982,7 +967,7 @@ class PackageIndex:
640 if self._inherited_keys:
641 for k in self._inherited_keys:
642 v = self.header.get(k)
643 - if v is not None and v == metadata.get(k):
644 + if v and v == metadata.get(k):
645 del metadata[k]
646 if self._default_pkg_data:
647 for k, v in self._default_pkg_data.items():
648
649 diff --git a/lib/portage/glsa.py b/lib/portage/glsa.py
650 index 1b68bc0e9..d61ad7e59 100644
651 --- a/lib/portage/glsa.py
652 +++ b/lib/portage/glsa.py
653 @@ -115,12 +115,10 @@ def get_glsa_list(myconfig):
654 @rtype: List of Strings
655 @return: a list of GLSA IDs in this repository
656 """
657 - rValue = []
658
659 + repository = os.path.join(myconfig["PORTDIR"], "metadata", "glsa")
660 if "GLSA_DIR" in myconfig:
661 repository = myconfig["GLSA_DIR"]
662 - else:
663 - repository = os.path.join(myconfig["PORTDIR"], "metadata", "glsa")
664
665 if not os.access(repository, os.R_OK):
666 return []