Skip to content

Commit

Permalink
pretty-format-json: ignore original newline presence or absence
Browse files Browse the repository at this point in the history
  • Loading branch information
ajoga committed Mar 14, 2024
1 parent 2d94897 commit 3ff6240
Show file tree
Hide file tree
Showing 4 changed files with 16 additions and 1 deletion.
1 change: 1 addition & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ repos:
hooks:
- id: trailing-whitespace
- id: end-of-file-fixer
exclude: testing/resources/pretty_formatted_json_no_endline.json
- id: check-yaml
- id: debug-statements
- id: double-quote-string-fixer
Expand Down
4 changes: 3 additions & 1 deletion pre_commit_hooks/pretty_format_json.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import json
import sys
from difflib import unified_diff
from os import linesep
from typing import Mapping
from typing import Sequence

Expand All @@ -27,7 +28,8 @@ def pairs_first(pairs: Sequence[tuple[str, str]]) -> Mapping[str, str]:
indent=indent,
ensure_ascii=ensure_ascii,
)
return f'{json_pretty}\n'
finisher = linesep if contents.endswith(linesep) else ''
return f'{json_pretty}{finisher}'


def _autofix(filename: str, new_contents: str) -> None:
Expand Down
9 changes: 9 additions & 0 deletions testing/resources/pretty_formatted_json_no_endline.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"alist": [
2,
34,
234
],
"blah": null,
"foo": "bar"
}
3 changes: 3 additions & 0 deletions tests/pretty_format_json_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ def test_parse_num_to_int():
('unsorted_pretty_formatted_json.json', 1),
('non_ascii_pretty_formatted_json.json', 1),
('pretty_formatted_json.json', 0),
('pretty_formatted_json_no_endline.json', 0),
),
)
def test_main(filename, expected_retval):
Expand All @@ -36,6 +37,7 @@ def test_main(filename, expected_retval):
('unsorted_pretty_formatted_json.json', 0),
('non_ascii_pretty_formatted_json.json', 1),
('pretty_formatted_json.json', 0),
('pretty_formatted_json_no_endline.json', 0),
),
)
def test_unsorted_main(filename, expected_retval):
Expand All @@ -49,6 +51,7 @@ def test_unsorted_main(filename, expected_retval):
('unsorted_pretty_formatted_json.json', 1),
('non_ascii_pretty_formatted_json.json', 1),
('pretty_formatted_json.json', 1),
('pretty_formatted_json_no_endline.json', 1),
('tab_pretty_formatted_json.json', 0),
),
)
Expand Down

0 comments on commit 3ff6240

Please sign in to comment.