Skip to content

Commit

Permalink
Merge pull request #209 from MridulS/pathlib_santize
Browse files Browse the repository at this point in the history
MAINT: use pathlib for path manipulation
  • Loading branch information
MridulS committed Apr 25, 2024
2 parents 02e43eb + 9c27556 commit 7188161
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 6 deletions.
15 changes: 9 additions & 6 deletions src/scippnexus/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import warnings
from collections.abc import Mapping
from functools import lru_cache
from pathlib import PurePosixPath
from types import MappingProxyType
from typing import Any, Dict, Iterator, List, Optional, Tuple, Union, overload

Expand Down Expand Up @@ -380,13 +381,15 @@ def __getitem__(self, sel):
# create the parent group, to ensure that fields get the correct properties
# such as sizes and dtype.
if '/' in sel:
if sel.startswith('/'):
return self.file[sel[1:]]
elif sel.endswith('/'):
return self[sel[:-1]]
sel_path = PurePosixPath(sel)
if sel_path.is_absolute():
return self.file[sel_path.relative_to('/').as_posix()]
# If the path is a single name, we can directly access the child
elif len(sel_path.parts) == 1:
return self[sel_path.as_posix()]
else:
grp, path = sel.split('/', 1)
return self[grp][path]
grp = sel_path.parts[0]
return self[grp][sel_path.relative_to(grp).as_posix()]
child = self._children[sel]
if isinstance(child, Field):
self._populate_fields()
Expand Down
6 changes: 6 additions & 0 deletions tests/nexus_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -678,3 +678,9 @@ def test_empty_class_does_not_warn(nxroot, nxclass):

def test_trailing_forward_slash_in_path_does_not_change_file_object(nxroot):
assert id(nxroot['entry/']) == id(nxroot['entry'])


def test_path_santization(nxroot):
nxroot['entry'].create_class('log', NXlog)
assert id(nxroot['/entry/log']) == id(nxroot['/entry//log'])
assert id(nxroot['entry/log']) == id(nxroot['entry//log'])

0 comments on commit 7188161

Please sign in to comment.