Skip to content

feat: Prepare For Multi-Command CLI Interface #121

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

Merged
merged 7 commits into from
Apr 15, 2025
Merged
Show file tree
Hide file tree
Changes from 5 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
60 changes: 4 additions & 56 deletions src/fundamend/cli.py
Original file line number Diff line number Diff line change
@@ -1,72 +1,20 @@
"""contains the entrypoint for the command line interface"""

import json
from pathlib import Path

import typer
from pydantic import RootModel
from rich.console import Console
from typing_extensions import Annotated

from fundamend import AhbReader, Anwendungshandbuch, MessageImplementationGuide, MigReader
from fundamend.commands import app as commands_app

app = typer.Typer(name="xml2json", help="Convert XML(s) by BDEW to JSON(s)")
app = typer.Typer(name="fundamend", help="CLI tool to work with XML files by BDEW", no_args_is_help=True)
Copy link
Contributor

@hf-kklein hf-kklein Apr 15, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

err_console = Console(stderr=True) # https://typer.tiangolo.com/tutorial/printing/#printing-to-standard-error


def _convert_to_json_file(xml_file_path: Path) -> Path:
"""converts the given XML file to a JSON file and returns the path of the latter"""
if not xml_file_path.is_file():
raise ValueError(f"The given path {xml_file_path.absolute()} is not a file")
is_ahb = "ahb" in xml_file_path.stem.lower()
is_mig = "mig" in xml_file_path.stem.lower()
if is_ahb and is_mig:
raise ValueError(f"Cannot detect if {xml_file_path} is an AHB or MIG")
root_model: RootModel[Anwendungshandbuch] | RootModel[MessageImplementationGuide]
if is_ahb:
ahb_model = AhbReader(xml_file_path).read()
root_model = RootModel[Anwendungshandbuch](ahb_model)
elif is_mig:
mig_model = MigReader(xml_file_path).read()
root_model = RootModel[MessageImplementationGuide](mig_model)
else:
raise ValueError(f"Seems like {xml_file_path} is neither an AHB nor a MIG")
out_dict = root_model.model_dump(mode="json")
json_file_path = xml_file_path.with_suffix(".json")
with open(json_file_path, encoding="utf-8", mode="w") as outfile:
json.dump(out_dict, outfile, indent=True, ensure_ascii=False)
print(f"Successfully converted {xml_file_path} file to JSON {json_file_path}")
return json_file_path


@app.command()
def main(
xml_path: Annotated[
Path,
typer.Option(
exists=True,
file_okay=True,
dir_okay=True,
writable=True,
readable=True,
resolve_path=True,
),
],
) -> None:
"""
converts the xml file from xml_in_path to a json file next to the .xml
"""
assert xml_path.exists() # ensured by typer
if xml_path.is_dir():
for _xml_path in xml_path.rglob("*.xml"):
_convert_to_json_file(_xml_path)
else:
_convert_to_json_file(xml_path)
app.add_typer(commands_app)


def cli() -> None:
"""entry point of the script defined in pyproject.toml"""
typer.run(main)
typer.run(app)


if __name__ == "__main__":
Expand Down
11 changes: 11 additions & 0 deletions src/fundamend/commands/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
"""
Contains the commands for the CLI.
"""

import typer

from fundamend.commands.xml2json import app as xml2json_app

app = typer.Typer()

app.add_typer(xml2json_app)
64 changes: 64 additions & 0 deletions src/fundamend/commands/xml2json.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
"""
Contains the command to convert XML files to JSON files.
"""

import json
from pathlib import Path

import typer
from pydantic import RootModel
from typing_extensions import Annotated

from fundamend import AhbReader, Anwendungshandbuch, MessageImplementationGuide, MigReader

app = typer.Typer()


