Skip to content

Commit ec6c39e

Browse files
committed
Print filenames in the diff
1 parent 7d878b5 commit ec6c39e

File tree

2 files changed

+20
-9
lines changed

2 files changed

+20
-9
lines changed

pre_commit_hooks/pretty_format_json.py

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11
from __future__ import print_function
22

33
import argparse
4-
import difflib
54
import io
65
import json
76
import sys
87
from collections import OrderedDict
8+
from difflib import unified_diff
99
from typing import List
1010
from typing import Mapping
1111
from typing import Optional
@@ -56,11 +56,11 @@ def parse_topkeys(s): # type: (str) -> List[str]
5656
return s.split(',')
5757

5858

59-
def get_diff(source, target): # type: (str, str) -> str
59+
def get_diff(source, target, file): # type: (str, str, str) -> str
6060
source_lines = source.splitlines(True)
6161
target_lines = target.splitlines(True)
62-
diff = ''.join(difflib.unified_diff(source_lines, target_lines))
63-
return diff
62+
diff = unified_diff(source_lines, target_lines, fromfile=file, tofile=file)
63+
return ''.join(diff)
6464

6565

6666
def main(argv=None): # type: (Optional[Sequence[str]]) -> int
@@ -129,7 +129,13 @@ def main(argv=None): # type: (Optional[Sequence[str]]) -> int
129129
if args.autofix:
130130
_autofix(json_file, pretty_contents)
131131
else:
132-
print(get_diff(''.join(contents), pretty_contents))
132+
print(
133+
get_diff(
134+
''.join(contents),
135+
pretty_contents,
136+
json_file,
137+
),
138+
)
133139

134140
status = 1
135141
except ValueError:

tests/pretty_format_json_test.py

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import os
12
import shutil
23

34
import pytest
@@ -110,9 +111,13 @@ def test_badfile_main():
110111
def test_diffing_output(capsys):
111112
resource_path = get_resource_path('not_pretty_formatted_json.json')
112113
expected_retval = 1
114+
a = os.path.join('a', resource_path)
115+
b = os.path.join('b', resource_path)
113116
expected_out = '''\
114-
--- \n+++ \n@@ -1,6 +1,9 @@
115-
{
117+
--- {}
118+
+++ {}
119+
@@ -1,6 +1,9 @@
120+
{{
116121
- "foo":
117122
- "bar",
118123
- "alist": [2, 34, 234],
@@ -124,9 +129,9 @@ def test_diffing_output(capsys):
124129
+ ],
125130
+ "blah": null,
126131
+ "foo": "bar"
127-
}
132+
}}
128133
129-
'''
134+
'''.format(a, b)
130135
expected_err = 'File {} is not pretty-formatted\n'.format(resource_path)
131136

132137
actual_retval = main([resource_path])

0 commit comments

Comments
 (0)