[diffoscope] 05/07: Split exceptions out into dedicated diffoscope.exc module.

Chris Lamb chris at chris-lamb.co.uk
Mon Aug 15 21:55:54 CEST 2016


This is an automated email from the git hooks/post-receive script.

lamby pushed a commit to branch master
in repository diffoscope.

commit 9d2e7b0d7faead42286f76b83c9c654bc26802d8
Author: Chris Lamb <lamby at debian.org>
Date:   Mon Aug 15 20:49:15 2016 +0100

    Split exceptions out into dedicated diffoscope.exc module.
    
    Signed-off-by: Chris Lamb <lamby at debian.org>
---
 diffoscope/__init__.py              | 190 +-----------------------------------
 diffoscope/comparators/binary.py    |   5 +-
 diffoscope/comparators/directory.py |   3 +-
 diffoscope/comparators/elf.py       |   4 +-
 diffoscope/comparators/ps.py        |   3 +-
 diffoscope/difference.py            |   3 +-
 diffoscope/{__init__.py => exc.py}  | 130 ++----------------------
 diffoscope/main.py                  |   4 +-
 tests/comparators/test_binary.py    |   5 +-
 9 files changed, 24 insertions(+), 323 deletions(-)

diff --git a/diffoscope/__init__.py b/diffoscope/__init__.py
index 9837445..e5c80c6 100644
--- a/diffoscope/__init__.py
+++ b/diffoscope/__init__.py
@@ -42,195 +42,6 @@ OS_NAMES = {
     'FreeBSD': 'FreeBSD',
 }
 
-class RequiredToolNotFound(Exception):
-    PROVIDERS = {
-        'bzip2': {
-            'debian': 'bzip2',
-            'arch': 'bzip2',
-        },
-        'cbfstool': {
-        },
-        'cd-iccdump': {
-            'debian': 'colord',
-            'arch': 'colord',
-            'FreeBSD': 'colord',
-        },
-        'cmp': {
-            'debian': 'diffutils',
-            'arch': 'diffutils',
-        },
-        'cpio': {
-            'debian': 'cpio',
-            'arch': 'cpio',
-        },
-        'diff': {
-            'debian': 'diffutils',
-            'arch': 'diffutils',
-        },
-        'enjarify': {
-            'debian': 'enjarify',
-            'arch': 'enjarify',
-        },
-        'file': {
-            'debian': 'file',
-            'arch': 'file',
-        },
-        'find': {
-            'debian': 'findutils',
-            'arch': 'findutils',
-        },
-        'getfacl': {
-            'debian': 'acl',
-            'arch': 'acl',
-        },
-        'ghc': {
-            'debian': 'ghc',
-            'arch': 'ghc',
-            'FreeBSD': 'ghc',
-        },
-        'gpg': {
-            'debian': 'gnupg',
-            'arch': 'gnupg',
-            'FreeBSD': 'gnupg',
-        },
-        'gzip': {
-            'debian': 'gzip',
-            'arch': 'gzip',
-        },
-        'img2txt': {
-            'debian': 'caca-utils',
-            'arch': 'libcaca',
-            'FreeBSD': 'libcaca',
-        },
-        'isoinfo': {
-            'debian': 'genisoimage',
-            'arch': 'cdrkit',
-            'FreeBSD': 'cdrtools',
-        },
-        'javap': {
-            'debian': 'default-jdk-headless | java-sdk',
-            'arch': 'java-environment',
-        },
-        'llvm-bcanalyzer': {
-            'debian': 'llvm',
-            'arch': 'llvm',
-        },
-        'llvm-config': {
-            'debian': 'llvm',
-            'arch': 'llvm',
-        },
-        'llvm-dis': {
-            'debian': 'llvm',
-            'arch': 'llvm',
-        },
-        'ls': {
-            'debian': 'coreutils',
-            'arch': 'coreutils',
-        },
-        'lsattr': {
-            'debian': 'e2fsprogs',
-            'arch': 'e2fsprogs',
-            'FreeBSD': 'e2fsprogs',
-        },
-        'msgunfmt': {
-            'debian': 'gettext',
-            'arch': 'gettext',
-            'FreeBSD': 'gettext-tools',
-        },
-        'nm': {
-            'debian': 'binutils-multiarch',
-            'arch': 'binutils',
-        },
-        'objdump': {
-            'debian': 'binutils-multiarch',
-            'arch': 'binutils',
-        },
-        'pdftk': {
-            'debian': 'pdftk',
-            'FreeBSD': 'pdftk',
-        },
-        'pdftotext': {
-            'debian': 'poppler-utils',
-            'arch': 'poppler',
-            'FreeBSD': 'poppler-utils',
-        },
-        'pedump': {
-            'debian': 'mono-utils',
-            'arch': 'mono-tools',
-            'FreeBSD': 'mono',
-        },
-        'ppudump': {
-            'debian': 'fp-utils',
-            'arch': 'fpc',
-            'FreeBSD': 'fpc',
-        },
-        'ps2ascii': {
-            'debian': 'ghostscript',
-            'arch': 'ghostscript',
-            'FreeBSD': 'ghostscript9-base',
-        },
-        'readelf': {
-            'debian': 'binutils-multiarch',
-            'arch': 'binutils',
-        },
-        'rpm2cpio': {
-            'debian': 'rpm2cpio',
-            'arch': 'rpmextract',
-            'FreeBSD': 'rpm2cpio',
-        },
-        'showttf': {
-            'debian': 'fontforge-extras',
-        },
-        'sng': {
-            'debian': 'sng',
-        },
-        'stat': {
-            'debian': 'coreutils',
-            'arch': 'coreutils',
-        },
-        'sqlite3': {
-            'debian': 'sqlite3',
-            'arch': 'sqlite',
-            'FreeBSD': 'sqlite3',
-        },
-        'tar': {
-            'debian': 'tar',
-            'arch': 'tar',
-        },
-        'unsquashfs': {
-            'debian': 'squashfs-tools',
-            'arch': 'squashfs-tools',
-            'FreeBSD': 'squashfs-tools',
-        },
-        'xxd': {
-            'debian': 'vim-common',
-            'arch': 'vim',
-            'FreeBSD': 'vim | vim-lite',
-        },
-        'xz': {
-            'debian': 'xz-utils',
-            'arch': 'xz',
-        },
-        'zipinfo': {
-            'debian': 'unzip',
-            'arch': 'unzip',
-            'FreeBSD': 'unzip',
-        },
-    }
-
-    def __init__(self, command):
-        self.command = command
-
-    def get_package(self):
-        providers = RequiredToolNotFound.PROVIDERS.get(self.command, None)
-        if not providers:
-            return None
-        return providers.get(get_current_os(), None)
-
-class OutputParsingError(Exception):
-    def __init__(self, command, object):
-        self.command = command
-        self.object_class = object.__class__
 
 def get_current_os():
     system = platform.system()
