Skip to content

Commit

Permalink
Merge pull request #143 from macisamuele/maci-132
Browse files Browse the repository at this point in the history
Expand pretty-format-yaml to allow customisation of offset
  • Loading branch information
macisamuele committed Jan 21, 2023
2 parents 4a72877 + 1319a0e commit f0d68c1
Show file tree
Hide file tree
Showing 4 changed files with 34 additions and 2 deletions.
18 changes: 16 additions & 2 deletions language_formatters_pre_commit_hooks/pretty_format_yaml.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,13 @@ def pretty_format_yaml(argv: typing.Optional[typing.List[str]] = None) -> int:
"--indent",
type=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)",
help="The number of spaces to be used as delimiter for indentation level (Default: %(default)s)",
)
parser.add_argument(
"--offset",
type=int,
default="0",
help="The number of spaces to be used as offset for nested structures (Default: %(default)s)",
)
parser.add_argument(
"--preserve-quotes",
Expand All @@ -67,8 +73,16 @@ def pretty_format_yaml(argv: typing.Optional[typing.List[str]] = None) -> int:

status = 0

if args.indent < args.offset + 2:
print(
"Indent should be at least 2 more than offset. \n"
"Invalid output could be resulting otherwise. \n"
"indent={}, offset={}".format(args.indent, args.offset)
)
return 1

yaml = YAML()
yaml.indent = args.indent
yaml.indent(mapping=args.indent, sequence=args.indent, offset=args.offset)
yaml.preserve_quotes = args.preserve_quotes
# Prevent ruamel.yaml to wrap yaml lines
yaml.width = args.line_width # type: ignore # mypy recognise yaml.width as None
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
root:
- key: 1
- value: "string"
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
root:
- key: 1
- value: string
12 changes: 12 additions & 0 deletions tests/pretty_format_yaml_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,18 @@ def test_pretty_format_yaml(filename, expected_retval):
assert pretty_format_yaml([filename]) == expected_retval


@pytest.mark.parametrize(
("filename", "args", "expected_retval"),
(
("offset2_indent4_pretty-formatted.yaml", ["--indent=1", "--offset=3"], 1),
("offset2_indent4_pretty-formatted.yaml", ["--indent=4", "--offset=2"], 0),
("offset2_indent4_not-pretty-formatted.yaml", ["--indent=4", "--offset=2"], 1),
),
)
def test_pretty_format_yaml_custom_cli_arguments(filename, args, expected_retval):
assert pretty_format_yaml([filename] + args) == expected_retval


@pytest.mark.parametrize(
("no_pretty_file_name, fixed_file_name"),
(
Expand Down

0 comments on commit f0d68c1

Please sign in to comment.