1 parent 7d878b5 commit ec6c39eCopy full SHA for ec6c39e
2 files changed
pre_commit_hooks/pretty_format_json.py
@@ -1,11 +1,11 @@
1
from __future__ import print_function
2
3
import argparse
4
-import difflib
5
import io
6
import json
7
import sys
8
from collections import OrderedDict
+from difflib import unified_diff
9
from typing import List
10
from typing import Mapping
11
from typing import Optional
@@ -56,11 +56,11 @@ def parse_topkeys(s): # type: (str) -> List[str]
56
return s.split(',')
57
58
59
-def get_diff(source, target): # type: (str, str) -> str
+def get_diff(source, target, file): # type: (str, str, str) -> str
60
source_lines = source.splitlines(True)
61
target_lines = target.splitlines(True)
62
- diff = ''.join(difflib.unified_diff(source_lines, target_lines))
63
- return diff
+ diff = unified_diff(source_lines, target_lines, fromfile=file, tofile=file)
+ return ''.join(diff)
64
65
66
def main(argv=None): # type: (Optional[Sequence[str]]) -> int
@@ -129,7 +129,13 @@ def main(argv=None): # type: (Optional[Sequence[str]]) -> int
129
if args.autofix:
130
_autofix(json_file, pretty_contents)
131
else:
132
- print(get_diff(''.join(contents), pretty_contents))
+ print(
133
+ get_diff(
134
+ ''.join(contents),
135
+ pretty_contents,
136
+ json_file,
137
+ ),
138
+ )
139
140
status = 1
141
except ValueError:
tests/pretty_format_json_test.py
@@ -1,3 +1,4 @@
+import os
import shutil
import pytest
@@ -110,9 +111,13 @@ def test_badfile_main():
110
111
def test_diffing_output(capsys):
112
resource_path = get_resource_path('not_pretty_formatted_json.json')
113
expected_retval = 1
114
+ a = os.path.join('a', resource_path)
115
+ b = os.path.join('b', resource_path)
116
expected_out = '''\
---- \n+++ \n@@ -1,6 +1,9 @@
- {
117
+--- {}
118
++++ {}
119
+@@ -1,6 +1,9 @@
120
+ {{
121
- "foo":
122
- "bar",
123
- "alist": [2, 34, 234],
@@ -124,9 +129,9 @@ def test_diffing_output(capsys):
124
+ ],
125
+ "blah": null,
126
+ "foo": "bar"
127
- }
+ }}
128
-'''
+'''.format(a, b)
expected_err = 'File {} is not pretty-formatted\n'.format(resource_path)
actual_retval = main([resource_path])
0 commit comments