Skip to content

Commit

Permalink
Fix option --diff-only not working on stdin input
Browse files Browse the repository at this point in the history
1. Fix diff reporting not working on stdin input
2. Alias --diff option to --diff-only
  • Loading branch information
ggicci authored and asottile committed Oct 31, 2020
1 parent 84e28de commit 4a9f6c1
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 5 deletions.
7 changes: 5 additions & 2 deletions reorder_python_imports.py
Original file line number Diff line number Diff line change
Expand Up @@ -482,7 +482,10 @@ def _fix_file(filename: str, args: argparse.Namespace) -> int:
unclassifiable_application_modules=args.unclassifiable,
)
if filename == '-':
print(new_contents, end='')
if args.diff_only:
_report_diff(contents, new_contents, '')
else:
print(new_contents, end='')
elif contents != new_contents:
if args.diff_only:
_report_diff(contents, new_contents, filename)
Expand Down Expand Up @@ -510,7 +513,7 @@ def _report_diff(contents: str, new_contents: str, filename: str) -> None:
fromfile=filename, tofile=filename,
),
)
if not diff.endswith('\n'):
if diff and not diff.endswith('\n'):
diff += '\n\\ No newline at end of file\n'

print(diff, end='')
Expand Down
28 changes: 25 additions & 3 deletions tests/reorder_python_imports_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -744,9 +744,10 @@ def test_integration_main_stdout(tmpdir, capsys):
)


def _apply_patch(patch):
patch_proc = subprocess.Popen(('patch',), stdin=subprocess.PIPE)
patch_proc.communicate(patch.encode('UTF-8'))
def _apply_patch(patch, origfile=None):
args = ('patch', origfile) if origfile else ('patch',)
patch_proc = subprocess.Popen(args, stdin=subprocess.PIPE)
patch_proc.communicate(patch.encode())
assert patch_proc.returncode == 0


Expand Down Expand Up @@ -1135,6 +1136,27 @@ def test_main_stdin_no_fix(capsys):
assert out == 'import os\nimport sys\n'


def test_main_stdin_diff_only(tmpdir, capsys):
tf = tmpdir.join('t.py')
input_b = b'import sys\nimport os\n'
tf.write(input_b)
stdin = io.TextIOWrapper(io.BytesIO(input_b), 'UTF-8')
with mock.patch.object(sys, 'stdin', stdin):
assert main(('-', '--diff-only')) == 1
out, _ = capsys.readouterr()
_apply_patch(out, origfile=tf)
assert tf.read() == 'import os\nimport sys\n'


def test_main_stdin_diff_only_no_changes(capsys):
input_b = b'import os\nimport sys\n'
stdin = io.TextIOWrapper(io.BytesIO(input_b), 'UTF-8')
with mock.patch.object(sys, 'stdin', stdin):
assert main(('-', '--diff-only')) == 0
out, err = capsys.readouterr()
assert out == ''


def test_main_exit_code_multiple_files(tmpdir):
f1 = tmpdir.join('t1.py')
f1.write('import os,sys\n')
Expand Down

0 comments on commit 4a9f6c1

Please sign in to comment.