Skip to content

Commit 25cdd54

Browse files
amarvinasottile
authored andcommitted
Continues processing JSONs even if hook fails (fixes #1038)
1 parent 8c24e2c commit 25cdd54

File tree

2 files changed

+31
-9
lines changed

2 files changed

+31
-9
lines changed

pre_commit_hooks/pretty_format_json.py

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -115,16 +115,20 @@ def main(argv: Sequence[str] | None = None) -> int:
115115
f'Input File {json_file} is not a valid JSON, consider using '
116116
f'check-json',
117117
)
118-
return 1
119-
120-
if contents != pretty_contents:
121-
if args.autofix:
122-
_autofix(json_file, pretty_contents)
123-
else:
124-
diff_output = get_diff(contents, pretty_contents, json_file)
125-
sys.stdout.buffer.write(diff_output.encode())
126-
127118
status = 1
119+
else:
120+
if contents != pretty_contents:
121+
if args.autofix:
122+
_autofix(json_file, pretty_contents)
123+
else:
124+
diff_output = get_diff(
125+
contents,
126+
pretty_contents,
127+
json_file,
128+
)
129+
sys.stdout.buffer.write(diff_output.encode())
130+
131+
status = 1
128132

129133
return status
130134

tests/pretty_format_json_test.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,24 @@ def test_autofix_main(tmpdir):
8282
assert ret == 0
8383

8484

85+
def test_invalid_main(tmpdir):
86+
srcfile1 = tmpdir.join('not_valid_json.json')
87+
srcfile1.write(
88+
'{\n'
89+
' // not json\n'
90+
' "a": "b"\n'
91+
'}',
92+
)
93+
srcfile2 = tmpdir.join('to_be_json_formatted.json')
94+
srcfile2.write('{ "a": "b" }')
95+
96+
# it should have skipped the first file and formatted the second one
97+
assert main(['--autofix', str(srcfile1), str(srcfile2)]) == 1
98+
99+
# confirm second file was formatted (shouldn't trigger linter again)
100+
assert main([str(srcfile2)]) == 0
101+
102+
85103
def test_orderfile_get_pretty_format():
86104
ret = main((
87105
'--top-keys=alist', get_resource_path('pretty_formatted_json.json'),

0 commit comments

Comments
 (0)