Skip to content

Commit

Permalink
Fix pretty_format_json to use int indent
Browse files Browse the repository at this point in the history
The indent parameter for json should be integer and under Python2 is
will raise an error if not. So switch from str to int and mention
default value in help text.
  • Loading branch information
Calum Lind committed Dec 10, 2017
1 parent 00974ef commit 5b6ddaf
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 29 deletions.
29 changes: 10 additions & 19 deletions pre_commit_hooks/pretty_format_json.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,24 +33,12 @@ def _autofix(filename, new_contents):
f.write(new_contents)


def parse_indent(s):
# type: (str) -> str
def parse_num_to_int(s):
"""Convert string numbers to int, leaving strings as is."""
try:
int_indentation_spec = int(s)
return int(s)
except ValueError:
if not s.strip():
return s
else:
raise ValueError(
'Non-whitespace JSON indentation delimiter supplied. ',
)
else:
if int_indentation_spec >= 0:
return int_indentation_spec * ' '
else:
raise ValueError(
'Negative integer supplied to construct JSON indentation delimiter. ',
)
return s


def parse_topkeys(s):
Expand All @@ -68,9 +56,12 @@ def pretty_format_json(argv=None):
)
parser.add_argument(
'--indent',
type=parse_indent,
default=' ',
help='String used as delimiter for one indentation level',
type=parse_num_to_int,
default='2',
help=(
'The number of indent spaces or a string to be used as delimiter'
' for indentation level e.g. 4 or "\t" (Default: 2)'
),
)
parser.add_argument(
'--no-ensure-ascii',
Expand Down
16 changes: 6 additions & 10 deletions tests/pretty_format_json_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,16 @@
import pytest
from six import PY2

from pre_commit_hooks.pretty_format_json import parse_indent
from pre_commit_hooks.pretty_format_json import parse_num_to_int
from pre_commit_hooks.pretty_format_json import pretty_format_json
from testing.util import get_resource_path


def test_parse_indent():
assert parse_indent('0') == ''
assert parse_indent('2') == ' '
assert parse_indent('\t') == '\t'
with pytest.raises(ValueError):
parse_indent('a')
with pytest.raises(ValueError):
parse_indent('-2')

def test_parse_num_to_int():
assert parse_num_to_int('0') == 0
assert parse_num_to_int('2') == 2
assert parse_num_to_int('\t') == '\t'
assert parse_num_to_int(' ') == ' '


@pytest.mark.parametrize(
Expand Down

0 comments on commit 5b6ddaf

Please sign in to comment.