diff --git a/pre_commit_hooks/pretty_format_json.py b/pre_commit_hooks/pretty_format_json.py index d9956fe..f3afe98 100644 --- a/pre_commit_hooks/pretty_format_json.py +++ b/pre_commit_hooks/pretty_format_json.py @@ -9,9 +9,11 @@ from difflib import unified_diff from typing import Mapping from typing import Sequence -def _insert_linebreaks(json_str) -> str: - # (?P\s*) seems to capture the \n. Hence, there is no need for it in the substitution string - return re.sub(r'\n(?P\s*)(?P.*): {}(?P,??)', '\n\g\g: {\n\g}\g', json_str) +def _insert_linebreaks(json_str: str) -> str: + return re.sub( + r'\n(?P\s*)(?P.*): {}(?P,??)', + '\n\g\g: {\n\g}\g', + json_str) def _get_pretty_format( contents: str, @@ -109,7 +111,8 @@ def main(argv: Sequence[str] | None = None) -> int: action='store_true', dest='empty_object_with_newline', default=False, - help='Format empty JSON objects to have a linebreak, also activates --no-sort-keys', + help='Format empty JSON objects to have a linebreak, ' \ + + 'also activates --no-sort-keys', ) parser.add_argument('filenames', nargs='*', help='Filenames to fix') args = parser.parse_args(argv) diff --git a/tests/pretty_format_json_test.py b/tests/pretty_format_json_test.py index 31f3955..4413d17 100644 --- a/tests/pretty_format_json_test.py +++ b/tests/pretty_format_json_test.py @@ -146,24 +146,29 @@ def test_empty_object_with_newline(tmpdir): ret = main(["--empty-object-with-newline", str(sameline)]) assert ret == 1 + # a template to be compared against. multiline = get_resource_path("empty_object_json_multiline.json") - to_be_formatted_sameline = tmpdir.join( - "not_pretty_formatted_empty_object_json_sameline.json" - ) - shutil.copyfile(str(sameline), str(to_be_formatted_sameline)) # file has empty object with newline => expect fail with default settings ret = main([str(multiline)]) assert ret == 1 - # now launch the autofix with empty object with newline support on that file + # launch the autofix with empty object with newline support on that file + to_be_formatted_sameline = tmpdir.join( + "not_pretty_formatted_empty_object_json_sameline.json" + ) + shutil.copyfile(str(sameline), str(to_be_formatted_sameline)) ret = main( - ["--autofix", "--empty-object-with-newline", str(to_be_formatted_sameline)] + ["--autofix", + "--empty-object-with-newline", + str(to_be_formatted_sameline)] ) # it should have formatted it and don't raise an error code + # to not stop the the commit assert ret == 0 - # file was formatted (shouldn't trigger linter with --empty-object-with-newline switch) + # file was formatted (shouldn't trigger linter with + # --empty-object-with-newline switch) ret = main(["--empty-object-with-newline", str(to_be_formatted_sameline)]) assert ret == 0 assert filecmp.cmp(to_be_formatted_sameline, multiline)