Skip to content

Commit

Permalink
Improve forcing of is_urdf argument
Browse files Browse the repository at this point in the history
  • Loading branch information
flferretti committed Nov 11, 2024
1 parent 73420ab commit 7cb5ba1
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 18 deletions.
33 changes: 15 additions & 18 deletions src/rod/sdf/sdf.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,24 +69,21 @@ def load(sdf: pathlib.Path | str, is_urdf: bool | None = None) -> Sdf:
# Check if the input is a string path.
is_str_path = getattr(sdf, "__len__", lambda: MAX_PATH + 1)() <= MAX_PATH

if is_urdf is not None:
sdf_string = sdf
else:
match sdf:
# Case 1: Handle SDF/URDF string.
case str() if not is_str_path:
sdf_string = sdf
is_urdf = "<robot" in sdf_string

# Case 2: Handle pathlib.Path and string paths.
case pathlib.Path() | str():
path = pathlib.Path(sdf)
sdf_string = path.read_text(encoding="utf-8")
is_urdf = path.suffix == ".urdf"

# Case 3: Raise an error for unsupported types.
case _:
raise TypeError(f"Unsupported type for 'sdf': {type(sdf)}")
match sdf:
# Case 1: Handle SDF/URDF string.
case str() if not is_str_path:
sdf_string = sdf
is_urdf = is_urdf if is_urdf is not None else "<robot" in sdf_string

# Case 2: Handle pathlib.Path and string paths.
case pathlib.Path() | str():
path = pathlib.Path(sdf)
sdf_string = path.read_text(encoding="utf-8")
is_urdf = is_urdf if is_urdf is not None else path.suffix == ".urdf"

# Case 3: Raise an error for unsupported types.
case _:
raise TypeError(f"Unsupported type for 'sdf': {type(sdf)}")

# Convert SDF to URDF if needed (it requires system executables)
if is_urdf:
Expand Down
5 changes: 5 additions & 0 deletions tests/test_urdf_parsing.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,11 @@ def test_urdf_parsing(robot: Robot) -> None:
with pytest.raises(RuntimeError):
_ = rod.Sdf.load(sdf=urdf_path.read_text(), is_urdf=False)

# Check that it fails is is_urdf=True and the resource is a non-existing path
with pytest.raises(FileNotFoundError):
_ = rod.Sdf.load(sdf="/non/existing/path", is_urdf=None)
_ = rod.Sdf.load(sdf="/non/existing/path", is_urdf=False)

# The following instead should succeed
_ = rod.Sdf.load(sdf=urdf_path, is_urdf=None)
_ = rod.Sdf.load(sdf=urdf_path, is_urdf=True)
Expand Down

0 comments on commit 7cb5ba1

Please sign in to comment.