Skip to content

Commit cf04ab0

Browse files
authored
Merge pull request #254 from cas--/refactor/pretty-format-json
Refactor/pretty format json
2 parents f3ff331 + 3e1b954 commit cf04ab0

File tree

3 files changed

+31
-43
lines changed

3 files changed

+31
-43
lines changed

pre_commit_hooks/pretty_format_json.py

Lines changed: 22 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,11 @@
22

33
import argparse
44
import io
5+
import json
56
import sys
67
from collections import OrderedDict
78

8-
import simplejson
9-
import six
9+
from six import text_type
1010

1111

1212
def _get_pretty_format(contents, indent, ensure_ascii=True, sort_keys=True, top_keys=[]):
@@ -17,40 +17,28 @@ def pairs_first(pairs):
1717
if sort_keys:
1818
after = sorted(after, key=lambda x: x[0])
1919
return OrderedDict(before + after)
20-
return six.text_type(simplejson.dumps(
21-
simplejson.loads(
22-
contents,
23-
object_pairs_hook=pairs_first,
24-
),
20+
json_pretty = json.dumps(
21+
json.loads(contents, object_pairs_hook=pairs_first),
2522
indent=indent,
2623
ensure_ascii=ensure_ascii,
27-
)) + "\n" # dumps does not end with a newline
24+
separators=(',', ': '), # Workaround for https://bugs.python.org/issue16333
25+
)
26+
# Ensure unicode (Py2) and add the newline that dumps does not end with.
27+
return text_type(json_pretty) + '\n'
2828

2929

3030
def _autofix(filename, new_contents):
31-
print("Fixing file {}".format(filename))
31+
print('Fixing file {}'.format(filename))
3232
with io.open(filename, 'w', encoding='UTF-8') as f:
3333
f.write(new_contents)
3434

3535

36-
def parse_indent(s):
37-
# type: (str) -> str
36+
def parse_num_to_int(s):
37+
"""Convert string numbers to int, leaving strings as is."""
3838
try:
39-
int_indentation_spec = int(s)
39+
return int(s)
4040
except ValueError:
41-
if not s.strip():
42-
return s
43-
else:
44-
raise ValueError(
45-
'Non-whitespace JSON indentation delimiter supplied. ',
46-
)
47-
else:
48-
if int_indentation_spec >= 0:
49-
return int_indentation_spec * ' '
50-
else:
51-
raise ValueError(
52-
'Negative integer supplied to construct JSON indentation delimiter. ',
53-
)
41+
return s
5442

5543

5644
def parse_topkeys(s):
@@ -68,9 +56,12 @@ def pretty_format_json(argv=None):
6856
)
6957
parser.add_argument(
7058
'--indent',
71-
type=parse_indent,
72-
default=' ',
73-
help='String used as delimiter for one indentation level',
59+
type=parse_num_to_int,
60+
default='2',
61+
help=(
62+
'The number of indent spaces or a string to be used as delimiter'
63+
' for indentation level e.g. 4 or "\t" (Default: 2)'
64+
),
7465
)
7566
parser.add_argument(
7667
'--no-ensure-ascii',
@@ -110,16 +101,15 @@ def pretty_format_json(argv=None):
110101
)
111102

112103
if contents != pretty_contents:
113-
print("File {} is not pretty-formatted".format(json_file))
104+
print('File {} is not pretty-formatted'.format(json_file))
114105

115106
if args.autofix:
116107
_autofix(json_file, pretty_contents)
117108

118109
status = 1
119-
120-
except simplejson.JSONDecodeError:
110+
except ValueError:
121111
print(
122-
"Input File {} is not a valid JSON, consider using check-json"
112+
'Input File {} is not a valid JSON, consider using check-json'
123113
.format(json_file),
124114
)
125115
return 1

setup.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,6 @@
2828
'flake8!=2.5.3',
2929
'autopep8>=1.3',
3030
'pyyaml',
31-
'simplejson',
3231
'six',
3332
],
3433
entry_points={

tests/pretty_format_json_test.py

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,18 @@
11
import shutil
22

33
import pytest
4+
from six import PY2
45

5-
from pre_commit_hooks.pretty_format_json import parse_indent
6+
from pre_commit_hooks.pretty_format_json import parse_num_to_int
67
from pre_commit_hooks.pretty_format_json import pretty_format_json
78
from testing.util import get_resource_path
89

910

10-
def test_parse_indent():
11-
assert parse_indent('0') == ''
12-
assert parse_indent('2') == ' '
13-
assert parse_indent('\t') == '\t'
14-
with pytest.raises(ValueError):
15-
parse_indent('a')
16-
with pytest.raises(ValueError):
17-
parse_indent('-2')
11+
def test_parse_num_to_int():
12+
assert parse_num_to_int('0') == 0
13+
assert parse_num_to_int('2') == 2
14+
assert parse_num_to_int('\t') == '\t'
15+
assert parse_num_to_int(' ') == ' '
1816

1917

2018
@pytest.mark.parametrize(
@@ -43,6 +41,7 @@ def test_unsorted_pretty_format_json(filename, expected_retval):
4341
assert ret == expected_retval
4442

4543

44+
@pytest.mark.skipif(PY2, reason="Requires Python3")
4645
@pytest.mark.parametrize(
4746
('filename', 'expected_retval'), (
4847
('not_pretty_formatted_json.json', 1),
@@ -52,7 +51,7 @@ def test_unsorted_pretty_format_json(filename, expected_retval):
5251
('tab_pretty_formatted_json.json', 0),
5352
),
5453
)
55-
def test_tab_pretty_format_json(filename, expected_retval):
54+
def test_tab_pretty_format_json(filename, expected_retval): # pragma: no cover
5655
ret = pretty_format_json(['--indent', '\t', get_resource_path(filename)])
5756
assert ret == expected_retval
5857

0 commit comments

Comments
 (0)