From ec6c39ee621461aa95e0cbcdd99189f331e31ce5 Mon Sep 17 00:00:00 2001 From: Joey Pinhas Date: Tue, 24 Sep 2019 15:42:24 -0400 Subject: [PATCH] Print filenames in the diff --- pre_commit_hooks/pretty_format_json.py | 16 +++++++++++----- tests/pretty_format_json_test.py | 13 +++++++++---- 2 files changed, 20 insertions(+), 9 deletions(-) diff --git a/pre_commit_hooks/pretty_format_json.py b/pre_commit_hooks/pretty_format_json.py index f5476a5..fa83305 100644 --- a/pre_commit_hooks/pretty_format_json.py +++ b/pre_commit_hooks/pretty_format_json.py @@ -1,11 +1,11 @@ from __future__ import print_function import argparse -import difflib import io import json import sys from collections import OrderedDict +from difflib import unified_diff from typing import List from typing import Mapping from typing import Optional @@ -56,11 +56,11 @@ def parse_topkeys(s): # type: (str) -> List[str] return s.split(',') -def get_diff(source, target): # type: (str, str) -> str +def get_diff(source, target, file): # type: (str, str, str) -> str source_lines = source.splitlines(True) target_lines = target.splitlines(True) - diff = ''.join(difflib.unified_diff(source_lines, target_lines)) - return diff + diff = unified_diff(source_lines, target_lines, fromfile=file, tofile=file) + return ''.join(diff) def main(argv=None): # type: (Optional[Sequence[str]]) -> int @@ -129,7 +129,13 @@ def main(argv=None): # type: (Optional[Sequence[str]]) -> int if args.autofix: _autofix(json_file, pretty_contents) else: - print(get_diff(''.join(contents), pretty_contents)) + print( + get_diff( + ''.join(contents), + pretty_contents, + json_file, + ), + ) status = 1 except ValueError: diff --git a/tests/pretty_format_json_test.py b/tests/pretty_format_json_test.py index d31fe91..7020c4c 100644 --- a/tests/pretty_format_json_test.py +++ b/tests/pretty_format_json_test.py @@ -1,3 +1,4 @@ +import os import shutil import pytest @@ -110,9 +111,13 @@ def test_badfile_main(): def test_diffing_output(capsys): resource_path = get_resource_path('not_pretty_formatted_json.json') expected_retval = 1 + a = os.path.join('a', resource_path) + b = os.path.join('b', resource_path) expected_out = '''\ ---- \n+++ \n@@ -1,6 +1,9 @@ - { +--- {} ++++ {} +@@ -1,6 +1,9 @@ + {{ - "foo": - "bar", - "alist": [2, 34, 234], @@ -124,9 +129,9 @@ def test_diffing_output(capsys): + ], + "blah": null, + "foo": "bar" - } + }} -''' +'''.format(a, b) expected_err = 'File {} is not pretty-formatted\n'.format(resource_path) actual_retval = main([resource_path])