From c15a662df3a9dc1cae34373686ca8e2e51946de9 Mon Sep 17 00:00:00 2001 From: Xevion Date: Thu, 11 May 2023 21:48:10 -0500 Subject: [PATCH] Add pathlib-based recursive walk function --- phototag/helpers.py | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/phototag/helpers.py b/phototag/helpers.py index 29fb0ee..f7663d1 100644 --- a/phototag/helpers.py +++ b/phototag/helpers.py @@ -9,7 +9,8 @@ import random import re import string from glob import glob -from typing import List, Optional, Tuple +from pathlib import Path +from typing import List, Optional, Tuple, Generator from phototag import LOSSY_EXTS, RAW_EXTS, CWD from phototag.exceptions import PhototagException, InvalidSelectionError @@ -98,6 +99,28 @@ def convert_to_bytes(size_string: str) -> int: return int(match.group(1)) * byte_magnitudes.get(match.group(2), 0) +def walk(root: Path, current: Optional[Path] = None, depth: Optional[int] = None) -> Generator[ + Path, None, None]: + """ + Recursively walk through a directory and yield all files found. + """ + root_abs_depth: int = len(root.parents) + + if depth is not None and depth < 0: + depth = None + + for item in (current or root).iterdir(): + if item.is_file(): + yield item.resolve() + if not item.is_dir(): + continue + + # Recursive handling + cur_depth: int = len(item.resolve().parents) - root_abs_depth - 1 + if depth is None or cur_depth < depth: + yield from walk(root, current=item, depth=depth) + + def select_files(files: List[str], regex: Optional[str], glob_pattern: Optional[str]) -> List[str]: """ Helper function for selecting files in the CWD (or subdirectories, via Glob) and filtering them.