Skip to content
This repository has been archived by the owner on Nov 3, 2020. It is now read-only.

Commit

Permalink
Merge pull request #12 from teeberg/show_diff
Browse files Browse the repository at this point in the history
Add --diff flag to show diff of expected imports
  • Loading branch information
dinoshauer committed Dec 28, 2015
2 parents ec01d99 + fe7d5f1 commit d044ff2
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 3 deletions.
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@ Available flags:

* ``--silent-overwrite``: The hook won't fail if it has to change files. It will
just do it.
* ``--check-only``: The hook will not change any files.
* ``--diff``: If imports are not ordered correctly, print a diff of required
changes to fix the import order.

The hook supports [isort's configuration files](https://github.com/timothycrosley/isort#configuring-isort) - Please refer to the isort documentation for reference

Expand Down
7 changes: 4 additions & 3 deletions pre_commit_hook/sort.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@
from isort import isort


def imports_incorrect(filename):
return isort.SortImports(filename, check=True).incorrectly_sorted
def imports_incorrect(filename, show_diff=False):
return isort.SortImports(filename, check=True, show_diff=show_diff).incorrectly_sorted


def main(argv=None):
Expand All @@ -16,12 +16,13 @@ def main(argv=None):
parser.add_argument('filenames', nargs='*', help='Filenames to run')
parser.add_argument('--silent-overwrite', action='store_true', dest='silent', default=False)
parser.add_argument('--check-only', action='store_true', dest='check_only', default=False)
parser.add_argument('--diff', action='store_true', dest='show_diff', default=False)
args = parser.parse_args(argv)

return_value = 0

for filename in args.filenames:
if imports_incorrect(filename):
if imports_incorrect(filename, show_diff=args.show_diff):
if args.check_only:
return_value = 1
elif args.silent:
Expand Down
18 changes: 18 additions & 0 deletions tests/sort_test.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import pytest
from isort.isort import stdout

from pre_commit_hook.sort import main

Expand All @@ -21,3 +22,20 @@ def test_sort(tmpfiles):
assert main([tmpfiles.join('incorrect_1.py').strpath]) == 1
assert main([tmpfiles.join('incorrect_2.py').strpath, '--check-only']) == 1
assert main([tmpfiles.join('incorrect_2.py').strpath, '--silent-overwrite']) == 0


def test_sort_with_diff(tmpfiles):
filename = tmpfiles.join('incorrect_1.py').strpath
main(['--diff', '--check-only', filename])

stdout.seek(0)
lines = stdout.read().splitlines()
# Skip diff header
lines = lines[4:]
assert lines == [
'+import json',
' import sys',
'-',
'-',
'-import json',
]

0 comments on commit d044ff2

Please sign in to comment.