Skip to content

Commit 986cd28

Browse files
committed
Add glob pattern utility functions for group filtering
Add _is_glob_pattern, _filter_group_paths, and _resolve_group_and_filter to common.py for detecting and applying glob patterns to group paths.
1 parent f7e47a1 commit 986cd28

1 file changed

Lines changed: 31 additions & 0 deletions

File tree

xarray/backends/common.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -249,6 +249,37 @@ def _iter_nc_groups(root, parent="/"):
249249
yield from _iter_nc_groups(group, parent=gpath)
250250

251251

252+
def _is_glob_pattern(pattern: str) -> bool:
253+
return any(c in pattern for c in "*?[")
254+
255+
256+
def _filter_group_paths(group_paths: Iterable[str], pattern: str) -> list[str]:
257+
from xarray.core.treenode import NodePath
258+
259+
matched: set[str] = {"/"}
260+
for path in group_paths:
261+
np_ = NodePath(path)
262+
if np_.match(pattern):
263+
matched.add(path)
264+
for parent in np_.parents:
265+
p = str(parent)
266+
if p:
267+
matched.add(p)
268+
269+
return [p for p in group_paths if p in matched]
270+
271+
272+
def _resolve_group_and_filter(
273+
group: str | None,
274+
all_group_paths: list[str],
275+
) -> tuple[str | None, list[str]]:
276+
if group is None:
277+
return None, all_group_paths
278+
if _is_glob_pattern(group):
279+
return None, _filter_group_paths(all_group_paths, group)
280+
return group, all_group_paths
281+
282+
252283
def find_root_and_group(ds):
253284
"""Find the root and group name of a netCDF4/h5netcdf dataset."""
254285
hierarchy = ()

0 commit comments

Comments
 (0)