44import io
55import json
66import sys
7+ import difflib
78from collections import OrderedDict
89from typing import List
910from 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+
5867def 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