Skip to content

Commit 319af68

Browse files
author
longendu
committed
add trace_dir_upwards
1 parent 4ff9f30 commit 319af68

File tree

1 file changed

+27
-1
lines changed

1 file changed

+27
-1
lines changed

aiutil/filesystem.py

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
#!/usr/bin/env python3
22
"""Filesystem related util functions."""
3-
3+
from collections import namedtuple
44
from typing import Iterable, Callable
55
import itertools
66
import os
@@ -18,6 +18,7 @@
1818
import dulwich.porcelain
1919

2020
HOME = Path.home()
21+
PosixPathPair = namedtuple("PosixPathPair", ["prefix", "base"])
2122

2223

2324
def copy_if_exists(src: str, dst: str | Path = HOME) -> bool:
@@ -691,3 +692,28 @@ def filter(
691692
if sub_pattern:
692693
return _filter_sp(path, pattern=pattern, sub_pattern=sub_pattern)
693694
return _filter_num(path, pattern=pattern, num_lines=num_lines)
695+
696+
697+
def trace_dir_upwards(path: str | pathlib.Path, name: str) -> PosixPathPair:
698+
"""Find the parent directory with the specified name.
699+
700+
Args:
701+
path: A local path contains `/name/`.
702+
name: The base name (stem) of the parent directory.
703+
704+
Returns:
705+
A PosixPathPair which contains the parent directory
706+
and the relative path to this parent directory.
707+
"""
708+
def _trace_dir_upwards(path: pathlib.Path) -> pathlib.Path:
709+
while (stem := path.stem) != name:
710+
if not stem:
711+
raise ValueError(f"The path {path} does not contain /{name}/!")
712+
path = path.parent
713+
return path
714+
715+
if isinstance(path, str):
716+
path = pathlib.Path(path)
717+
prefix = _trace_dir_upwards(path)
718+
return PosixPathPair(prefix, path.relative_to(prefix))
719+

0 commit comments

Comments
 (0)