1"""isort.py.
2
3Defines a git hook to allow pre-commit warnings and errors about import order.
4
5usage:
6    exit_code = git_hook(strict=True)
7
8Copyright (C) 2015  Helen Sherwood-Taylor
9
10Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
11documentation files (the "Software"), to deal in the Software without restriction, including without limitation
12the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
13to permit persons to whom the Software is furnished to do so, subject to the following conditions:
14
15The above copyright notice and this permission notice shall be included in all copies or
16substantial portions of the Software.
17
18THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
19TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
21CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
22OTHER DEALINGS IN THE SOFTWARE.
23
24"""
25import subprocess
26
27from isort import SortImports
28
29
30def get_output(command):
31    """
32    Run a command and return raw output
33
34    :param str command: the command to run
35    :returns: the stdout output of the command
36    """
37    return subprocess.check_output(command.split())
38
39
40def get_lines(command):
41    """
42    Run a command and return lines of output
43
44    :param str command: the command to run
45    :returns: list of whitespace-stripped lines output by command
46    """
47    stdout = get_output(command)
48    return [line.strip().decode('utf-8') for line in stdout.splitlines()]
49
50
51def git_hook(strict=False):
52    """
53    Git pre-commit hook to check staged files for isort errors
54
55    :param bool strict - if True, return number of errors on exit,
56        causing the hook to fail. If False, return zero so it will
57        just act as a warning.
58
59    :return number of errors if in strict mode, 0 otherwise.
60    """
61
62    # Get list of files modified and staged
63    diff_cmd = "git diff-index --cached --name-only --diff-filter=ACMRTUXB HEAD"
64    files_modified = get_lines(diff_cmd)
65
66    errors = 0
67    for filename in files_modified:
68        if filename.endswith('.py'):
69            # Get the staged contents of the file
70            staged_cmd = "git show :%s" % filename
71            staged_contents = get_output(staged_cmd)
72
73            sort = SortImports(
74                file_path=filename,
75                file_contents=staged_contents.decode(),
76                check=True
77            )
78
79            if sort.incorrectly_sorted:
80                errors += 1
81
82    return errors if strict else 0
83