@@ -254,6 +65,7 @@ def tool_required(command):
         else:
             @functools.wraps(original_function)
             def tool_check(*args, **kwargs):
+                from .exc import RequiredToolNotFound
                 raise RequiredToolNotFound(command)
         return tool_check
     return wrapper
diff --git a/diffoscope/comparators/binary.py b/diffoscope/comparators/binary.py
index 6a9a8e1..55b152e 100644
--- a/diffoscope/comparators/binary.py
+++ b/diffoscope/comparators/binary.py
@@ -26,8 +26,8 @@ import magic
 import binascii
 import subprocess
 
-from diffoscope import tool_required, RequiredToolNotFound, logger, \
-    OutputParsingError
+from diffoscope import tool_required, logger
+from diffoscope.exc import OutputParsingError, RequiredToolNotFound
 from diffoscope.config import Config
 from diffoscope.difference import Difference
 
@@ -54,6 +54,7 @@ def hexdump_fallback(path):
 
 def compare_binary_files(file1, file2, source=None):
     import diffoscope.comparators.utils
+
     try:
         return Difference.from_command(diffoscope.comparators.utils.Xxd, file1.path, file2.path, source=[file1.name, file2.name])
     except RequiredToolNotFound:
diff --git a/diffoscope/comparators/directory.py b/diffoscope/comparators/directory.py
index 856a0e9..cec01cb 100644
--- a/diffoscope/comparators/directory.py
+++ b/diffoscope/comparators/directory.py
@@ -23,7 +23,8 @@ import subprocess
 
 import diffoscope.comparators
 
-from diffoscope import logger, tool_required, RequiredToolNotFound
+from diffoscope import logger, tool_required
+from diffoscope.exc import RequiredToolNotFound
 from diffoscope.difference import Difference
 from diffoscope.comparators.utils import Container, Command
 from diffoscope.comparators.binary import FilesystemFile
