Commit c18d0dc2 authored by Julian Andres Klode's avatar Julian Andres Klode
Browse files

Remove Python 2 and old pyflakes hacks

This includes, but might not be limited to:

- explicit version checks
- try/except ImportError wrapping of typing imports
- referencing imported types like `Type  # pyflakes` because
  older pyflakes stumbled upon them only being used in `# type`
  comments
parent a4fe0b97
......@@ -26,12 +26,6 @@
from __future__ import print_function
try:
from typing import Optional
except ImportError:
pass
import errno
import os
import os.path
......@@ -43,16 +37,7 @@ import tempfile
import apt_pkg
from apt_pkg import gettext as _
if sys.version_info.major > 2:
unicode = str
try:
from typing import List, Tuple, Union
List # pyflakes
Tuple # pyflakes
Union # pyflakes
except ImportError:
pass
from typing import List, Optional, Tuple
class AptKeyError(Exception):
......@@ -106,9 +91,6 @@ def _call_apt_key_script(*args, **kwargs):
stderr=subprocess.PIPE)
stdin = kwargs.get("stdin", None)
# py2 needs this encoded, py3.3 will crash if it is
if sys.version_info.major < 3 and isinstance(stdin, unicode):
stdin = stdin.encode("utf-8") # type: ignore
output, stderr = proc.communicate(stdin) # type: str, str
......
......@@ -26,32 +26,14 @@ import os
import warnings
import weakref
try:
from typing import (Any, Callable, Dict, Iterator, List, Optional,
Set, Tuple, Union, cast, KeysView)
Any # pyflakes
Callable # pyflakes
Dict # pyflakes
Iterator # pyflakes
KeysView # pyflakes
List # pyflakes
Optional # pyflakes
Set # pyflakes
Tuple # pyflakes
Union # pyflakes
except ImportError:
def cast(typ, obj): # type: ignore
return obj
pass
from typing import (Any, Callable, Dict, Iterator, List, Optional,
Set, Tuple, Union, cast, KeysView)
import apt_pkg
from apt.package import Package, Version
import apt.progress.text
from apt.progress.base import AcquireProgress, InstallProgress, OpProgress
OpProgress # pyflakes
InstallProgress # pyflakes
AcquireProgress # pyflakes
Version # pyflakes
class FetchCancelledException(IOError):
......
......@@ -22,11 +22,7 @@
"""Classes related to cdrom handling."""
from __future__ import print_function
try:
from typing import Optional
except ImportError:
pass
from typing import Optional
import glob
import apt_pkg
......
......@@ -26,19 +26,7 @@ import gzip
import os
import sys
try:
from typing import Dict, Iterable, List, Optional, Set, Tuple, Union, cast
Dict # pyflakes
Iterable # pyflakes
List # pyflakes
Optional # pyflakes
Set # pyflakes
Tuple # pyflakes
Union # pyflakes
except ImportError:
def cast(typ, obj): # type: ignore
return obj
pass
from typing import Dict, Iterable, List, Optional, Set, Tuple, Union, cast
from apt_pkg import gettext as _
from io import BytesIO
......
......@@ -28,52 +28,14 @@ import re
import socket
import subprocess
import threading
threading # pyflakes
try:
from http.client import BadStatusLine
from urllib.error import HTTPError
from urllib.request import urlopen
except ImportError:
from httplib import BadStatusLine # type: ignore
from urllib2 import HTTPError, urlopen # type: ignore
try:
from typing import (Any, Iterable, Iterator, List, Optional, Set,
Tuple, Union, no_type_check, overload, Mapping,
Sequence)
Any # pyflakes
Iterable # pyflakes
Iterator # pyflakes
List # pyflakes
Optional # pyflakes
Set # pyflakes
Tuple # pyflakes
Union # pyflakes
overload # pyflakes
Sequence # pyflakes
except ImportError:
import collections
class GenericWrapper(object):
"""Takes a non-generic type and adds __getitem__"""
def __init__(self, value):
# type: (type) -> None
self.value = value
def __getitem__(self, key):
# type: (type) -> type
return self.value
List = GenericWrapper(list) # type: ignore
Mapping = GenericWrapper(collections.Mapping) # type: ignore
Sequence = GenericWrapper(collections.Sequence) # type: ignore
Any = None
def no_type_check(arg):
# type: (Any) -> Any
return arg
pass
from http.client import BadStatusLine
from urllib.error import HTTPError
from urllib.request import urlopen
from typing import (Any, Iterable, Iterator, List, Optional, Set,
Tuple, Union, no_type_check, Mapping,
Sequence)
import apt_pkg
import apt.progress.text
......@@ -82,17 +44,12 @@ from apt.progress.base import (
AcquireProgress,
InstallProgress,
)
AcquireProgress # pyflakes
InstallProgress # pyflakes
from apt_pkg import gettext as _
__all__ = ('BaseDependency', 'Dependency', 'Origin', 'Package', 'Record',
'Version', 'VersionList')
if sys.version_info.major >= 3:
unicode = str
def _file_is_same(path, size, hashes):
# type: (str, int, apt_pkg.HashStringList) -> bool
......@@ -636,7 +593,7 @@ class Version(object):
"Please report.") % (self.package.name)
try:
if not isinstance(dsc, unicode):
if not isinstance(dsc, str):
# Only convert where needed (i.e. Python 2.X)
dsc = dsc.decode("utf-8")
except UnicodeDecodeError as err:
......@@ -1329,7 +1286,7 @@ class Package(object):
"/%(src_pkg)s_%(src_ver)s/changelog"
else:
res = _("The list of changes is not available")
if isinstance(res, unicode):
if isinstance(res, str):
return res
else:
return res.decode("utf-8")
......@@ -1438,7 +1395,7 @@ class Package(object):
# Print an error if we failed to extract a changelog
if len(changelog) == 0:
changelog = _("The list of changes is not available")
if not isinstance(changelog, unicode):
if not isinstance(changelog, str):
changelog = changelog.decode("utf-8")
self._changelog = changelog
......@@ -1452,14 +1409,14 @@ class Package(object):
"later.") % (src_pkg, src_ver)
else:
res = _("The list of changes is not available")
if isinstance(res, unicode):
if isinstance(res, str):
return res
else:
return res.decode("utf-8")
except (IOError, BadStatusLine):
res = _("Failed to download the list of changes. \nPlease "
"check your Internet connection.")
if isinstance(res, unicode):
if isinstance(res, str):
return res
else:
return res.decode("utf-8")
......
......@@ -25,11 +25,7 @@ for terminals, etc.
from __future__ import print_function
try:
from typing import Sequence
Sequence # pylint
except ImportError:
pass
from typing import Sequence
__all__ = [] # type: Sequence[str]
......@@ -26,19 +26,13 @@ from __future__ import print_function
import errno
import fcntl
import io
import os
import re
import select
import sys
try:
from typing import Optional, Union
import io
io # pyflakes
Optional # pyflakes
Union # pyflakes
except ImportError:
pass
from typing import Optional, Union
import apt_pkg
......
......@@ -22,31 +22,16 @@ import os
import signal
import sys
try:
import types
from typing import Callable, Optional, Union
types # pyflakes
Callable # pyflakes
Optional # pyflakes
Union # pyflakes
except ImportError:
pass
import types
from typing import Callable, Optional, Union
import apt_pkg
from apt.progress import base
io # pyflakes
__all__ = ['AcquireProgress', 'CdromProgress', 'OpProgress']
if sys.version_info.major >= 3:
raw_input = input # pyflakes
long = int
else:
input = raw_input
def _(msg):
# type: (str) -> str
......@@ -122,7 +107,7 @@ class AcquireProgress(base.AcquireProgress, TextProgress):
base.AcquireProgress.__init__(self)
self._signal = None # type: Union[Callable[[signal.Signals, types.FrameType], None], int, signal.Handlers, None] # noqa
self._width = 80
self._id = long(1)
self._id = 1
def start(self):
# type: () -> None
......@@ -135,7 +120,7 @@ class AcquireProgress(base.AcquireProgress, TextProgress):
self._signal = signal.signal(signal.SIGWINCH, self._winch)
# Get the window size.
self._winch()
self._id = long(1)
self._id = 1
def _winch(self, *dummy):
# type: (object) -> None
......@@ -201,7 +186,7 @@ class AcquireProgress(base.AcquireProgress, TextProgress):
tval = '%i%%' % percent
end = ""
if self.current_cps:
eta = long(float(self.total_bytes - self.current_bytes) /
eta = int(float(self.total_bytes - self.current_bytes) /
self.current_cps)
end = " %sB/s %s" % (apt_pkg.size_to_str(self.current_cps),
apt_pkg.time_to_str(eta))
......
......@@ -21,20 +21,11 @@ from __future__ import print_function
import datetime
import os
try:
from typing import Optional, Tuple
Optional # pyflakes
Tuple # pyflakes
except ImportError:
pass
from typing import Optional, Tuple
import apt
import apt_pkg
apt # pyflakes
datetime # pyflakes
os # pyflakes
def get_maintenance_end_date(release_date, m_months):
# type: (datetime.datetime, int) -> Tuple[int, int]
......
......@@ -73,9 +73,7 @@ except KeyError:
p1 = Popen(["dpkg-parsechangelog", "-l../../debian/changelog"],
stdout=PIPE)
p2 = Popen(["sed", "-n", 's/^Version: //p'], stdin=p1.stdout, stdout=PIPE)
release = p2.communicate()[0]
if sys.version_info.major >= 3:
release = release.decode("utf-8")
release = p2.communicate()[0].decode("utf-8")
# Handle the alpha release scheme
......
......@@ -12,15 +12,8 @@ import tempfile
import time
import unittest
if sys.version_info[0] > 2:
from http.server import HTTPServer
from http.server import SimpleHTTPRequestHandler as HTTPRequestHandler
HTTPServer # pyflakes
HTTPRequestHandler # pyflakes
else:
from BaseHTTPServer import HTTPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler as HTTPRequestHandler
from http.server import HTTPServer
from http.server import SimpleHTTPRequestHandler as HTTPRequestHandler
import apt_pkg
import apt.auth
......
......@@ -11,7 +11,6 @@ Unit tests to verify the correctness of Hashes, HashString and the various
functions like md5sum."""
import unittest
import hashlib
import sys
import warnings
import apt_pkg
......@@ -84,16 +83,10 @@ class TestHashes(testcommon.TestCase):
def test_unicode(self):
"""hashes: Test apt_pkg.Hashes(unicode)."""
if sys.version_info[0] == 3:
self.assertRaises(TypeError, apt_pkg.Hashes, "D")
self.assertRaises(TypeError, apt_pkg.md5sum, "D")
self.assertRaises(TypeError, apt_pkg.sha1sum, "D")
self.assertRaises(TypeError, apt_pkg.sha256sum, "D")
else:
self.assertRaises(TypeError, apt_pkg.Hashes, u"")
self.assertRaises(TypeError, apt_pkg.md5sum, u"")
self.assertRaises(TypeError, apt_pkg.sha1sum, u"")
self.assertRaises(TypeError, apt_pkg.sha256sum, u"")
self.assertRaises(TypeError, apt_pkg.Hashes, "D")
self.assertRaises(TypeError, apt_pkg.md5sum, "D")
self.assertRaises(TypeError, apt_pkg.sha1sum, "D")
self.assertRaises(TypeError, apt_pkg.sha256sum, "D")
class TestHashString(testcommon.TestCase):
......@@ -131,8 +124,7 @@ class TestHashString(testcommon.TestCase):
def test_wrong(self):
"""hashes: Test apt_pkg.HashString(wrong_type)."""
self.assertRaises(TypeError, apt_pkg.HashString, 0)
if sys.version_info[0] == 3:
self.assertRaises(TypeError, apt_pkg.HashString, bytes())
self.assertRaises(TypeError, apt_pkg.HashString, bytes())
class TestHashStringList(testcommon.TestCase):
......
......@@ -3,7 +3,6 @@
import apt_pkg
import os
import sys
import unittest
......@@ -29,14 +28,3 @@ class TestCase(unittest.TestCase):
# Restore default values
apt_pkg.config["Dir::Etc::main"] = "apt.conf"
apt_pkg.config["Dir::Etc::parts"] = "apt.conf.d"
if (sys.version_info.major, sys.version_info.minor) < (3, 2):
def assertRaisesRegex(self, exc_typ, regex, func, *args, **kwds):
"""Compatibility helper"""
try:
func(*args, **kwds)
except Exception as exc:
self.assertIsInstance(exc, exc_typ)
self.assertRegexpMatches(str(exc), regex)
else:
self.fail("Did not raise exception")
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment