mirror of
https://github.com/pre-commit/pre-commit-hooks.git
synced 2026-03-30 18:26:53 +00:00
Fix pretty_format_json to use int indent
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.
This commit is contained in:
parent
00974efa31
commit
5b6ddaf9f7
2 changed files with 16 additions and 29 deletions
|
|
@ -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):
|
||||
|
|
@ -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',
|
||||
|
|
|
|||
|
|
@ -3,20 +3,16 @@ import shutil
|
|||
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(
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue