From 2eec17081b6f7456a62cadda9cf3e21b9fd810af Mon Sep 17 00:00:00 2001 From: Jevin Sweval Date: Fri, 18 Apr 2025 14:51:25 -0400 Subject: [PATCH] New -N/--add-eof-newline option to add ending NL Makes xml-fmt play nice with end-of-file-fixer --- src/xml_fmt/__main__.py | 20 +++++++++++++++----- tests/test_main.py | 14 ++++++++++++++ 2 files changed, 29 insertions(+), 5 deletions(-) diff --git a/src/xml_fmt/__main__.py b/src/xml_fmt/__main__.py index 3bacccb..f4eb802 100644 --- a/src/xml_fmt/__main__.py +++ b/src/xml_fmt/__main__.py @@ -25,6 +25,7 @@ class Options(Namespace): indent: str expand_empty_elements: bool + add_eof_newline: bool def run(args: Sequence[str] | None = None) -> int: @@ -76,6 +77,12 @@ def _build_cli() -> ArgumentParser: action="store_true", help="controls if empty XML elements should be collapsed into a self closing element or expanded", ) + format_group.add_argument( + "-N", + "--add-eof-newline", + action="store_true", + help="controls if a trailing newline is appended to the output", + ) msg = "XML (XSD) file(s) to format, use '-' to read from stdin" parser.add_argument("inputs", nargs="+", type=_path_creator, help=msg) @@ -133,11 +140,14 @@ def _handle_one(filename: Path | None, opts: Options) -> bool: def _format(raw: str, opts: Options) -> str: element = XML(raw) indent(element, opts.indent) - return tostring( - element, - encoding="unicode", - xml_declaration=True, - short_empty_elements=not opts.expand_empty_elements, + return ( + tostring( + element, + encoding="unicode", + xml_declaration=True, + short_empty_elements=not opts.expand_empty_elements, + ) + + "\n" * opts.add_eof_newline ) diff --git a/tests/test_main.py b/tests/test_main.py index e0a3eaf..d66c447 100644 --- a/tests/test_main.py +++ b/tests/test_main.py @@ -128,3 +128,17 @@ def test_xml_path_no_write(capsys: pytest.CaptureFixture[str], min_xml: Path) -> out, err = capsys.readouterr() assert "\nxml-fmt: error: argument inputs: cannot write path\n" in err assert not out + + +def test_xml_format_add_newline(capsys: pytest.CaptureFixture[str], tmp_path: Path, min_xml_str: str) -> None: + xml = tmp_path / "name.xml" + xml.write_text(min_xml_str) + + exit_code = run([str(xml), "--no-print-diff", "--add-eof-newline"]) + + assert xml.read_text() == min_xml_str + "\n" + assert exit_code == 1 + + out, err = capsys.readouterr() + assert not err + assert out.splitlines() == []