Skip to content

New -N/--add-eof-newline option to add ending NL #10

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 15 additions & 5 deletions src/xml_fmt/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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
)


Expand Down
14 changes: 14 additions & 0 deletions tests/test_main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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() == []