about summary refs log tree commit diff stats
diff options
context:
space:
mode:
authortoonn <toonn@toonn.io>2020-06-29 20:01:39 +0200
committertoonn <toonn@toonn.io>2020-06-29 20:12:20 +0200
commite2cd95df0bb632adcc84674d05031630fe5a589c (patch)
tree404b23bc84730545ec076c50c5cac217ff772df8
parent84a1ff6c66d7f4d4a713d432e01aa9272f0d2765 (diff)
downloadranger-e2cd95df0bb632adcc84674d05031630fe5a589c.tar.gz
Factor out python 3 version checking
We check whether we're running python 2 or 3 in many places. In some
places we do more specific version checks but with the new `PY3`
constant modeled after `six` this code should be slightly more readable.
-rw-r--r--ranger/__init__.py2
-rwxr-xr-xranger/config/commands.py15
-rw-r--r--ranger/container/file.py4
-rw-r--r--ranger/container/tags.py5
-rw-r--r--ranger/core/actions.py10
-rw-r--r--ranger/core/fm.py1
-rw-r--r--ranger/core/loader.py11
-rw-r--r--ranger/core/main.py4
-rw-r--r--ranger/core/tab.py6
-rw-r--r--ranger/ext/img_display.py3
-rw-r--r--ranger/gui/bar.py2
-rw-r--r--ranger/gui/widgets/console.py8
12 files changed, 34 insertions, 37 deletions
diff --git a/ranger/__init__.py b/ranger/__init__.py
index 4dee1e91..b2d99115 100644
--- a/ranger/__init__.py
+++ b/ranger/__init__.py
@@ -11,6 +11,7 @@ program you want to use to open your files with.
 from __future__ import (absolute_import, division, print_function)
 
 import os
+from sys import version_info
 
 
 # Version helper
@@ -50,6 +51,7 @@ MACRO_DELIMITER_ESC = '%%'
 DEFAULT_PAGER = 'less'
 USAGE = '%prog [options] [path]'
 VERSION = version_helper()
+PY3 = version_info[0] >= 3
 
 # These variables are ignored if the corresponding
 # XDG environment variable is non-empty and absolute
diff --git a/ranger/config/commands.py b/ranger/config/commands.py
index 5defa677..ca9d4c32 100755
--- a/ranger/config/commands.py
+++ b/ranger/config/commands.py
@@ -95,6 +95,7 @@ from collections import deque
 import os
 import re
 
+from ranger import PY3
 from ranger.api.commands import Command
 
 
@@ -852,11 +853,10 @@ class load_copy_buffer(Command):
     copy_buffer_filename = 'copy_buffer'
 
     def execute(self):
-        import sys
         from ranger.container.file import File
         from os.path import exists
         fname = self.fm.datapath(self.copy_buffer_filename)
-        unreadable = IOError if sys.version_info[0] < 3 else OSError
+        unreadable = OSError if PY3 else IOError
         try:
             fobj = open(fname, 'r')
         except unreadable:
@@ -878,10 +878,9 @@ class save_copy_buffer(Command):
     copy_buffer_filename = 'copy_buffer'
 
     def execute(self):
-        import sys
         fname = None
         fname = self.fm.datapath(self.copy_buffer_filename)
-        unwritable = IOError if sys.version_info[0] < 3 else OSError
+        unwritable = OSError if PY3 else IOError
         try:
             fobj = open(fname, 'w')
         except unwritable:
@@ -1126,24 +1125,22 @@ class bulkrename(Command):
 
     def execute(self):
         # pylint: disable=too-many-locals,too-many-statements,too-many-branches
-        import sys
         import tempfile
         from ranger.container.file import File
         from ranger.ext.shell_escape import shell_escape as esc
-        py3 = sys.version_info[0] >= 3
 
         # Create and edit the file list
         filenames = [f.relative_path for f in self.fm.thistab.get_selection()]
         with tempfile.NamedTemporaryFile(delete=False) as listfile:
             listpath = listfile.name
-            if py3:
+            if PY3:
                 listfile.write("\n".join(filenames).encode(
                     encoding="utf-8", errors="surrogateescape"))
             else:
                 listfile.write("\n".join(filenames))
         self.fm.execute_file([File(listpath)], app='editor')
         with (open(listpath, 'r', encoding="utf-8", errors="surrogateescape") if
-              py3 else open(listpath, 'r')) as listfile:
+              PY3 else open(listpath, 'r')) as listfile:
             new_filenames = listfile.read().split("\n")
         os.unlink(listpath)
         if all(a == b for a, b in zip(filenames, new_filenames)):
@@ -1170,7 +1167,7 @@ class bulkrename(Command):
                         old=esc(old), new=esc(new)))
             # Make sure not to forget the ending newline
             script_content = "\n".join(script_lines) + "\n"
-            if py3:
+            if PY3:
                 cmdfile.write(script_content.encode(encoding="utf-8",
                                                     errors="surrogateescape"))
             else:
diff --git a/ranger/container/file.py b/ranger/container/file.py
index 6450cfe6..9477abe7 100644
--- a/ranger/container/file.py
+++ b/ranger/container/file.py
@@ -4,13 +4,13 @@
 from __future__ import (absolute_import, division, print_function)
 
 import re