diff --git a/diffoscope/comparators/elf.py b/diffoscope/comparators/elf.py
index 84d74fe..4cb0fca 100644
--- a/diffoscope/comparators/elf.py
+++ b/diffoscope/comparators/elf.py
@@ -22,8 +22,8 @@ import os.path
 import subprocess
 import collections
 
-from diffoscope import tool_required, OutputParsingError, logger, \
-    get_named_temporary_file
+from diffoscope import tool_required, logger, get_named_temporary_file
+from diffoscope.exc import OutputParsingError
 from diffoscope.difference import Difference
 from diffoscope.comparators.deb import DebFile, get_build_id_map
 from diffoscope.comparators.utils import Command, Container
diff --git a/diffoscope/comparators/ps.py b/diffoscope/comparators/ps.py
index f0dd02b..9fa1113 100644
--- a/diffoscope/comparators/ps.py
+++ b/diffoscope/comparators/ps.py
@@ -19,7 +19,8 @@
 
 import re
 
-from diffoscope import tool_required, RequiredToolNotFound, logger
+from diffoscope import tool_required, logger
+from diffoscope.exc import RequiredToolNotFound
 from diffoscope.difference import Difference
 from diffoscope.comparators.text import TextFile
 from diffoscope.comparators.utils import Command
diff --git a/diffoscope/difference.py b/diffoscope/difference.py
index 21ccc24..b2ed8a7 100644
--- a/diffoscope/difference.py
+++ b/diffoscope/difference.py
@@ -28,7 +28,8 @@ import subprocess
 
 from multiprocessing.dummy import Queue
 
-from diffoscope import logger, tool_required, RequiredToolNotFound
+from diffoscope import logger, tool_required
+from diffoscope.exc import RequiredToolNotFound
 from diffoscope.config import Config
 
 
