Skip to content
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

ioutils: Supports recursive match "**" #3795

Merged
merged 1 commit into from
May 5, 2023
Merged
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
12 changes: 12 additions & 0 deletions src/silx/io/test/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -989,3 +989,15 @@ def test_match_commonh5():
result = list(utils.match(fobj, "/entry_*/*"))

assert sorted(result) == ['entry_0000/data', 'entry_0000/group', 'entry_0001/data', 'entry_0001/group']


def test_recursive_match_commonh5():
"""Test match function with commonh5 objects"""
with commonh5.File("filename.file", mode="w") as fobj:
fobj["entry_0000/bar/data"] = 0
fobj["entry_0001/foo/data"] = 1
fobj["entry_0001/foo/data1"] = 2
fobj["entry_0003"] = 3

result = list(utils.match(fobj, "**/data"))
assert result == ['entry_0000/bar/data', 'entry_0001/foo/data']
17 changes: 17 additions & 0 deletions src/silx/io/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -825,13 +825,30 @@ def visitall(item):
yield from _visitall(item, '')


def iter_groups(group, _root=None):
"""Pythonic implementation of h5py.Group visit()"""
for name in group.keys():
entity = group.get(name)
if is_group(entity):
yield name
for subgroup in iter_groups(entity, _root=name):
yield f"{name}/{subgroup}"


def match(group, path_pattern: str) -> Generator[str, None, None]:
"""Generator of paths inside given h5py-like `group` matching `path_pattern`"""
if not is_group(group):
raise ValueError(f"Not a h5py-like group: {group}")

path_parts = path_pattern.strip("/").split("/", 1)
if path_parts[0] == "**":
# recursive match
for subpath in iter_groups(group):
sub = group.get(subpath)
for groupname in match(sub, path_parts[1]):
yield f"{subpath}/{groupname}"
return

for matching_path in fnmatch.filter(group.keys(), path_parts[0]):
if len(path_parts) == 1: # No more sub-path, stop recursion
yield matching_path
Expand Down