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] Eliminate the most of explicit py3 conditionals
Date: Thu, 16 Jul 2020 12:19:05
Message-Id: 20200716121832.463050-1-mgorny@gentoo.org
1 Eliminate the most of py2/py3 conditions in the code. Leave a few
2 where the relevant code is unclear, they will be addressed later.
3
4 Closes: https://github.com/gentoo/portage/pull/574
5 Signed-off-by: Michał Górny <mgorny@g.o>
6 ---
7 bin/check-implicit-pointer-usage.py | 25 ++--------
8 bin/chmod-lite.py | 11 ++---
9 bin/dohtml.py | 11 ++---
10 bin/doins.py | 7 ++-
11 bin/ebuild | 15 +-----
12 bin/filter-bash-environment.py | 11 ++---
13 bin/install.py | 19 ++++---
14 bin/pid-ns-init | 10 ++--
15 bin/xattr-helper.py | 32 +++---------
16 lib/_emerge/DependencyArg.py | 10 ----
17 lib/_emerge/JobStatusDisplay.py | 4 +-
18 lib/_emerge/Package.py | 8 ---
19 lib/_emerge/PackageVirtualDbapi.py | 3 --
20 lib/_emerge/SequentialTaskQueue.py | 3 --
21 lib/_emerge/TaskSequence.py | 3 --
22 lib/_emerge/UseFlagDisplay.py | 8 ---
23 lib/_emerge/UserQuery.py | 17 +++----
24 lib/_emerge/actions.py | 2 -
25 lib/_emerge/resolver/DbapiProvidesIndex.py | 3 --
26 lib/_emerge/resolver/output_helpers.py | 16 ------
27 lib/_emerge/resolver/slot_collision.py | 8 ---
28 lib/portage/__init__.py | 49 +++++++------------
29 lib/portage/_emirrordist/Config.py | 4 --
30 lib/portage/_selinux.py | 12 -----
31 lib/portage/_sets/base.py | 3 --
32 lib/portage/dbapi/porttree.py | 7 +--
33 lib/portage/dep/__init__.py | 18 +------
34 lib/portage/dep/soname/SonameAtom.py | 8 ---
35 lib/portage/elog/mod_save_summary.py | 2 -
36 lib/portage/elog/mod_syslog.py | 4 --
37 lib/portage/exception.py | 45 ++++-------------
38 lib/portage/mail.py | 49 +++----------------
39 lib/portage/manifest.py | 7 ---
40 lib/portage/output.py | 4 +-
41 lib/portage/process.py | 16 +-----
42 lib/portage/proxy/objectproxy.py | 6 ---
43 lib/portage/repository/config.py | 6 ---
44 .../tests/unicode/test_string_format.py | 44 ++++-------------
45 lib/portage/util/_ShelveUnicodeWrapper.py | 45 -----------------
46 39 files changed, 102 insertions(+), 453 deletions(-)
47 delete mode 100644 lib/portage/util/_ShelveUnicodeWrapper.py
48
49 diff --git a/bin/check-implicit-pointer-usage.py b/bin/check-implicit-pointer-usage.py
50 index a49db8107..868e4b3c8 100755
51 --- a/bin/check-implicit-pointer-usage.py
52 +++ b/bin/check-implicit-pointer-usage.py
53 @@ -33,22 +33,10 @@ pointer_pattern = (
54 + r"|"
55 + r"cast to pointer from integer of different size)")
56
57 -if sys.hexversion < 0x3000000:
58 - # Use encoded byte strings in python-2.x, since the python ebuilds are
59 - # known to remove the encodings module when USE=build is enabled (thus
60 - # disabling unicode decoding/encoding). The portage module has a
61 - # workaround for this, but currently we don't import that here since we
62 - # don't want to trigger potential sandbox violations due to stale pyc
63 - # files for the portage module.
64 - unicode_quote_open = '\xE2\x80\x98'
65 - unicode_quote_close = '\xE2\x80\x99'
66 - def write(msg):
67 - sys.stdout.write(msg)
68 -else:
69 - unicode_quote_open = '\u2018'
70 - unicode_quote_close = '\u2019'
71 - def write(msg):
72 - sys.stdout.buffer.write(msg.encode('utf_8', 'backslashreplace'))
73 +unicode_quote_open = '\u2018'
74 +unicode_quote_close = '\u2019'
75 +def write(msg):
76 + sys.stdout.buffer.write(msg.encode('utf_8', 'backslashreplace'))
77
78 pointer_pattern = re.compile(pointer_pattern)
79
80 @@ -57,10 +45,7 @@ last_implicit_linenum = -1
81 last_implicit_func = ""
82
83 while True:
84 - if sys.hexversion >= 0x3000000:
85 - line = sys.stdin.buffer.readline().decode('utf_8', 'replace')
86 - else:
87 - line = sys.stdin.readline()
88 + line = sys.stdin.buffer.readline().decode('utf_8', 'replace')
89 if not line:
90 break
91 # translate unicode open/close quotes to ascii ones
92 diff --git a/bin/chmod-lite.py b/bin/chmod-lite.py
93 index 177be7eab..7fe743ed1 100755
94 --- a/bin/chmod-lite.py
95 +++ b/bin/chmod-lite.py
96 @@ -12,12 +12,11 @@ os.chdir(os.environ["__PORTAGE_HELPER_CWD"])
97
98 def main(files):
99
100 - if sys.hexversion >= 0x3000000:
101 - # We can't trust that the filesystem encoding (locale dependent)
102 - # correctly matches the arguments, so use surrogateescape to
103 - # pass through the original argv bytes for Python 3.
104 - fs_encoding = sys.getfilesystemencoding()
105 - files = [x.encode(fs_encoding, 'surrogateescape') for x in files]
106 + # We can't trust that the filesystem encoding (locale dependent)
107 + # correctly matches the arguments, so use surrogateescape to
108 + # pass through the original argv bytes for Python 3.
109 + fs_encoding = sys.getfilesystemencoding()
110 + files = [x.encode(fs_encoding, 'surrogateescape') for x in files]
111
112 for filename in files:
113 # Emulate 'chmod -fR a+rX,u+w,g-w,o-w' with minimal chmod calls.
114 diff --git a/bin/dohtml.py b/bin/dohtml.py
115 index df8552b83..67c5eb9d1 100755
116 --- a/bin/dohtml.py
117 +++ b/bin/dohtml.py
118 @@ -163,12 +163,11 @@ def print_help():
119 def parse_args():
120 argv = sys.argv[:]
121
122 - if sys.hexversion >= 0x3000000:
123 - # We can't trust that the filesystem encoding (locale dependent)
124 - # correctly matches the arguments, so use surrogateescape to
125 - # pass through the original argv bytes for Python 3.
126 - fs_encoding = sys.getfilesystemencoding()
127 - argv = [x.encode(fs_encoding, 'surrogateescape') for x in argv]
128 + # We can't trust that the filesystem encoding (locale dependent)
129 + # correctly matches the arguments, so use surrogateescape to
130 + # pass through the original argv bytes for Python 3.
131 + fs_encoding = sys.getfilesystemencoding()
132 + argv = [x.encode(fs_encoding, 'surrogateescape') for x in argv]
133
134 for x, arg in enumerate(argv):
135 try:
136 diff --git a/bin/doins.py b/bin/doins.py
137 index 6bc30c90b..98dc4f810 100644
138 --- a/bin/doins.py
139 +++ b/bin/doins.py
140 @@ -514,10 +514,9 @@ def _parse_args(argv):
141
142 # Encode back to the original byte stream. Please see
143 # http://bugs.python.org/issue8776.
144 - if sys.version_info.major >= 3:
145 - opts.distdir = os.fsencode(opts.distdir) + b'/'
146 - opts.dest = os.fsencode(opts.dest)
147 - opts.sources = [os.fsencode(source) for source in opts.sources]
148 + opts.distdir = os.fsencode(opts.distdir) + b'/'
149 + opts.dest = os.fsencode(opts.dest)
150 + opts.sources = [os.fsencode(source) for source in opts.sources]
151
152 return opts
153
154 diff --git a/bin/ebuild b/bin/ebuild
155 index 460aa0fd1..ea02fa95a 100755
156 --- a/bin/ebuild
157 +++ b/bin/ebuild
158 @@ -144,9 +144,6 @@ if not os.path.isabs(ebuild):
159 # the canonical path returned from os.getcwd() may may be unusable in
160 # cases where the directory stucture is built from symlinks.
161 pwd = os.environ.get('PWD', '')
162 - if sys.hexversion < 0x3000000:
163 - pwd = _unicode_decode(pwd, encoding=_encodings['content'],
164 - errors='strict')
165 if pwd and pwd != mycwd and \
166 os.path.realpath(pwd) == mycwd:
167 mycwd = portage.normalize_path(pwd)
168 @@ -163,16 +160,8 @@ vdb_path = os.path.realpath(os.path.join(portage.settings['EROOT'], VDB_PATH))
169 if ebuild_portdir != vdb_path and \
170 ebuild_portdir not in portage.portdb.porttrees:
171 portdir_overlay = portage.settings.get("PORTDIR_OVERLAY", "")
172 - if sys.hexversion >= 0x3000000:
173 - os.environ["PORTDIR_OVERLAY"] = \
174 - portdir_overlay + \
175 - " " + _shell_quote(ebuild_portdir)
176 - else:
177 - os.environ["PORTDIR_OVERLAY"] = \
178 - _unicode_encode(portdir_overlay,
179 - encoding=_encodings['content'], errors='strict') + \
180 - " " + _unicode_encode(_shell_quote(ebuild_portdir),
181 - encoding=_encodings['content'], errors='strict')
182 + os.environ["PORTDIR_OVERLAY"] = (
183 + portdir_overlay + " " + _shell_quote(ebuild_portdir))
184
185 print("Appending %s to PORTDIR_OVERLAY..." % ebuild_portdir)
186 portage._reset_legacy_globals()
187 diff --git a/bin/filter-bash-environment.py b/bin/filter-bash-environment.py
188 index 045ea6f52..5e82fc91c 100755
189 --- a/bin/filter-bash-environment.py
190 +++ b/bin/filter-bash-environment.py
191 @@ -136,14 +136,9 @@ if __name__ == "__main__":
192 sys.stderr.flush()
193 sys.exit(2)
194
195 - file_in = sys.stdin
196 - file_out = sys.stdout
197 - if sys.hexversion >= 0x3000000:
198 - file_in = sys.stdin.buffer
199 - file_out = sys.stdout.buffer
200 - var_pattern = os.fsencode(args[0]).split()
201 - else:
202 - var_pattern = args[0].split()
203 + file_in = sys.stdin.buffer
204 + file_out = sys.stdout.buffer
205 + var_pattern = os.fsencode(args[0]).split()
206
207 # Filter invalid variable names that are not supported by bash.
208 var_pattern.append(br'\d.*')
209 diff --git a/bin/install.py b/bin/install.py
210 index 495534d33..c013f07e5 100755
211 --- a/bin/install.py
212 +++ b/bin/install.py
213 @@ -232,16 +232,15 @@ def main(args):
214 cmdline = [install_binary]
215 cmdline += args
216
217 - if sys.hexversion >= 0x3000000:
218 - # We can't trust that the filesystem encoding (locale dependent)
219 - # correctly matches the arguments, so use surrogateescape to
220 - # pass through the original argv bytes for Python 3.
221 - fs_encoding = sys.getfilesystemencoding()
222 - cmdline = [x.encode(fs_encoding, 'surrogateescape') for x in cmdline]
223 - files = [x.encode(fs_encoding, 'surrogateescape') for x in files]
224 - if opts.target_directory is not None:
225 - opts.target_directory = \
226 - opts.target_directory.encode(fs_encoding, 'surrogateescape')
227 + # We can't trust that the filesystem encoding (locale dependent)
228 + # correctly matches the arguments, so use surrogateescape to
229 + # pass through the original argv bytes for Python 3.
230 + fs_encoding = sys.getfilesystemencoding()
231 + cmdline = [x.encode(fs_encoding, 'surrogateescape') for x in cmdline]
232 + files = [x.encode(fs_encoding, 'surrogateescape') for x in files]
233 + if opts.target_directory is not None:
234 + opts.target_directory = \
235 + opts.target_directory.encode(fs_encoding, 'surrogateescape')
236
237 returncode = subprocess.call(cmdline)
238 if returncode == os.EX_OK:
239 diff --git a/bin/pid-ns-init b/bin/pid-ns-init
240 index 18c74f799..3a218a5df 100644
241 --- a/bin/pid-ns-init
242 +++ b/bin/pid-ns-init
243 @@ -39,7 +39,7 @@ def preexec_fn(uid, gid, groups, umask):
244 os.umask(umask)
245
246 # CPython >= 3 subprocess.Popen handles this internally.
247 - if sys.version_info.major < 3 or platform.python_implementation() != 'CPython':
248 + if platform.python_implementation() != 'CPython':
249 for signum in (
250 signal.SIGHUP,
251 signal.SIGINT,
252 @@ -70,10 +70,10 @@ def main(argv):
253 groups = tuple(int(group) for group in groups.split(',')) if groups else None
254 umask = int(umask) if umask else None
255
256 - popen_kwargs = {}
257 - popen_kwargs['preexec_fn'] = functools.partial(preexec_fn, uid, gid, groups, umask)
258 - if sys.version_info.major > 2:
259 - popen_kwargs['pass_fds'] = pass_fds
260 + popen_kwargs = {
261 + 'preexec_fn': functools.partial(preexec_fn, uid, gid, groups, umask),
262 + 'pass_fds': pass_fds,
263 + }
264 # Isolate parent process from process group SIGSTOP (bug 675870)
265 setsid = True
266 os.setsid()
267 diff --git a/bin/xattr-helper.py b/bin/xattr-helper.py
268 index 49c981580..7658934a0 100755
269 --- a/bin/xattr-helper.py
270 +++ b/bin/xattr-helper.py
271 @@ -26,24 +26,14 @@ _UNQUOTE_RE = re.compile(br'\\[0-7]{3}')
272 _FS_ENCODING = sys.getfilesystemencoding()
273
274
275 -if sys.hexversion < 0x3000000:
276 +def octal_quote_byte(b):
277 + return ('\\%03o' % ord(b)).encode('ascii')
278
279 - def octal_quote_byte(b):
280 - return b'\\%03o' % ord(b)
281
282 - def unicode_encode(s):
283 - if isinstance(s, unicode):
284 - s = s.encode(_FS_ENCODING)
285 - return s
286 -else:
287 -
288 - def octal_quote_byte(b):
289 - return ('\\%03o' % ord(b)).encode('ascii')
290 -
291 - def unicode_encode(s):
292 - if isinstance(s, str):
293 - s = s.encode(_FS_ENCODING, 'surrogateescape')
294 - return s
295 +def unicode_encode(s):
296 + if isinstance(s, str):
297 + s = s.encode(_FS_ENCODING, 'surrogateescape')
298 + return s
299
300
301 def quote(s, quote_chars):
302 @@ -157,20 +147,14 @@ def main(argv):
303
304 options = parser.parse_args(argv)
305
306 - if sys.hexversion >= 0x3000000:
307 - file_in = sys.stdin.buffer.raw
308 - else:
309 - file_in = sys.stdin
310 + file_in = sys.stdin.buffer.raw
311
312 if options.dump:
313 if options.paths:
314 options.paths = [unicode_encode(x) for x in options.paths]
315 else:
316 options.paths = [x for x in file_in.read().split(b'\0') if x]
317 - if sys.hexversion >= 0x3000000:
318 - file_out = sys.stdout.buffer
319 - else:
320 - file_out = sys.stdout
321 + file_out = sys.stdout.buffer
322 dump_xattrs(options.paths, file_out)
323
324 elif options.restore:
325 diff --git a/lib/_emerge/DependencyArg.py b/lib/_emerge/DependencyArg.py
326 index 87f255f10..a997f0f90 100644
327 --- a/lib/_emerge/DependencyArg.py
328 +++ b/lib/_emerge/DependencyArg.py
329 @@ -31,14 +31,4 @@ class DependencyArg(object):
330 return hash((self.arg, self.root_config.root))
331
332 def __str__(self):
333 - # Use unicode_literals format string for python-2.x safety,
334 - # ensuring that self.arg.__unicode__() is used
335 - # when necessary.
336 return "%s" % (self.arg,)
337 -
338 - if sys.hexversion < 0x3000000:
339 -
340 - __unicode__ = __str__
341 -
342 - def __str__(self):
343 - return _unicode_encode(self.__unicode__(), encoding=_encodings['content'])
344 diff --git a/lib/_emerge/JobStatusDisplay.py b/lib/_emerge/JobStatusDisplay.py
345 index b3160a4cc..2ef3f8465 100644
346 --- a/lib/_emerge/JobStatusDisplay.py
347 +++ b/lib/_emerge/JobStatusDisplay.py
348 @@ -83,9 +83,7 @@ class JobStatusDisplay(object):
349 # avoid potential UnicodeEncodeError
350 s = _unicode_encode(s,
351 encoding=_encodings['stdio'], errors='backslashreplace')
352 - out = self.out
353 - if sys.hexversion >= 0x3000000:
354 - out = out.buffer
355 + out = self.out.buffer
356 out.write(s)
357 out.flush()
358
359 diff --git a/lib/_emerge/Package.py b/lib/_emerge/Package.py
360 index 76f4066bb..1fb0bb20b 100644
361 --- a/lib/_emerge/Package.py
362 +++ b/lib/_emerge/Package.py
363 @@ -528,14 +528,6 @@ class Package(Task):
364 s += ")"
365 return s
366
367 - if sys.hexversion < 0x3000000:
368 -
369 - __unicode__ = __str__
370 -
371 - def __str__(self):
372 - return _unicode_encode(self.__unicode__(),
373 - encoding=_encodings['content'])
374 -
375 class _use_class(object):
376
377 __slots__ = ("enabled", "_expand", "_expand_hidden",
378 diff --git a/lib/_emerge/PackageVirtualDbapi.py b/lib/_emerge/PackageVirtualDbapi.py
379 index 26293dd98..957eab594 100644
380 --- a/lib/_emerge/PackageVirtualDbapi.py
381 +++ b/lib/_emerge/PackageVirtualDbapi.py
382 @@ -41,9 +41,6 @@ class PackageVirtualDbapi(dbapi):
383 def __bool__(self):
384 return bool(self._cpv_map)
385
386 - if sys.hexversion < 0x3000000:
387 - __nonzero__ = __bool__
388 -
389 def __iter__(self):
390 return iter(self._cpv_map.values())
391
392 diff --git a/lib/_emerge/SequentialTaskQueue.py b/lib/_emerge/SequentialTaskQueue.py
393 index d2551b1c6..1cadbca41 100644
394 --- a/lib/_emerge/SequentialTaskQueue.py
395 +++ b/lib/_emerge/SequentialTaskQueue.py
396 @@ -85,8 +85,5 @@ class SequentialTaskQueue(SlotObject):
397 def __bool__(self):
398 return bool(self._task_queue or self.running_tasks)
399
400 - if sys.hexversion < 0x3000000:
401 - __nonzero__ = __bool__
402 -
403 def __len__(self):
404 return len(self._task_queue) + len(self.running_tasks)
405 diff --git a/lib/_emerge/TaskSequence.py b/lib/_emerge/TaskSequence.py
406 index 1f2ba94c2..2fd349810 100644
407 --- a/lib/_emerge/TaskSequence.py
408 +++ b/lib/_emerge/TaskSequence.py
409 @@ -54,8 +54,5 @@ class TaskSequence(CompositeTask):
410 def __bool__(self):
411 return bool(self._task_queue)
412
413 - if sys.hexversion < 0x3000000:
414 - __nonzero__ = __bool__
415 -
416 def __len__(self):
417 return len(self._task_queue)
418 diff --git a/lib/_emerge/UseFlagDisplay.py b/lib/_emerge/UseFlagDisplay.py
419 index c16e7ba0d..6f6e27fb8 100644
420 --- a/lib/_emerge/UseFlagDisplay.py
421 +++ b/lib/_emerge/UseFlagDisplay.py
422 @@ -30,14 +30,6 @@ class UseFlagDisplay(object):
423 s = '(%s)' % s
424 return s
425
426 - if sys.hexversion < 0x3000000:
427 -
428 - __unicode__ = __str__
429 -
430 - def __str__(self):
431 - return _unicode_encode(self.__unicode__(),
432 - encoding=_encodings['content'])
433 -
434 def _cmp_combined(a, b):
435 """
436 Sort by name, combining enabled and disabled flags.
437 diff --git a/lib/_emerge/UserQuery.py b/lib/_emerge/UserQuery.py
438 index faa32cf50..a9b3a4865 100644
439 --- a/lib/_emerge/UserQuery.py
440 +++ b/lib/_emerge/UserQuery.py
441 @@ -54,17 +54,12 @@ class UserQuery(object):
442 print(bold(prompt), end=' ')
443 try:
444 while True:
445 - if sys.hexversion >= 0x3000000:
446 - try:
447 - response = input("[%s] " %
448 - "/".join([colours[i](responses[i])
449 - for i in range(len(responses))]))
450 - except UnicodeDecodeError as e:
451 - response = _unicode_decode(e.object).rstrip('\n')
452 - else:
453 - response=raw_input("["+"/".join([colours[i](responses[i])
454 - for i in range(len(responses))])+"] ")
455 - response = _unicode_decode(response)
456 + try:
457 + response = input("[%s] " %
458 + "/".join([colours[i](responses[i])
459 + for i in range(len(responses))]))
460 + except UnicodeDecodeError as e:
461 + response = _unicode_decode(e.object).rstrip('\n')
462 if response or not enter_invalid:
463 for key in responses:
464 # An empty response will match the
465 diff --git a/lib/_emerge/actions.py b/lib/_emerge/actions.py
466 index dc54372a3..e717bc828 100644
467 --- a/lib/_emerge/actions.py
468 +++ b/lib/_emerge/actions.py
469 @@ -3194,8 +3194,6 @@ def run_action(emerge_config):
470
471 if not "--pretend" in emerge_config.opts:
472 time_fmt = "%b %d, %Y %H:%M:%S"
473 - if sys.hexversion < 0x3000000:
474 - time_fmt = portage._unicode_encode(time_fmt)
475 time_str = time.strftime(time_fmt, time.localtime(time.time()))
476 # Avoid potential UnicodeDecodeError in Python 2, since strftime
477 # returns bytes in Python 2, and %b may contain non-ascii chars.
478 diff --git a/lib/_emerge/resolver/DbapiProvidesIndex.py b/lib/_emerge/resolver/DbapiProvidesIndex.py
479 index 1650edd4e..9d122a7e5 100644
480 --- a/lib/_emerge/resolver/DbapiProvidesIndex.py
481 +++ b/lib/_emerge/resolver/DbapiProvidesIndex.py
482 @@ -73,9 +73,6 @@ class PackageDbapiProvidesIndex(DbapiProvidesIndex):
483 def __bool__(self):
484 return bool(self._db)
485
486 - if sys.hexversion < 0x3000000:
487 - __nonzero__ = __bool__
488 -
489 def __iter__(self):
490 return iter(self._db)
491
492 diff --git a/lib/_emerge/resolver/output_helpers.py b/lib/_emerge/resolver/output_helpers.py
493 index 4279590dc..0616bb6ac 100644
494 --- a/lib/_emerge/resolver/output_helpers.py
495 +++ b/lib/_emerge/resolver/output_helpers.py
496 @@ -76,14 +76,6 @@ class _RepoDisplay(object):
497 " indicates that the source repository could not be determined\n")
498 return "".join(output)
499
500 - if sys.hexversion < 0x3000000:
501 -
502 - __unicode__ = __str__
503 -
504 - def __str__(self):
505 - return _unicode_encode(self.__unicode__(),
506 - encoding=_encodings['content'])
507 -
508
509 class _PackageCounters(object):
510
511 @@ -677,11 +669,3 @@ class PkgAttrDisplay(SlotObject):
512 output.append(self.mask)
513
514 return "".join(output)
515 -
516 - if sys.hexversion < 0x3000000:
517 -
518 - __unicode__ = __str__
519 -
520 - def __str__(self):
521 - return _unicode_encode(self.__unicode__(),
522 - encoding=_encodings['content'])
523 diff --git a/lib/_emerge/resolver/slot_collision.py b/lib/_emerge/resolver/slot_collision.py
524 index 0bed08785..e77433fb8 100644
525 --- a/lib/_emerge/resolver/slot_collision.py
526 +++ b/lib/_emerge/resolver/slot_collision.py
527 @@ -1130,14 +1130,6 @@ class _solution_candidate_generator(object):
528 def __str__(self):
529 return "%s" % (self.value,)
530
531 - if sys.hexversion < 0x3000000:
532 -
533 - __unicode__ = __str__
534 -
535 - def __str__(self):
536 - return _unicode_encode(self.__unicode__(),
537 - encoding=_encodings['content'], errors='backslashreplace')
538 -
539 def __init__(self, all_involved_flags):
540 #A copy of all_involved_flags with all "cond" values
541 #replaced by a _value_helper object.
542 diff --git a/lib/portage/__init__.py b/lib/portage/__init__.py
543 index 8ac899f7b..2c44376cb 100644
544 --- a/lib/portage/__init__.py
545 +++ b/lib/portage/__init__.py
546 @@ -163,43 +163,30 @@ _encodings = {
547 'stdio' : 'utf_8',
548 }
549
550 -if sys.hexversion >= 0x3000000:
551 -
552 - def _decode_argv(argv):
553 - # With Python 3, the surrogateescape encoding error handler makes it
554 - # possible to access the original argv bytes, which can be useful
555 - # if their actual encoding does no match the filesystem encoding.
556 - fs_encoding = sys.getfilesystemencoding()
557 - return [_unicode_decode(x.encode(fs_encoding, 'surrogateescape'))
558 - for x in argv]
559 -
560 - def _unicode_encode(s, encoding=_encodings['content'], errors='backslashreplace'):
561 - if isinstance(s, str):
562 - s = s.encode(encoding, errors)
563 - return s
564
565 - def _unicode_decode(s, encoding=_encodings['content'], errors='replace'):
566 - if isinstance(s, bytes):
567 - s = str(s, encoding=encoding, errors=errors)
568 - return s
569 +def _decode_argv(argv):
570 + # With Python 3, the surrogateescape encoding error handler makes it
571 + # possible to access the original argv bytes, which can be useful
572 + # if their actual encoding does no match the filesystem encoding.
573 + fs_encoding = sys.getfilesystemencoding()
574 + return [_unicode_decode(x.encode(fs_encoding, 'surrogateescape'))
575 + for x in argv]
576
577 - _native_string = _unicode_decode
578 -else:
579
580 - def _decode_argv(argv):
581 - return [_unicode_decode(x) for x in argv]
582 +def _unicode_encode(s, encoding=_encodings['content'], errors='backslashreplace'):
583 + if isinstance(s, str):
584 + s = s.encode(encoding, errors)
585 + return s
586
587 - def _unicode_encode(s, encoding=_encodings['content'], errors='backslashreplace'):
588 - if isinstance(s, unicode):
589 - s = s.encode(encoding, errors)
590 - return s
591
592 - def _unicode_decode(s, encoding=_encodings['content'], errors='replace'):
593 - if isinstance(s, bytes):
594 - s = unicode(s, encoding=encoding, errors=errors)
595 - return s
596 +def _unicode_decode(s, encoding=_encodings['content'], errors='replace'):
597 + if isinstance(s, bytes):
598 + s = str(s, encoding=encoding, errors=errors)
599 + return s
600 +
601 +
602 +_native_string = _unicode_decode
603
604 - _native_string = _unicode_encode
605
606 class _unicode_func_wrapper(object):
607 """
608 diff --git a/lib/portage/_emirrordist/Config.py b/lib/portage/_emirrordist/Config.py
609 index c1f59f725..d5dea7ab4 100644
610 --- a/lib/portage/_emirrordist/Config.py
611 +++ b/lib/portage/_emirrordist/Config.py
612 @@ -12,7 +12,6 @@ import portage
613 from portage import os
614 from portage.package.ebuild.fetch import MirrorLayoutConfig
615 from portage.util import grabdict, grablines
616 -from portage.util._ShelveUnicodeWrapper import ShelveUnicodeWrapper
617
618 class Config(object):
619 def __init__(self, options, portdb, event_loop):
620 @@ -126,9 +125,6 @@ class Config(object):
621 from bsddb3 import dbshelve
622 db = dbshelve.open(db_file, flags=open_flag)
623
624 - if sys.hexversion < 0x3000000:
625 - db = ShelveUnicodeWrapper(db)
626 -
627 if self.options.dry_run:
628 logging.warning("dry-run: %s db opened in readonly mode" % db_desc)
629 if not isinstance(db, dict):
630 diff --git a/lib/portage/_selinux.py b/lib/portage/_selinux.py
631 index 49e2e8e58..a64215f27 100644
632 --- a/lib/portage/_selinux.py
633 +++ b/lib/portage/_selinux.py
634 @@ -23,8 +23,6 @@ def copyfile(src, dest):
635 dest = _native_string(dest, encoding=_encodings['fs'], errors='strict')
636 (rc, ctx) = selinux.lgetfilecon(src)
637 if rc < 0:
638 - if sys.hexversion < 0x3000000:
639 - src = _unicode_decode(src, encoding=_encodings['fs'], errors='replace')
640 raise OSError(_("copyfile: Failed getting context of \"%s\".") % src)
641
642 setfscreate(ctx)
643 @@ -48,8 +46,6 @@ def mkdir(target, refdir):
644 refdir = _native_string(refdir, encoding=_encodings['fs'], errors='strict')
645 (rc, ctx) = selinux.getfilecon(refdir)
646 if rc < 0:
647 - if sys.hexversion < 0x3000000:
648 - refdir = _unicode_decode(refdir, encoding=_encodings['fs'], errors='replace')
649 raise OSError(
650 _("mkdir: Failed getting context of reference directory \"%s\".") \
651 % refdir)
652 @@ -65,8 +61,6 @@ def rename(src, dest):
653 dest = _native_string(dest, encoding=_encodings['fs'], errors='strict')
654 (rc, ctx) = selinux.lgetfilecon(src)
655 if rc < 0:
656 - if sys.hexversion < 0x3000000:
657 - src = _unicode_decode(src, encoding=_encodings['fs'], errors='replace')
658 raise OSError(_("rename: Failed getting context of \"%s\".") % src)
659
660 setfscreate(ctx)
661 @@ -98,8 +92,6 @@ def setexec(ctx="\n"):
662 portage.writemsg("!!! %s\n" % msg, noiselevel=-1)
663
664 if rc < 0:
665 - if sys.hexversion < 0x3000000:
666 - ctx = _unicode_decode(ctx, encoding=_encodings['content'], errors='replace')
667 if selinux.security_getenforce() == 1:
668 raise OSError(_("Failed setting exec() context \"%s\".") % ctx)
669 else:
670 @@ -110,8 +102,6 @@ def setexec(ctx="\n"):
671 def setfscreate(ctx="\n"):
672 ctx = _native_string(ctx, encoding=_encodings['content'], errors='strict')
673 if selinux.setfscreatecon(ctx) < 0:
674 - if sys.hexversion < 0x3000000:
675 - ctx = _unicode_decode(ctx, encoding=_encodings['content'], errors='replace')
676 raise OSError(
677 _("setfscreate: Failed setting fs create context \"%s\".") % ctx)
678
679 @@ -148,8 +138,6 @@ def symlink(target, link, reflnk):
680 reflnk = _native_string(reflnk, encoding=_encodings['fs'], errors='strict')
681 (rc, ctx) = selinux.lgetfilecon(reflnk)
682 if rc < 0:
683 - if sys.hexversion < 0x3000000:
684 - reflnk = _unicode_decode(reflnk, encoding=_encodings['fs'], errors='replace')
685 raise OSError(
686 _("symlink: Failed getting context of reference symlink \"%s\".") \
687 % reflnk)
688 diff --git a/lib/portage/_sets/base.py b/lib/portage/_sets/base.py
689 index 4d0a42179..a9c898da7 100644
690 --- a/lib/portage/_sets/base.py
691 +++ b/lib/portage/_sets/base.py
692 @@ -43,9 +43,6 @@ class PackageSet(object):
693 self._load()
694 return bool(self._atoms or self._nonatoms)
695
696 - if sys.hexversion < 0x3000000:
697 - __nonzero__ = __bool__
698 -
699 def supportsOperation(self, op):
700 if not op in OPERATIONS:
701 raise ValueError(op)
702 diff --git a/lib/portage/dbapi/porttree.py b/lib/portage/dbapi/porttree.py
703 index da337ad0e..4916114cd 100644
704 --- a/lib/portage/dbapi/porttree.py
705 +++ b/lib/portage/dbapi/porttree.py
706 @@ -1455,12 +1455,7 @@ class FetchlistDict(Mapping):
707 infinite recursion in some cases."""
708 return len(self.portdb.cp_list(self.cp, mytree=self.mytree))
709
710 - def keys(self):
711 - """Returns keys for all packages within pkgdir"""
712 - return self.portdb.cp_list(self.cp, mytree=self.mytree)
713 -
714 - if sys.hexversion >= 0x3000000:
715 - keys = __iter__
716 + keys = __iter__
717
718
719 def _async_manifest_fetchlist(portdb, repo_config, cp, cpv_list=None,
720 diff --git a/lib/portage/dep/__init__.py b/lib/portage/dep/__init__.py
721 index baeea4bf7..bfb957d89 100644
722 --- a/lib/portage/dep/__init__.py
723 +++ b/lib/portage/dep/__init__.py
724 @@ -960,22 +960,11 @@ class _use_dep(object):
725 def __bool__(self):
726 return bool(self.tokens)
727
728 - if sys.hexversion < 0x3000000:
729 - __nonzero__ = __bool__
730 -
731 def __str__(self):
732 if not self.tokens:
733 return ""
734 return "[%s]" % (",".join(self.tokens),)
735
736 - if sys.hexversion < 0x3000000:
737 -
738 - __unicode__ = __str__
739 -
740 - def __str__(self):
741 - return _unicode_encode(self.__unicode__(),
742 - encoding=_encodings['content'], errors='backslashreplace')
743 -
744 def __repr__(self):
745 return "portage.dep._use_dep(%s)" % repr(self.tokens)
746
747 @@ -1715,9 +1704,8 @@ class ExtendedAtomDict(portage.cache.mappings.MutableMapping):
748 else:
749 return self._normal.__delitem__(cp)
750
751 - if sys.hexversion >= 0x3000000:
752 - keys = __iter__
753 - items = iteritems
754 + keys = __iter__
755 + items = iteritems
756
757 def __len__(self):
758 return len(self._normal) + len(self._extended)
759 @@ -2575,8 +2563,6 @@ class _RequiredUseBranch(object):
760
761 return " ".join(tokens)
762
763 - if sys.hexversion < 0x3000000:
764 - __nonzero__ = __bool__
765
766 def check_required_use(required_use, use, iuse_match, eapi=None):
767 """
768 diff --git a/lib/portage/dep/soname/SonameAtom.py b/lib/portage/dep/soname/SonameAtom.py
769 index 12d79386b..2dae03c36 100644
770 --- a/lib/portage/dep/soname/SonameAtom.py
771 +++ b/lib/portage/dep/soname/SonameAtom.py
772 @@ -56,14 +56,6 @@ class SonameAtom(object):
773 def __str__(self):
774 return "%s: %s" % (self.multilib_category, self.soname)
775
776 - if sys.hexversion < 0x3000000:
777 -
778 - __unicode__ = __str__
779 -
780 - def __str__(self):
781 - return _unicode_encode(self.__unicode__(),
782 - encoding=_encodings['content'])
783 -
784 def match(self, pkg):
785 """
786 Check if the given package instance matches this atom. Unbuilt
787 diff --git a/lib/portage/elog/mod_save_summary.py b/lib/portage/elog/mod_save_summary.py
788 index 48c006037..7aa6f2bef 100644
789 --- a/lib/portage/elog/mod_save_summary.py
790 +++ b/lib/portage/elog/mod_save_summary.py
791 @@ -73,8 +73,6 @@ def process(mysettings, key, logentries, fulltext):
792 mode=elogdir_grp_mode, mask=0)
793
794 time_fmt = "%Y-%m-%d %H:%M:%S %Z"
795 - if sys.hexversion < 0x3000000:
796 - time_fmt = _unicode_encode(time_fmt)
797 time_str = time.strftime(time_fmt, time.localtime(time.time()))
798 # Avoid potential UnicodeDecodeError in Python 2, since strftime
799 # returns bytes in Python 2, and %Z may contain non-ascii chars.
800 diff --git a/lib/portage/elog/mod_syslog.py b/lib/portage/elog/mod_syslog.py
801 index d2ad89d65..e5d1bbca8 100644
802 --- a/lib/portage/elog/mod_syslog.py
803 +++ b/lib/portage/elog/mod_syslog.py
804 @@ -26,9 +26,5 @@ def process(mysettings, key, logentries, fulltext):
805 msgcontent = [msgcontent]
806 for line in msgcontent:
807 line = "%s: %s: %s" % (key, phase, line)
808 - if sys.hexversion < 0x3000000 and not isinstance(line, bytes):
809 - # Avoid TypeError from syslog.syslog()
810 - line = line.encode(_encodings['content'],
811 - 'backslashreplace')
812 syslog.syslog(_pri[msgtype], line.rstrip("\n"))
813 syslog.closelog()
814 diff --git a/lib/portage/exception.py b/lib/portage/exception.py
815 index fa59f1f14..e2be95c1e 100644
816 --- a/lib/portage/exception.py
817 +++ b/lib/portage/exception.py
818 @@ -9,35 +9,15 @@ from portage.localization import _
819
820 class PortageException(Exception):
821 """General superclass for portage exceptions"""
822 - if sys.hexversion >= 0x3000000:
823 - def __init__(self, value):
824 - self.value = value[:]
825 -
826 - def __str__(self):
827 - if isinstance(self.value, str):
828 - return self.value
829 - else:
830 - return repr(self.value)
831 - else:
832 - def __init__(self, value):
833 - self.value = value[:]
834 - if isinstance(self.value, str):
835 - self.value = _unicode_decode(self.value,
836 - encoding=_encodings['content'], errors='replace')
837 -
838 - def __unicode__(self):
839 - if isinstance(self.value, unicode):
840 - return self.value
841 - else:
842 - return _unicode_decode(repr(self.value),
843 - encoding=_encodings['content'], errors='replace')
844 -
845 - def __str__(self):
846 - if isinstance(self.value, unicode):
847 - return _unicode_encode(self.value,
848 - encoding=_encodings['content'], errors='backslashreplace')
849 - else:
850 - return repr(self.value)
851 + def __init__(self, value):
852 + self.value = value[:]
853 +
854 + def __str__(self):
855 + if isinstance(self.value, str):
856 + return self.value
857 + else:
858 + return repr(self.value)
859 +
860
861 class PortageKeyError(KeyError, PortageException):
862 __doc__ = KeyError.__doc__
863 @@ -187,13 +167,6 @@ class UnsupportedAPIException(PortagePackageException):
864 return _unicode_decode(msg,
865 encoding=_encodings['content'], errors='replace')
866
867 - if sys.hexversion < 0x3000000:
868 -
869 - __unicode__ = __str__
870 -
871 - def __str__(self):
872 - return _unicode_encode(self.__unicode__(),
873 - encoding=_encodings['content'], errors='backslashreplace')
874
875 class SignatureException(PortageException):
876 """Signature was not present in the checked file"""
877 diff --git a/lib/portage/mail.py b/lib/portage/mail.py
878 index 6a351aa24..730c9352e 100644
879 --- a/lib/portage/mail.py
880 +++ b/lib/portage/mail.py
881 @@ -19,20 +19,15 @@ from portage import _unicode_decode, _unicode_encode
882 from portage.localization import _
883 import portage
884
885 -if sys.hexversion >= 0x3000000:
886 - def _force_ascii_if_necessary(s):
887 - # Force ascii encoding in order to avoid UnicodeEncodeError
888 - # from smtplib.sendmail with python3 (bug #291331).
889 - s = _unicode_encode(s,
890 - encoding='ascii', errors='backslashreplace')
891 - s = _unicode_decode(s,
892 - encoding='ascii', errors='replace')
893 - return s
894 +def _force_ascii_if_necessary(s):
895 + # Force ascii encoding in order to avoid UnicodeEncodeError
896 + # from smtplib.sendmail with python3 (bug #291331).
897 + s = _unicode_encode(s,
898 + encoding='ascii', errors='backslashreplace')
899 + s = _unicode_decode(s,
900 + encoding='ascii', errors='replace')
901 + return s
902
903 -else:
904 -
905 - def _force_ascii_if_necessary(s):
906 - return s
907
908 def TextMessage(_text):
909 from email.mime.text import MIMEText
910 @@ -47,16 +42,6 @@ def create_message(sender, recipient, subject, body, attachments=None):
911 from email.mime.multipart import MIMEMultipart as MultipartMessage
912 from email.utils import formatdate
913
914 - if sys.hexversion < 0x3000000:
915 - sender = _unicode_encode(sender,
916 - encoding=_encodings['content'], errors='strict')
917 - recipient = _unicode_encode(recipient,
918 - encoding=_encodings['content'], errors='strict')
919 - subject = _unicode_encode(subject,
920 - encoding=_encodings['content'], errors='backslashreplace')
921 - body = _unicode_encode(body,
922 - encoding=_encodings['content'], errors='backslashreplace')
923 -
924 if attachments == None:
925 mymessage = TextMessage(body)
926 else:
927 @@ -66,10 +51,6 @@ def create_message(sender, recipient, subject, body, attachments=None):
928 if isinstance(x, BaseMessage):
929 mymessage.attach(x)
930 elif isinstance(x, str):
931 - if sys.hexversion < 0x3000000:
932 - x = _unicode_encode(x,
933 - encoding=_encodings['content'],
934 - errors='backslashreplace')
935 mymessage.attach(TextMessage(x))
936 else:
937 raise portage.exception.PortageException(_("Can't handle type of attachment: %s") % type(x))
938 @@ -129,20 +110,6 @@ def send_mail(mysettings, message):
939
940 myfrom = message.get("From")
941
942 - if sys.hexversion < 0x3000000:
943 - myrecipient = _unicode_encode(myrecipient,
944 - encoding=_encodings['content'], errors='strict')
945 - mymailhost = _unicode_encode(mymailhost,
946 - encoding=_encodings['content'], errors='strict')
947 - mymailport = _unicode_encode(mymailport,
948 - encoding=_encodings['content'], errors='strict')
949 - myfrom = _unicode_encode(myfrom,
950 - encoding=_encodings['content'], errors='strict')
951 - mymailuser = _unicode_encode(mymailuser,
952 - encoding=_encodings['content'], errors='strict')
953 - mymailpasswd = _unicode_encode(mymailpasswd,
954 - encoding=_encodings['content'], errors='strict')
955 -
956 # user wants to use a sendmail binary instead of smtp
957 if mymailhost[0] == os.sep and os.path.exists(mymailhost):
958 fd = os.popen(mymailhost+" -f "+myfrom+" "+myrecipient, "w")
959 diff --git a/lib/portage/manifest.py b/lib/portage/manifest.py
960 index b2c3923a1..7671bae34 100644
961 --- a/lib/portage/manifest.py
962 +++ b/lib/portage/manifest.py
963 @@ -107,13 +107,6 @@ class Manifest2Entry(ManifestEntry):
964 def __ne__(self, other):
965 return not self.__eq__(other)
966
967 - if sys.hexversion < 0x3000000:
968 -
969 - __unicode__ = __str__
970 -
971 - def __str__(self):
972 - return _unicode_encode(self.__unicode__(),
973 - encoding=_encodings['repo.content'], errors='strict')
974
975 class Manifest(object):
976 parsers = (parseManifest2,)
977 diff --git a/lib/portage/output.py b/lib/portage/output.py
978 index 6fbb24f4c..8bfcd91c2 100644
979 --- a/lib/portage/output.py
980 +++ b/lib/portage/output.py
981 @@ -256,9 +256,7 @@ def xtermTitle(mystr, raw=False):
982 # avoid potential UnicodeEncodeError
983 mystr = _unicode_encode(mystr,
984 encoding=_encodings['stdio'], errors='backslashreplace')
985 - f = sys.stderr
986 - if sys.hexversion >= 0x3000000:
987 - f = f.buffer
988 + f = sys.stderr.buffer
989 f.write(mystr)
990 f.flush()
991
992 diff --git a/lib/portage/process.py b/lib/portage/process.py
993 index bbe8d02f0..f550bcb30 100644
994 --- a/lib/portage/process.py
995 +++ b/lib/portage/process.py
996 @@ -198,10 +198,7 @@ def run_exitfuncs():
997 exc_info = sys.exc_info()
998
999 if exc_info is not None:
1000 - if sys.hexversion >= 0x3000000:
1001 - raise exc_info[0](exc_info[1]).with_traceback(exc_info[2])
1002 - else:
1003 - exec("raise exc_info[0], exc_info[1], exc_info[2]")
1004 + raise exc_info[0](exc_info[1]).with_traceback(exc_info[2])
1005
1006 atexit.register(run_exitfuncs)
1007
1008 @@ -289,15 +286,6 @@ def spawn(mycommand, env=None, opt_name=None, fd_pipes=None, returnpid=False,
1009
1010 env = os.environ if env is None else env
1011
1012 - if sys.hexversion < 0x3000000:
1013 - # Avoid a potential UnicodeEncodeError from os.execve().
1014 - env_bytes = {}
1015 - for k, v in env.items():
1016 - env_bytes[_unicode_encode(k, encoding=_encodings['content'])] = \
1017 - _unicode_encode(v, encoding=_encodings['content'])
1018 - env = env_bytes
1019 - del env_bytes
1020 -
1021 # If an absolute path to an executable file isn't given
1022 # search for it unless we've been told not to.
1023 binary = mycommand[0]
1024 @@ -964,7 +952,7 @@ def find_binary(binary):
1025 @return: full path to binary or None if the binary could not be located.
1026 """
1027 paths = os.environ.get("PATH", "")
1028 - if sys.hexversion >= 0x3000000 and isinstance(binary, bytes):
1029 + if isinstance(binary, bytes):
1030 # return bytes when input is bytes
1031 paths = paths.encode(sys.getfilesystemencoding(), 'surrogateescape')
1032 paths = paths.split(b':')
1033 diff --git a/lib/portage/proxy/objectproxy.py b/lib/portage/proxy/objectproxy.py
1034 index a755774ae..e3bf4f75a 100644
1035 --- a/lib/portage/proxy/objectproxy.py
1036 +++ b/lib/portage/proxy/objectproxy.py
1037 @@ -88,11 +88,5 @@ class ObjectProxy(object):
1038 def __bool__(self):
1039 return bool(object.__getattribute__(self, '_get_target')())
1040
1041 - if sys.hexversion < 0x3000000:
1042 - __nonzero__ = __bool__
1043 -
1044 - def __unicode__(self):
1045 - return unicode(object.__getattribute__(self, '_get_target')())
1046 -
1047 def __int__(self):
1048 return int(object.__getattribute__(self, '_get_target')())
1049 diff --git a/lib/portage/repository/config.py b/lib/portage/repository/config.py
1050 index e75b6b543..210ae3aa0 100644
1051 --- a/lib/portage/repository/config.py
1052 +++ b/lib/portage/repository/config.py
1053 @@ -530,12 +530,6 @@ class RepoConfig(object):
1054 d[k] = getattr(self, k, None)
1055 return "%s" % (d,)
1056
1057 - if sys.hexversion < 0x3000000:
1058 -
1059 - __unicode__ = __str__
1060 -
1061 - def __str__(self):
1062 - return _unicode_encode(self.__unicode__())
1063
1064 class RepoConfigLoader(object):
1065 """Loads and store config of several repositories, loaded from PORTDIR_OVERLAY or repos.conf"""
1066 diff --git a/lib/portage/tests/unicode/test_string_format.py b/lib/portage/tests/unicode/test_string_format.py
1067 index 713aca8ae..561feeea1 100644
1068 --- a/lib/portage/tests/unicode/test_string_format.py
1069 +++ b/lib/portage/tests/unicode/test_string_format.py
1070 @@ -10,8 +10,6 @@ from _emerge.DependencyArg import DependencyArg
1071 from _emerge.UseFlagDisplay import UseFlagDisplay
1072
1073
1074 -STR_IS_UNICODE = sys.hexversion >= 0x3000000
1075 -
1076 class StringFormatTestCase(TestCase):
1077 """
1078 Test that string formatting works correctly in the current interpretter,
1079 @@ -39,17 +37,9 @@ class StringFormatTestCase(TestCase):
1080 formatted_str = "%s" % (dependency_arg,)
1081 self.assertEqual(formatted_str, arg_unicode)
1082
1083 - if STR_IS_UNICODE:
1084 -
1085 - # Test the __str__ method which returns unicode in python3
1086 - formatted_str = "%s" % (dependency_arg,)
1087 - self.assertEqual(formatted_str, arg_unicode)
1088 -
1089 - else:
1090 -
1091 - # Test the __str__ method which returns encoded bytes in python2
1092 - formatted_bytes = b"%s" % (dependency_arg,)
1093 - self.assertEqual(formatted_bytes, arg_bytes)
1094 + # Test the __str__ method which returns unicode in python3
1095 + formatted_str = "%s" % (dependency_arg,)
1096 + self.assertEqual(formatted_str, arg_unicode)
1097
1098 def testPortageException(self):
1099
1100 @@ -64,17 +54,9 @@ class StringFormatTestCase(TestCase):
1101 formatted_str = "%s" % (e,)
1102 self.assertEqual(formatted_str, arg_unicode)
1103
1104 - if STR_IS_UNICODE:
1105 -
1106 - # Test the __str__ method which returns unicode in python3
1107 - formatted_str = "%s" % (e,)
1108 - self.assertEqual(formatted_str, arg_unicode)
1109 -
1110 - else:
1111 -
1112 - # Test the __str__ method which returns encoded bytes in python2
1113 - formatted_bytes = b"%s" % (e,)
1114 - self.assertEqual(formatted_bytes, arg_bytes)
1115 + # Test the __str__ method which returns unicode in python3
1116 + formatted_str = "%s" % (e,)
1117 + self.assertEqual(formatted_str, arg_unicode)
1118
1119 def testUseFlagDisplay(self):
1120
1121 @@ -90,14 +72,6 @@ class StringFormatTestCase(TestCase):
1122 formatted_str = "%s" % (e,)
1123 self.assertEqual(isinstance(formatted_str, str), True)
1124
1125 - if STR_IS_UNICODE:
1126 -
1127 - # Test the __str__ method which returns unicode in python3
1128 - formatted_str = "%s" % (e,)
1129 - self.assertEqual(isinstance(formatted_str, str), True)
1130 -
1131 - else:
1132 -
1133 - # Test the __str__ method which returns encoded bytes in python2
1134 - formatted_bytes = b"%s" % (e,)
1135 - self.assertEqual(isinstance(formatted_bytes, bytes), True)
1136 + # Test the __str__ method which returns unicode in python3
1137 + formatted_str = "%s" % (e,)
1138 + self.assertEqual(isinstance(formatted_str, str), True)
1139 diff --git a/lib/portage/util/_ShelveUnicodeWrapper.py b/lib/portage/util/_ShelveUnicodeWrapper.py
1140 deleted file mode 100644
1141 index adbd5199f..000000000
1142 --- a/lib/portage/util/_ShelveUnicodeWrapper.py
1143 +++ /dev/null
1144 @@ -1,45 +0,0 @@
1145 -# Copyright 2013 Gentoo Foundation
1146 -# Distributed under the terms of the GNU General Public License v2
1147 -
1148 -class ShelveUnicodeWrapper(object):
1149 - """
1150 - Convert unicode to str and back again, since python-2.x shelve
1151 - module doesn't support unicode.
1152 - """
1153 - def __init__(self, shelve_instance):
1154 - self._shelve = shelve_instance
1155 -
1156 - def _encode(self, s):
1157 - if isinstance(s, unicode):
1158 - s = s.encode('utf_8')
1159 - return s
1160 -
1161 - def __len__(self):
1162 - return len(self._shelve)
1163 -
1164 - def __contains__(self, k):
1165 - return self._encode(k) in self._shelve
1166 -
1167 - def __iter__(self):
1168 - return self._shelve.__iter__()
1169 -
1170 - def items(self):
1171 - return self._shelve.iteritems()
1172 -
1173 - def __setitem__(self, k, v):
1174 - self._shelve[self._encode(k)] = self._encode(v)
1175 -
1176 - def __getitem__(self, k):
1177 - return self._shelve[self._encode(k)]
1178 -
1179 - def __delitem__(self, k):
1180 - del self._shelve[self._encode(k)]
1181 -
1182 - def get(self, k, *args):
1183 - return self._shelve.get(self._encode(k), *args)
1184 -
1185 - def close(self):
1186 - self._shelve.close()
1187 -
1188 - def clear(self):
1189 - self._shelve.clear()
1190 --
1191 2.27.0

Replies