diff --git a/diffoscope/__init__.py b/diffoscope/exc.py
similarity index 57%
copy from diffoscope/__init__.py
copy to diffoscope/exc.py
index 9837445..1d5a433 100644
--- a/diffoscope/__init__.py
+++ b/diffoscope/exc.py
@@ -1,46 +1,7 @@
-# -*- coding: utf-8 -*-
-#
-# diffoscope: in-depth comparison of files, archives, and directories
-#
-# Copyright © 2014-2015 Jérémy Bobbio <lunar at debian.org>
-#
-# diffoscope is free software: you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation, either version 3 of the License, or
-# (at your option) any later version.
-#
-# diffoscope is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with diffoscope.  If not, see <http://www.gnu.org/licenses/>.
-
-import os
-import shutil
-import logging
-import platform
-import tempfile
-import functools
-
-from distutils.spawn import find_executable
-
-VERSION = "59"
-
-logger = logging.getLogger("diffoscope")
-logger.setLevel(logging.WARNING)
-ch = logging.StreamHandler()
-ch.setLevel(logging.DEBUG)
-logger.addHandler(ch)
-formatter = logging.Formatter('%(levelname)8s %(message)s')
-ch.setFormatter(formatter)
-
-OS_NAMES = {
-    'arch': 'Arch Linux',
-    'debian': 'Debian',
-    'FreeBSD': 'FreeBSD',
-}
+class OutputParsingError(Exception):
+    def __init__(self, command, object):
+        self.command = command
+        self.object_class = object.__class__
 
 class RequiredToolNotFound(Exception):
     PROVIDERS = {
@@ -222,88 +183,9 @@ class RequiredToolNotFound(Exception):
         self.command = command
 
     def get_package(self):
+        from . import get_current_os
+
         providers = RequiredToolNotFound.PROVIDERS.get(self.command, None)
         if not providers:
             return None
         return providers.get(get_current_os(), None)
-
-class OutputParsingError(Exception):
-    def __init__(self, command, object):
-        self.command = command
-        self.object_class = object.__class__
-
-def get_current_os():
-    system = platform.system()
-    if system == "Linux":
-        # FIXME: Will break under Python 3.7, see:
-        # https://docs.python.org/3/library/platform.html#platform.linux_distribution
-        return platform.linux_distribution()[0]
-    return system
-
-
-# decorator that checks if the specified tool is installed
-def tool_required(command):
-    if not hasattr(tool_required, 'all'):
-        tool_required.all = set()
-    tool_required.all.add(command)
-    def wrapper(original_function):
-        if find_executable(command):
-            @functools.wraps(original_function)
-            def tool_check(*args, **kwargs):
-                return original_function(*args, **kwargs)
-        else:
-            @functools.wraps(original_function)
-            def tool_check(*args, **kwargs):
-                raise RequiredToolNotFound(command)
-        return tool_check
-    return wrapper
-
-
-def set_locale():
-    """Normalize locale so external tool gives us stable and properly
-    encoded output"""
-
-    for var in ['LANGUAGE', 'LC_ALL']:
-        if var in os.environ:
-            del os.environ[var]
-    for var in ['LANG', 'LC_NUMERIC', 'LC_TIME', 'LC_COLLATE', 'LC_MONETARY',
-                'LC_MESSAGES', 'LC_PAPER', 'LC_NAME', 'LC_ADDRESS',
-                'LC_TELEPHONE', 'LC_MEASUREMENT', 'LC_IDENTIFICATION']:
-        os.environ[var] = 'C'
-    os.environ['LC_CTYPE'] = 'C.UTF-8'
-    os.environ['TZ'] = 'UTC'
-
-
-temp_files = []
-temp_dirs = []
-
-
-def get_named_temporary_file(*args, **kwargs):
-    if 'suffix' not in kwargs:
-        kwargs['suffix'] = '_diffoscope'
-    f = tempfile.NamedTemporaryFile(*args, **kwargs)
-    temp_files.append(f.name)
-    return f
-
-
-def get_temporary_directory(*args, **kwargs):
-    if 'suffix' not in kwargs:
-        kwargs['suffix'] = '_diffoscope'
-    d = tempfile.TemporaryDirectory(*args, **kwargs)
-    temp_dirs.append(d)
-    return d
-
-
-def clean_all_temp_files():
-    for temp_file in temp_files:
-        try:
-            os.unlink(temp_file)
-        except FileNotFoundError:
-            pass
-        except:
-            logger.exception('Unable to delete %s', temp_file)
-    for temp_dir in temp_dirs:
-        try:
-            temp_dir.cleanup()
-        except:
-            logger.exception('Unable to delete %s', temp_dir)
diff --git a/diffoscope/main.py b/diffoscope/main.py
index 25e8db3..7cd234a 100644
--- a/diffoscope/main.py
+++ b/diffoscope/main.py
@@ -31,6 +31,7 @@ import contextlib
 import diffoscope.comparators
 
 from diffoscope import logger, VERSION, set_locale, clean_all_temp_files
+from diffoscope.exc import RequiredToolNotFound
 from diffoscope.config import Config
 from diffoscope.presenters.html import output_html, output_html_directory, \
     JQUERY_SYSTEM_LOCATIONS
@@ -134,7 +135,8 @@ class RangeCompleter(object):
 
 class ListToolsAction(argparse.Action):
     def __call__(self, parser, namespace, os_override, option_string=None):
-        from diffoscope import tool_required, RequiredToolNotFound, OS_NAMES, get_current_os
+        from diffoscope import tool_required, OS_NAMES, get_current_os
+
         print("External-Tools-Required: ", end='')
         print(', '.join(sorted(tool_required.all)))
         if os_override:
diff --git a/tests/comparators/test_binary.py b/tests/comparators/test_binary.py
index f3b3ec2..37d7ea2 100644
--- a/tests/comparators/test_binary.py
+++ b/tests/comparators/test_binary.py
@@ -22,7 +22,8 @@ import subprocess
 
 import diffoscope.comparators.binary
 
-from diffoscope import RequiredToolNotFound, tool_required
+from diffoscope import tool_required
+from diffoscope.exc import RequiredToolNotFound
 from diffoscope.difference import Difference
 from diffoscope.comparators import specialize
 from diffoscope.comparators.binary import File, FilesystemFile, NonExistingFile
@@ -133,7 +134,7 @@ def test_with_compare_details_and_failed_process():
 
 @pytest.mark.skipif(tool_missing('xxd'), reason='missing xxd')
 def test_with_compare_details_and_tool_not_found(monkeypatch):
-    monkeypatch.setattr('diffoscope.RequiredToolNotFound.get_package', lambda _: 'some-package')
+    monkeypatch.setattr('diffoscope.exc.RequiredToolNotFound.get_package', lambda _: 'some-package')
     class MockFile(FilesystemFile):
         @tool_required('nonexistent')
         def compare_details(self, other, source=None):

-- 
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/reproducible/diffoscope.git


More information about the diffoscope mailing list