-import sys
 
+from ranger import PY3
 from ranger.container.fsobject import FileSystemObject
 
 N_FIRST_BYTES = 256
 CONTROL_CHARACTERS = set(list(range(0, 9)) + list(range(14, 32)))
-if sys.version_info[0] < 3:
+if not PY3:
     CONTROL_CHARACTERS = set(chr(n) for n in CONTROL_CHARACTERS)
 
 # Don't even try to preview files which match this regular expression:
diff --git a/ranger/container/tags.py b/ranger/container/tags.py
index dabaf6a8..ed5b876a 100644
--- a/ranger/container/tags.py
+++ b/ranger/container/tags.py
@@ -7,7 +7,8 @@ from __future__ import (absolute_import, division, print_function)
 
 from os.path import isdir, exists, dirname, abspath, realpath, expanduser, sep
 import string
-import sys
+
+from ranger import PY3
 
 ALLOWED_KEYS = string.ascii_letters + string.digits + string.punctuation
 
@@ -72,7 +73,7 @@ class Tags(object):
 
     def sync(self):
         try:
-            if sys.version_info[0] >= 3:
+            if PY3:
                 fobj = open(self._filename, 'r', errors='replace')
             else:
                 fobj = open(self._filename, 'r')
diff --git a/ranger/core/actions.py b/ranger/core/actions.py
index c3d7de86..13337561 100644
--- a/ranger/core/actions.py
+++ b/ranger/core/actions.py
@@ -17,10 +17,10 @@ import tempfile
 from inspect import cleandoc
 from stat import S_IEXEC
 from hashlib import sha1
-from sys import version_info
 from logging import getLogger
 
 import ranger
+from ranger import PY3
 from ranger.ext.direction import Direction
 from ranger.ext.relative_symlink import relative_symlink
 from ranger.ext.keybinding_parser import key_to_string, construct_keybinding
