From 5a65e8e40b165beface05cd376f1c65e396493a3 Mon Sep 17 00:00:00 2001 From: LightArrowsEXE Date: Thu, 5 Sep 2024 00:02:07 +0200 Subject: [PATCH] SPath: Implement fglob ```bash $ python benchmark.py Total time for 10000 iterations: 0.4242 seconds Average time per fglob call: 0.000042 seconds Total time for 10000 simple glob iterations: 0.5244 seconds Average time per simple glob call: 0.000052 seconds ``` --- stgpytools/types/file.py | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/stgpytools/types/file.py b/stgpytools/types/file.py index 5f412f5..e4e46d7 100644 --- a/stgpytools/types/file.py +++ b/stgpytools/types/file.py @@ -1,7 +1,8 @@ from __future__ import annotations +import fnmatch import shutil -from os import PathLike, listdir, path +from os import PathLike, listdir, path, walk from pathlib import Path from typing import TYPE_CHECKING, Any, Callable, Iterable, Literal, TypeAlias, Union @@ -142,6 +143,16 @@ def lglob(self, pattern: str) -> list[SPath]: return [SPath(p) for p in self.glob(pattern)] + def fglob(self, pattern: str = '*') -> SPath | None: + """Glob the path and return the first match.""" + + for root, dirs, files in walk(self): + for name in dirs + files: + if fnmatch.fnmatch(name, pattern): + return SPath(path.join(root, name)) + + return None + def find_newest_file(self, pattern: str = '*') -> SPath | None: """Find the most recently modified file matching the given pattern in the directory."""