def _convert_to_json_file(xml_file_path: Path) -> Path:
"""converts the given XML file to a JSON file and returns the path of the latter"""
if not xml_file_path.is_file():
raise ValueError(f"The given path {xml_file_path.absolute()} is not a file")
is_ahb = "ahb" in xml_file_path.stem.lower()
is_mig = "mig" in xml_file_path.stem.lower()
if is_ahb and is_mig:
raise ValueError(f"Cannot detect if {xml_file_path} is an AHB or MIG")
root_model: RootModel[Anwendungshandbuch] | RootModel[MessageImplementationGuide]
if is_ahb:
ahb_model = AhbReader(xml_file_path).read()
root_model = RootModel[Anwendungshandbuch](ahb_model)
elif is_mig:
mig_model = MigReader(xml_file_path).read()
root_model = RootModel[MessageImplementationGuide](mig_model)
else:
raise ValueError(f"Seems like {xml_file_path} is neither an AHB nor a MIG")
out_dict = root_model.model_dump(mode="json")
json_file_path = xml_file_path.with_suffix(".json")
with open(json_file_path, encoding="utf-8", mode="w") as outfile:
json.dump(out_dict, outfile, indent=True, ensure_ascii=False)
print(f"Successfully converted {xml_file_path} file to JSON {json_file_path}")
return json_file_path

Comment on lines +38 to +40
Copy link
Preview

Copilot AI Apr 15, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[nitpick] Consider replacing print() with typer.echo() for consistent CLI output handling which integrates better with Typer's logging and testing facilities.

Suggested change
print(f"Successfully converted {xml_file_path} file to JSON {json_file_path}")
return json_file_path
typer.echo(f"Successfully converted {xml_file_path} file to JSON {json_file_path}")

Copilot uses AI. Check for mistakes.


@app.command()
def xml2json(
xml_path: Annotated[
Path,
typer.Option(
exists=True,
file_okay=True,
dir_okay=True,
writable=True,
readable=True,
resolve_path=True,
),
],
) -> None:
"""
converts the xml file from xml_in_path to a json file next to the .xml
"""
assert xml_path.exists() # ensured by typer
if xml_path.is_dir():
for _xml_path in xml_path.rglob("*.xml"):
_convert_to_json_file(_xml_path)
else:
_convert_to_json_file(xml_path)
6 changes: 3 additions & 3 deletions unittests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ def test_cli_single_file_mig(tmp_path: Path) -> None:
original_mig_file = Path(__file__).parent / "example_files" / "UTILTS_MIG_1.1c_Lesefassung_2023_12_12.xml"
tmp_mig_path = tmp_path / "my_mig.xml"
_copy_xml_file(original_mig_file, tmp_mig_path)
result = runner.invoke(app, ["--xml-path", str(tmp_mig_path.absolute())])
result = runner.invoke(app, ["xml2json", "--xml-path", str(tmp_mig_path.absolute())])
assert result.exit_code == 0
assert (tmp_path / "my_mig.json").exists()

Expand All @@ -35,7 +35,7 @@ def test_cli_single_file_ahb(tmp_path: Path) -> None:
original_ahb_file = Path(__file__).parent / "example_files" / "UTILTS_AHB_1.1d_Konsultationsfassung_2024_04_02.xml"
tmp_ahb_path = tmp_path / "my_ahb.xml"
_copy_xml_file(original_ahb_file, tmp_ahb_path)
result = runner.invoke(app, ["--xml-path", str(tmp_ahb_path)])
result = runner.invoke(app, ["xml2json", "--xml-path", str(tmp_ahb_path.absolute())])
assert result.exit_code == 0
assert (tmp_path / "my_ahb.json").exists()

Expand All @@ -49,7 +49,7 @@ def test_cli_directory(tmp_path: Path) -> None:
tmp_ahb_path = tmp_path / "my_ahb.xml"
_copy_xml_file(original_ahb_file, tmp_ahb_path)
_copy_xml_file(original_mig_file, tmp_mig_path)
result = runner.invoke(app, ["--xml-path", str(tmp_path)])
result = runner.invoke(app, ["xml2json", "--xml-path", str(tmp_path.absolute())])
assert result.exit_code == 0
assert (tmp_path / "my_mig.json").exists()
assert (tmp_path / "my_ahb.json").exists()