@@ -1050,10 +1050,10 @@ class Actions(  # pylint: disable=too-many-instance-attributes,too-many-public-m
 
     @staticmethod
     def sha1_encode(path):
-        if version_info[0] < 3:
-            return os.path.join(ranger.args.cachedir, sha1(path).hexdigest()) + '.jpg'
-        return os.path.join(ranger.args.cachedir,
-                            sha1(path.encode('utf-8', 'backslashreplace')).hexdigest()) + '.jpg'
+        if PY3:
+            return os.path.join(ranger.args.cachedir, sha1(path.encode(
+                'utf-8', 'backslashreplace')).hexdigest()) + '.jpg'
+        return os.path.join(ranger.args.cachedir, sha1(path).hexdigest()) + '.jpg'
 
     def get_preview(self, fobj, width, height):  # pylint: disable=too-many-return-statements
         pager = self.ui.get_pager()
diff --git a/ranger/core/fm.py b/ranger/core/fm.py
index 7d23c9b6..9461e325 100644
--- a/ranger/core/fm.py
+++ b/ranger/core/fm.py
@@ -55,7 +55,6 @@ class FM(Actions,  # pylint: disable=too-many-instance-attributes
         self.tabs = {}
         self.tags = tags
         self.restorable_tabs = deque([], ranger.MAX_RESTORABLE_TABS)
-        self.py3 = sys.version_info >= (3, )
         self.previews = {}
         self.default_linemodes = deque()
         self.loader = Loader()
diff --git a/ranger/core/loader.py b/ranger/core/loader.py
index 7d4b21e8..dcee568a 100644
--- a/ranger/core/loader.py
+++ b/ranger/core/loader.py
@@ -9,7 +9,6 @@ from time import time, sleep
 import math
 import os.path
 import select
-import sys
 import errno
 
 try:
@@ -18,6 +17,7 @@ try:
 except ImportError:
     HAVE_CHARDET = False
 
+from ranger import PY3
 from ranger.core.shared import FileManagerAware
 from ranger.ext.safe_path import get_safe_path
 from ranger.ext.signals import SignalDispatcher
@@ -171,14 +171,13 @@ class CommandLoader(  # pylint: disable=too-many-instance-attributes
         self.popenArgs = popenArgs  # pylint: disable=invalid-name
 
     def generate(self):  # pylint: disable=too-many-branches,too-many-statements
-        py3 = sys.version_info[0] >= 3
         popenargs = {} if self.popenArgs is None else self.popenArgs
         popenargs['stdout'] = popenargs['stderr'] = PIPE
         popenargs['stdin'] = PIPE if self.input else open(os.devnull, 'r')
         self.process = process = Popen(self.args, **popenargs)
         self.signal_emit('before', process=process, loader=self)
         if self.input:
-            if py3:
+            if PY3:
                 import io
                 stdin = io.TextIOWrapper(process.stdin)
             else:
@@ -212,7 +211,7 @@ class CommandLoader(  # pylint: disable=too-many-instance-attributes
                         robjs = robjs[0]
                         if robjs == process.stderr:
                             read = robjs.readline()
-                            if py3:
+                            if PY3:
                                 read = safe_decode(read)
                             if read:
                                 self.fm.notify(read, bad=True)
@@ -227,7 +226,7 @@ class CommandLoader(  # pylint: disable=too-many-instance-attributes
                     sleep(0.03)
             if not self.silent:
                 for line in process.stderr:
-                    if py3:
+                    if PY3:
                         line = safe_decode(line)
                     self.fm.notify(line, bad=True)
             if self.read:
@@ -235,7 +234,7 @@ class CommandLoader(  # pylint: disable=too-many-instance-attributes
                 if read:
                     read_stdout += read
             if read_stdout:
-                if py3:
+                if PY3:
                     read_stdout = safe_decode(read_stdout)
                 self.stdout_buffer += read_stdout
         self.finished = True
diff --git a/ranger/core/main.py b/ranger/core/main.py
index 5f7abaca..f3cd30c1 100644
--- a/ranger/core/main.py
+++ b/ranger/core/main.py
@@ -13,7 +13,7 @@ import shutil
 import sys
 import tempfile
 
-from ranger import VERSION
+from ranger import PY3, VERSION
 
 
 LOG = getLogger(__name__)
@@ -74,7 +74,7 @@ def main(
             return 1
         fm = FM()
         try:
-            if sys.version_info[0] >= 3:
+            if PY3:
                 fobj = open(fm.datapath('tagged'), 'r', errors='replace')
             else:
                 fobj = open(fm.datapath('tagged'), 'r')
diff --git a/ranger/core/tab.py b/ranger/core/tab.py
index 1d5e69d4..6a6cce73 100644
--- a/ranger/core/tab.py
+++ b/ranger/core/tab.py
@@ -5,8 +5,8 @@ from __future__ import (absolute_import, division, print_function)
 
 import os
 from os.path import abspath, normpath, join, expanduser, isdir
-import sys
 
+from ranger import PY3
 from ranger.container import settings
 from ranger.container.history import History
 from ranger.core.shared import FileManagerAware, SettingsAware
@@ -27,9 +27,9 @@ class Tab(FileManagerAware, SettingsAware):  # pylint: disable=too-many-instance
         # "==", and this breaks _set_thisfile_from_signal and _on_tab_change.
         self.fm.signal_bind('move', self._set_thisfile_from_signal,
                             priority=settings.SIGNAL_PRIORITY_AFTER_SYNC,
-                            weak=(sys.version_info[0] >= 3))
+                            weak=(PY3))
         self.fm.signal_bind('tab.change', self._on_tab_change,
-                            weak=(sys.version_info[0] >= 3))
+                            weak=(PY3))
 
     def _set_thisfile_from_signal(self, signal):
         if self == signal.tab:
diff --git a/ranger/ext/img_display.py b/ranger/ext/img_display.py
index ffaa4c07..105d55df 100644
--- a/ranger/ext/img_display.py
+++ b/ranger/ext/img_display.py
@@ -30,6 +30,7 @@ from contextlib import contextmanager
 import codecs
 from tempfile import NamedTemporaryFile
 
+from ranger import PY3
 from ranger.core.shared import FileManagerAware
 
 W3MIMGDISPLAY_ENV = "W3MIMGDISPLAY_PATH"
@@ -359,7 +360,7 @@ class ITerm2ImageDisplayer(ImageDisplayer, FileManagerAware):
         elif image_type == 'gif':
             width, height = struct.unpack('<HH', file_header[6:10])
         elif image_type == 'jpeg':
-            unreadable = IOError if sys.version_info[0] < 3 else OSError
+            unreadable = OSError if PY3 else IOError
             try:
                 file_handle.seek(0)
                 size = 2
diff --git a/ranger/gui/bar.py b/ranger/gui/bar.py
index b02861b6..88bf55eb 100644
--- a/ranger/gui/bar.py
+++ b/ranger/gui/bar.py
@@ -3,8 +3,6 @@
 
 from __future__ import (absolute_import, division, print_function)
 
-import sys
-
 from ranger import PY3
 from ranger.ext.widestring import WideString, utf_char_width
 
diff --git a/ranger/gui/widgets/console.py b/ranger/gui/widgets/console.py
index d796058c..bf8a12c0 100644
--- a/ranger/gui/widgets/console.py
+++ b/ranger/gui/widgets/console.py
@@ -317,13 +317,13 @@ class Console(Widget):  # pylint: disable=too-many-instance-attributes,too-many-
         """
         Returns a new position by moving word-wise in the line
 
-        >>> import sys
-        >>> if sys.version_info < (3, ):
+        >>> from ranger import PY3
+        >>> if PY3:
+        ...     line = "\\u30AA\\u30CF\\u30E8\\u30A6 world,  this is dog"
+        ... else:
         ...     # Didn't get the unicode test to work on python2, even though
         ...     # it works fine in ranger, even with unicode input...
         ...     line = "ohai world,  this is dog"
-        ... else:
-        ...     line = "\\u30AA\\u30CF\\u30E8\\u30A6 world,  this is dog"
         >>> Console.move_by_word(line, 0, -1)
         0
         >>> Console.move_by_word(line, 0, 1)