Gentoo Archives: gentoo-portage-dev

From: "Michał Górny" <mgorny@g.o>
To: gentoo-portage-dev@l.g.o
Cc: "Michał Górny" <mgorny@g.o>
Subject: [gentoo-portage-dev] [PATCH] Clean up more py2 conditional code
Date: Thu, 16 Jul 2020 19:05:53
Message-Id: 20200716190525.343970-1-mgorny@gentoo.org
1 Closes: https://github.com/gentoo/portage/pull/575
2 Signed-off-by: Michał Górny <mgorny@g.o>
3 ---
4 lib/portage/cache/anydbm.py | 4 +-
5 lib/portage/cache/mappings.py | 45 +++++-----------
6 lib/portage/cache/sql_template.py | 5 +-
7 lib/portage/cache/template.py | 12 ++---
8 lib/portage/elog/messages.py | 3 +-
9 lib/portage/output.py | 3 +-
10 lib/portage/package/ebuild/config.py | 11 +---
11 .../futures/asyncio/test_subprocess_exec.py | 4 --
12 lib/portage/tests/util/futures/test_retry.py | 2 -
13 lib/portage/tests/util/test_socks5.py | 16 ++----
14 lib/portage/util/__init__.py | 53 +++++--------------
15 lib/portage/util/_dyn_libs/NeededEntry.py | 10 ----
16 lib/portage/util/digraph.py | 3 --
17 lib/portage/util/listdir.py | 2 -
18 lib/portage/util/whirlpool.py | 25 ++++-----
19 lib/portage/xpak.py | 2 -
20 16 files changed, 52 insertions(+), 148 deletions(-)
21
22 diff --git a/lib/portage/cache/anydbm.py b/lib/portage/cache/anydbm.py
23 index 88d85b0da..121a4eaf2 100644
24 --- a/lib/portage/cache/anydbm.py
25 +++ b/lib/portage/cache/anydbm.py
26 @@ -112,5 +112,5 @@ class database(fs_template.FsBased):
27 self.__db.sync()
28 self.__db.close()
29
30 - if sys.hexversion >= 0x3000000:
31 - items = iteritems
32 + # TODO: do we need iteritems()?
33 + items = iteritems
34 diff --git a/lib/portage/cache/mappings.py b/lib/portage/cache/mappings.py
35 index 0432fdf60..0adecde4a 100644
36 --- a/lib/portage/cache/mappings.py
37 +++ b/lib/portage/cache/mappings.py
38 @@ -25,9 +25,6 @@ class Mapping(object):
39 def __iter__(self):
40 return iter(self.keys())
41
42 - def keys(self):
43 - return list(self.__iter__())
44 -
45 def __contains__(self, key):
46 try:
47 value = self[key]
48 @@ -46,12 +43,6 @@ class Mapping(object):
49 for _, v in self.items():
50 yield v
51
52 - def values(self):
53 - return [v for _, v in self.iteritems()]
54 -
55 - def items(self):
56 - return list(self.iteritems())
57 -
58 def get(self, key, default=None):
59 try:
60 return self[key]
61 @@ -64,10 +55,10 @@ class Mapping(object):
62 def __len__(self):
63 return len(list(self))
64
65 - if sys.hexversion >= 0x3000000:
66 - items = iteritems
67 - keys = __iter__
68 - values = itervalues
69 + # TODO: do we need to keep iter*?
70 + items = iteritems
71 + keys = __iter__
72 + values = itervalues
73
74 class MutableMapping(Mapping):
75 """
76 @@ -184,8 +175,8 @@ class UserDict(MutableMapping):
77 def clear(self):
78 self.data.clear()
79
80 - if sys.hexversion >= 0x3000000:
81 - keys = __iter__
82 + keys = __iter__
83 +
84
85 class ProtectedDict(MutableMapping):
86 """
87 @@ -234,8 +225,8 @@ class ProtectedDict(MutableMapping):
88 def __contains__(self, key):
89 return key in self.new or (key not in self.blacklist and key in self.orig)
90
91 - if sys.hexversion >= 0x3000000:
92 - keys = __iter__
93 + keys = __iter__
94 +
95
96 class LazyLoad(Mapping):
97 """
98 @@ -271,8 +262,8 @@ class LazyLoad(Mapping):
99 self.pull = None
100 return key in self.d
101
102 - if sys.hexversion >= 0x3000000:
103 - keys = __iter__
104 + keys = __iter__
105 +
106
107 _slot_dict_classes = weakref.WeakValueDictionary()
108
109 @@ -328,9 +319,6 @@ def slot_dict_class(keys, prefix="_val_"):
110 l += 1
111 return l
112
113 - def keys(self):
114 - return list(self)
115 -
116 def iteritems(self):
117 prefix = self._prefix
118 for k in self.allowed_keys:
119 @@ -339,16 +327,10 @@ def slot_dict_class(keys, prefix="_val_"):
120 except AttributeError:
121 pass
122
123 - def items(self):
124 - return list(self.iteritems())
125 -
126 def itervalues(self):
127 for k, v in self.iteritems():
128 yield v
129
130 - def values(self):
131 - return list(self.itervalues())
132 -
133 def __delitem__(self, k):
134 try:
135 delattr(self, self._prefix + k)
136 @@ -447,10 +429,9 @@ def slot_dict_class(keys, prefix="_val_"):
137 def __repr__(self):
138 return repr(dict(self.iteritems()))
139
140 - if sys.hexversion >= 0x3000000:
141 - items = iteritems
142 - keys = __iter__
143 - values = itervalues
144 + items = iteritems
145 + keys = __iter__
146 + values = itervalues
147
148 v = SlotDict
149 _slot_dict_classes[v.allowed_keys] = v
150 diff --git a/lib/portage/cache/sql_template.py b/lib/portage/cache/sql_template.py
151 index d023b1b5d..ba75a529f 100644
152 --- a/lib/portage/cache/sql_template.py
153 +++ b/lib/portage/cache/sql_template.py
154 @@ -296,6 +296,5 @@ class SQLDatabase(template.database):
155
156 return [ row[0] for row in self.con.fetchall() ]
157
158 - if sys.hexversion >= 0x3000000:
159 - items = iteritems
160 - keys = __iter__
161 + items = iteritems
162 + keys = __iter__
163 diff --git a/lib/portage/cache/template.py b/lib/portage/cache/template.py
164 index d7fff3e32..e2dc3f088 100644
165 --- a/lib/portage/cache/template.py
166 +++ b/lib/portage/cache/template.py
167 @@ -171,9 +171,6 @@ class database(object):
168 def has_key(self, cpv):
169 return cpv in self
170
171 - def keys(self):
172 - return list(self)
173 -
174 def iterkeys(self):
175 return iter(self)
176
177 @@ -181,9 +178,6 @@ class database(object):
178 for x in self:
179 yield (x, self[x])
180
181 - def items(self):
182 - return list(self.iteritems())
183 -
184 def sync(self, rate=0):
185 self.sync_rate = rate
186 if(rate == 0):
187 @@ -290,9 +284,9 @@ class database(object):
188 if cont:
189 yield cpv
190
191 - if sys.hexversion >= 0x3000000:
192 - keys = __iter__
193 - items = iteritems
194 + keys = __iter__
195 + items = iteritems
196 +
197
198 _keysorter = operator.itemgetter(0)
199
200 diff --git a/lib/portage/elog/messages.py b/lib/portage/elog/messages.py
201 index a4897d8d8..4917d44dd 100644
202 --- a/lib/portage/elog/messages.py
203 +++ b/lib/portage/elog/messages.py
204 @@ -122,8 +122,7 @@ def _elog_base(level, msg, phase="other", key=None, color=None, out=None):
205 if out in (sys.stdout, sys.stderr):
206 formatted_msg = _unicode_encode(formatted_msg,
207 encoding=_encodings['stdio'], errors='backslashreplace')
208 - if sys.hexversion >= 0x3000000:
209 - out = out.buffer
210 + out = out.buffer
211
212 out.write(formatted_msg)
213
214 diff --git a/lib/portage/output.py b/lib/portage/output.py
215 index 26880adca..dbfb81714 100644
216 --- a/lib/portage/output.py
217 +++ b/lib/portage/output.py
218 @@ -396,8 +396,7 @@ class ConsoleStyleFile(object):
219 if f in (sys.stdout, sys.stderr):
220 s = _unicode_encode(s,
221 encoding=_encodings['stdio'], errors='backslashreplace')
222 - if sys.hexversion >= 0x3000000:
223 - f = f.buffer
224 + f = f.buffer
225 f.write(s)
226
227 def writelines(self, lines):
228 diff --git a/lib/portage/package/ebuild/config.py b/lib/portage/package/ebuild/config.py
229 index 4ae53f5b2..2e62ef5ce 100644
230 --- a/lib/portage/package/ebuild/config.py
231 +++ b/lib/portage/package/ebuild/config.py
232 @@ -2708,9 +2708,6 @@ class config(object):
233 self[k] = x
234 return x
235
236 - def keys(self):
237 - return list(self)
238 -
239 def __iter__(self):
240 keys = set()
241 keys.update(self._constant_keys)
242 @@ -2725,9 +2722,6 @@ class config(object):
243 for k in self:
244 yield (k, self._getitem(k))
245
246 - def items(self):
247 - return list(self.iteritems())
248 -
249 def __setitem__(self,mykey,myvalue):
250 "set a value; will be thrown away at reset() time"
251 if not isinstance(myvalue, str):
252 @@ -2918,6 +2912,5 @@ class config(object):
253
254 return self._selinux_enabled
255
256 - if sys.hexversion >= 0x3000000:
257 - keys = __iter__
258 - items = iteritems
259 + keys = __iter__
260 + items = iteritems
261 diff --git a/lib/portage/tests/util/futures/asyncio/test_subprocess_exec.py b/lib/portage/tests/util/futures/asyncio/test_subprocess_exec.py
262 index d7e94d132..6ad987316 100644
263 --- a/lib/portage/tests/util/futures/asyncio/test_subprocess_exec.py
264 +++ b/lib/portage/tests/util/futures/asyncio/test_subprocess_exec.py
265 @@ -132,8 +132,6 @@ class SubprocessExecTestCase(TestCase):
266 requires an AbstractEventLoop.connect_read_pipe implementation
267 (and a ReadTransport implementation for it to return).
268 """
269 - if sys.version_info.major < 3:
270 - self.skipTest('ReadTransport not implemented for python2')
271
272 args_tuple = (b'hello', b'world')
273 echo_binary = find_binary("echo")
274 @@ -162,8 +160,6 @@ class SubprocessExecTestCase(TestCase):
275 requires an AbstractEventLoop.connect_write_pipe implementation
276 (and a WriteTransport implementation for it to return).
277 """
278 - if sys.version_info.major < 3:
279 - self.skipTest('WriteTransport not implemented for python2')
280
281 stdin_data = b'hello world'
282 cat_binary = find_binary("cat")
283 diff --git a/lib/portage/tests/util/futures/test_retry.py b/lib/portage/tests/util/futures/test_retry.py
284 index 4530bba83..94ede2e17 100644
285 --- a/lib/portage/tests/util/futures/test_retry.py
286 +++ b/lib/portage/tests/util/futures/test_retry.py
287 @@ -229,6 +229,4 @@ class RetryForkExecutorTestCase(RetryTestCase):
288
289 class RetryThreadExecutorTestCase(RetryForkExecutorTestCase):
290 def _setUpExecutor(self):
291 - if sys.version_info.major < 3:
292 - self.skipTest('ThreadPoolExecutor not supported for python2')
293 self._executor = ThreadPoolExecutor(max_workers=1)
294 diff --git a/lib/portage/tests/util/test_socks5.py b/lib/portage/tests/util/test_socks5.py
295 index 5db85b0a6..f7b893996 100644
296 --- a/lib/portage/tests/util/test_socks5.py
297 +++ b/lib/portage/tests/util/test_socks5.py
298 @@ -193,19 +193,13 @@ class Socks5ServerTestCase(TestCase):
299 'PORTAGE_BIN_PATH': PORTAGE_BIN_PATH,
300 }
301
302 - try:
303 - proxy = socks5.get_socks5_proxy(settings)
304 - except NotImplementedError:
305 - # bug 658172 for python2.7
306 - self.skipTest('get_socks5_proxy not implemented for {} {}.{}'.format(
307 - platform.python_implementation(), *sys.version_info[:2]))
308 - else:
309 - loop.run_until_complete(socks5.proxy.ready())
310 + proxy = socks5.get_socks5_proxy(settings)
311 + loop.run_until_complete(socks5.proxy.ready())
312
313 - result = loop.run_until_complete(loop.run_in_executor(None,
314 - self._fetch_via_proxy, proxy, host, server.server_port, path))
315 + result = loop.run_until_complete(loop.run_in_executor(None,
316 + self._fetch_via_proxy, proxy, host, server.server_port, path))
317
318 - self.assertEqual(result, content)
319 + self.assertEqual(result, content)
320 finally:
321 socks5.proxy.stop()
322 shutil.rmtree(tempdir)
323 diff --git a/lib/portage/util/__init__.py b/lib/portage/util/__init__.py
324 index 0ff34da30..e390874f2 100644
325 --- a/lib/portage/util/__init__.py
326 +++ b/lib/portage/util/__init__.py
327 @@ -72,7 +72,7 @@ def writemsg(mystr, noiselevel=0, fd=None):
328 else:
329 mystr = _unicode_encode(mystr,
330 encoding=_encodings['stdio'], errors='backslashreplace')
331 - if sys.hexversion >= 0x3000000 and fd in (sys.stdout, sys.stderr):
332 + if fd in (sys.stdout, sys.stderr):
333 fd = fd.buffer
334 fd.write(mystr)
335 fd.flush()
336 @@ -107,7 +107,7 @@ def normalize_path(mypath):
337 We dislike this behavior so we create our own normpath func
338 to fix it.
339 """
340 - if sys.hexversion >= 0x3000000 and isinstance(mypath, bytes):
341 + if isinstance(mypath, bytes):
342 path_sep = os.path.sep.encode()
343 else:
344 path_sep = os.path.sep
345 @@ -591,19 +591,15 @@ def writedict(mydict, myfilename, writekey=True):
346 lines.append("%s %s\n" % (k, " ".join(v)))
347 write_atomic(myfilename, "".join(lines))
348
349 +
350 def shlex_split(s):
351 """
352 This is equivalent to shlex.split, but if the current interpreter is
353 python2, it temporarily encodes unicode strings to bytes since python2's
354 shlex.split() doesn't handle unicode strings.
355 """
356 - convert_to_bytes = sys.hexversion < 0x3000000 and not isinstance(s, bytes)
357 - if convert_to_bytes:
358 - s = _unicode_encode(s)
359 - rval = shlex.split(s)
360 - if convert_to_bytes:
361 - rval = [_unicode_decode(x) for x in rval]
362 - return rval
363 + return shlex.split(s)
364 +
365
366 class _getconfig_shlex(shlex.shlex):
367
368 @@ -668,15 +664,9 @@ def getconfig(mycfg, tolerant=False, allow_sourcing=False, expand=True,
369
370 f = None
371 try:
372 - # NOTE: shlex doesn't support unicode objects with Python 2
373 - # (produces spurious \0 characters).
374 - if sys.hexversion < 0x3000000:
375 - f = open(_unicode_encode(mycfg,
376 - encoding=_encodings['fs'], errors='strict'), 'rb')
377 - else:
378 - f = open(_unicode_encode(mycfg,
379 - encoding=_encodings['fs'], errors='strict'), mode='r',
380 - encoding=_encodings['content'], errors='replace')
381 + f = open(_unicode_encode(mycfg,
382 + encoding=_encodings['fs'], errors='strict'), mode='r',
383 + encoding=_encodings['content'], errors='replace')
384 content = f.read()
385 except IOError as e:
386 if e.errno == PermissionDenied.errno:
387 @@ -1309,29 +1299,10 @@ class atomic_ofstream(ObjectProxy):
388 def _get_target(self):
389 return object.__getattribute__(self, '_file')
390
391 - if sys.hexversion >= 0x3000000:
392 -
393 - def __getattribute__(self, attr):
394 - if attr in ('close', 'abort', '__del__'):
395 - return object.__getattribute__(self, attr)
396 - return getattr(object.__getattribute__(self, '_file'), attr)
397 -
398 - else:
399 -
400 - # For TextIOWrapper, automatically coerce write calls to
401 - # unicode, in order to avoid TypeError when writing raw
402 - # bytes with python2.
403 -
404 - def __getattribute__(self, attr):
405 - if attr in ('close', 'abort', 'write', '__del__'):
406 - return object.__getattribute__(self, attr)
407 - return getattr(object.__getattribute__(self, '_file'), attr)
408 -
409 - def write(self, s):
410 - f = object.__getattribute__(self, '_file')
411 - if isinstance(f, io.TextIOWrapper):
412 - s = _unicode_decode(s)
413 - return f.write(s)
414 + def __getattribute__(self, attr):
415 + if attr in ('close', 'abort', '__del__'):
416 + return object.__getattribute__(self, attr)
417 + return getattr(object.__getattribute__(self, '_file'), attr)
418
419 def close(self):
420 """Closes the temporary file, copies permissions (if possible),
421 diff --git a/lib/portage/util/_dyn_libs/NeededEntry.py b/lib/portage/util/_dyn_libs/NeededEntry.py
422 index 59c4cf87d..154f50690 100644
423 --- a/lib/portage/util/_dyn_libs/NeededEntry.py
424 +++ b/lib/portage/util/_dyn_libs/NeededEntry.py
425 @@ -73,13 +73,3 @@ class NeededEntry(object):
426 (self.multilib_category if self.multilib_category
427 is not None else "")
428 ]) + "\n"
429 -
430 - if sys.hexversion < 0x3000000:
431 -
432 - __unicode__ = __str__
433 -
434 - def __str__(self):
435 - return _unicode_encode(self.__unicode__(),
436 - encoding=_encodings['content'])
437 -
438 - __str__.__doc__ = __unicode__.__doc__
439 diff --git a/lib/portage/util/digraph.py b/lib/portage/util/digraph.py
440 index 23c9e3c1a..e75a3a686 100644
441 --- a/lib/portage/util/digraph.py
442 +++ b/lib/portage/util/digraph.py
443 @@ -383,6 +383,3 @@ class digraph(object):
444 __contains__ = contains
445 empty = is_empty
446 copy = clone
447 -
448 - if sys.hexversion < 0x3000000:
449 - __nonzero__ = __bool__
450 diff --git a/lib/portage/util/listdir.py b/lib/portage/util/listdir.py
451 index 2012e145f..37312beb6 100644
452 --- a/lib/portage/util/listdir.py
453 +++ b/lib/portage/util/listdir.py
454 @@ -7,8 +7,6 @@ import errno
455 import stat
456 import sys
457
458 -if sys.hexversion < 0x3000000:
459 - from itertools import izip as zip
460
461 from portage import os
462 from portage.const import VCS_DIRS
463 diff --git a/lib/portage/util/whirlpool.py b/lib/portage/util/whirlpool.py
464 index 170ae73f8..a947dd719 100644
465 --- a/lib/portage/util/whirlpool.py
466 +++ b/lib/portage/util/whirlpool.py
467 @@ -26,8 +26,7 @@
468 ## This Python implementation is therefore also placed in the public domain.
469
470 import sys
471 -if sys.hexversion >= 0x3000000:
472 - xrange = range
473 +
474
475 #block_size = 64
476 digest_size = 64
477 @@ -641,8 +640,6 @@ def WhirlpoolInit(ctx):
478 def WhirlpoolAdd(source, sourceBits, ctx):
479 if not isinstance(source, bytes):
480 raise TypeError("Expected %s, got %s" % (bytes, type(source)))
481 - if sys.hexversion < 0x3000000:
482 - source = [ord(s)&0xff for s in source]
483
484 carry = 0
485 value = sourceBits
486 @@ -700,19 +697,19 @@ def WhirlpoolFinalize(ctx):
487 bufferPos += 1
488 if bufferPos > 32:
489 if bufferPos < 64:
490 - for i in xrange(64 - bufferPos):
491 + for i in range(64 - bufferPos):
492 ctx.buffer[bufferPos+i] = 0
493 processBuffer(ctx)
494 bufferPos = 0
495 if bufferPos < 32:
496 - for i in xrange(32 - bufferPos):
497 + for i in range(32 - bufferPos):
498 ctx.buffer[bufferPos+i] = 0
499 bufferPos = 32
500 - for i in xrange(32):
501 + for i in range(32):
502 ctx.buffer[32+i] = ctx.bitLength[i]
503 processBuffer(ctx)
504 digest = ''
505 - for i in xrange(8):
506 + for i in range(8):
507 digest += chr((ctx.hash[i] >> 56) % 0x100)
508 digest += chr((ctx.hash[i] >> 48) % 0x100)
509 digest += chr((ctx.hash[i] >> 40) % 0x100)
510 @@ -743,7 +740,7 @@ def processBuffer(ctx):
511 buffr = ctx.buffer
512
513 buf_cnt = 0
514 - for i in xrange(8):
515 + for i in range(8):
516 block[i] = ((buffr[buf_cnt+0] & 0xff) << 56) ^ \
517 ((buffr[buf_cnt+1] & 0xff) << 48) ^ \
518 ((buffr[buf_cnt+2] & 0xff) << 40) ^ \
519 @@ -753,11 +750,11 @@ def processBuffer(ctx):
520 ((buffr[buf_cnt+6] & 0xff) << 8) ^ \
521 ((buffr[buf_cnt+7] & 0xff) << 0)
522 buf_cnt += 8
523 - for i in xrange(8):
524 + for i in range(8):
525 K[i] = ctx.hash[i]
526 state[i] = block[i] ^ K[i]
527
528 - for r in xrange(1, R+1):
529 + for r in range(1, R+1):
530 L[0] = CDo(K, 0, 7, 6, 5, 4, 3, 2, 1) ^ rc[r]
531 L[1] = CDo(K, 1, 0, 7, 6, 5, 4, 3, 2)
532 L[2] = CDo(K, 2, 1, 0, 7, 6, 5, 4, 3)
533 @@ -766,7 +763,7 @@ def processBuffer(ctx):
534 L[5] = CDo(K, 5, 4, 3, 2, 1, 0, 7, 6)
535 L[6] = CDo(K, 6, 5, 4, 3, 2, 1, 0, 7)
536 L[7] = CDo(K, 7, 6, 5, 4, 3, 2, 1, 0)
537 - for i in xrange(8):
538 + for i in range(8):
539 K[i] = L[i]
540 L[0] = CDo(state, 0, 7, 6, 5, 4, 3, 2, 1) ^ K[0]
541 L[1] = CDo(state, 1, 0, 7, 6, 5, 4, 3, 2) ^ K[1]
542 @@ -776,10 +773,10 @@ def processBuffer(ctx):
543 L[5] = CDo(state, 5, 4, 3, 2, 1, 0, 7, 6) ^ K[5]
544 L[6] = CDo(state, 6, 5, 4, 3, 2, 1, 0, 7) ^ K[6]
545 L[7] = CDo(state, 7, 6, 5, 4, 3, 2, 1, 0) ^ K[7]
546 - for i in xrange(8):
547 + for i in range(8):
548 state[i] = L[i]
549 # apply the Miyaguchi-Preneel compression function
550 - for i in xrange(8):
551 + for i in range(8):
552 ctx.hash[i] ^= state[i] ^ block[i]
553 return
554
555 diff --git a/lib/portage/xpak.py b/lib/portage/xpak.py
556 index c708190b9..23539b6be 100644
557 --- a/lib/portage/xpak.py
558 +++ b/lib/portage/xpak.py
559 @@ -78,8 +78,6 @@ def encodeint(myint):
560 def decodeint(mystring):
561 """Takes a 4 byte string and converts it into a 4 byte integer.
562 Returns an integer."""
563 - if sys.hexversion < 0x3000000:
564 - mystring = [ord(x) for x in mystring]
565 myint = 0
566 myint += mystring[3]
567 myint += mystring[2] << 8
568 --
569 2.27.0

Replies