Skip to content

Commit 780f202

Browse files
committed
Add option to show expected output
This prints a diff between the given json file and the expected (pretty) output, with this functionality hidden behind a cli flag
1 parent 3e9db01 commit 780f202

File tree

1 file changed

+18
-10
lines changed

1 file changed

+18
-10
lines changed

pre_commit_hooks/pretty_format_json.py

Lines changed: 18 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import io
55
import json
66
import sys
7+
import difflib
78
from collections import OrderedDict
89
from typing import List
910
from typing import Mapping
@@ -55,6 +56,14 @@ def parse_topkeys(s): # type: (str) -> List[str]
5556
return s.split(',')
5657

5758

59+
def get_diff(source, target):
60+
source_lines = ''.join(source).split('\n')
61+
target_lines = ''.join(target).split('\n')
62+
d = difflib.Differ()
63+
diff = d.compare(source_lines, target_lines)
64+
return '\n'.join(diff)
65+
66+
5867
def main(argv=None): # type: (Optional[Sequence[str]]) -> int
5968
parser = argparse.ArgumentParser()
6069
parser.add_argument(
@@ -96,6 +105,13 @@ def main(argv=None): # type: (Optional[Sequence[str]]) -> int
96105
default=[],
97106
help='Ordered list of keys to keep at the top of JSON hashes',
98107
)
108+
parser.add_argument(
109+
'--show-expected',
110+
action='store_true',
111+
dest='show_expected',
112+
default=False,
113+
help='Show a diff between the input file and expected (pretty) output',
114+
)
99115

100116
parser.add_argument('filenames', nargs='*', help='Filenames to fix')
101117
args = parser.parse_args(argv)
@@ -115,16 +131,8 @@ def main(argv=None): # type: (Optional[Sequence[str]]) -> int
115131
if contents != pretty_contents:
116132
print('File {} is not pretty-formatted'.format(json_file))
117133

118-
contents_by_line = ''.join(contents).split('\n')
119-
pretty_contents_by_line = ''.join(pretty_contents).split('\n')
120-
121-
diff = len(contents_by_line) - len(pretty_contents_by_line)
122-
if diff > 0:
123-
pretty_contents_by_line.extend([''] * diff)
124-
125-
for line_num, line in enumerate(contents_by_line):
126-
if line != pretty_contents_by_line[line_num]:
127-
print('{}:{}'.format(json_file, line_num))
134+
if args.show_expected:
135+
print(get_diff(contents, pretty_contents))
128136

129137
if args.autofix:
130138
_autofix(json_file, pretty_contents)

0 commit comments

Comments
 (0)