From 4a9f6c1314406d9d79b569a3f5326e46ec3ee0d1 Mon Sep 17 00:00:00 2001 From: Ggicci Date: Fri, 30 Oct 2020 15:41:37 +0800 Subject: [PATCH] Fix option --diff-only not working on stdin input 1. Fix diff reporting not working on stdin input 2. Alias --diff option to --diff-only --- reorder_python_imports.py | 7 +++++-- tests/reorder_python_imports_test.py | 28 +++++++++++++++++++++++++--- 2 files changed, 30 insertions(+), 5 deletions(-) diff --git a/reorder_python_imports.py b/reorder_python_imports.py index 36c6caf..2de6cf9 100644 --- a/reorder_python_imports.py +++ b/reorder_python_imports.py @@ -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) @@ -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='') diff --git a/tests/reorder_python_imports_test.py b/tests/reorder_python_imports_test.py index 2462def..67979c5 100644 --- a/tests/reorder_python_imports_test.py +++ b/tests/reorder_python_imports_test.py @@ -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 @@ -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')