Last active
October 22, 2022 08:16
-
-
Save nikoheikkila/9252fa3c0c0e89a940218bd71e73ca31 to your computer and use it in GitHub Desktop.
General directory scanner implementation in pure Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class PathScanner: | |
input_paths: list[str] | |
allowed_extensions: tuple[str] | |
def __init__(self, input_paths: list[str], allowed_extensions: tuple[str]) -> None: | |
self.input_paths = input_paths | |
self.allowed_extensions = allowed_extensions | |
def fetch_paths(self) -> list[str]: | |
result: list[str] = [] | |
for input_path in self.input_paths: | |
item = Path(input_path) | |
if item.is_dir(): | |
result.extend(self.scan_directory(item)) | |
if item.is_file(): | |
result.extend(self.scan_file(item)) | |
return result | |
def scan_directory(self, directory: Path) -> list[str]: | |
return map( | |
self.normalize_path, filter(self.is_accepted_filetype, directory.iterdir()) | |
) | |
def scan_file(self, file: Path) -> list[str]: | |
return map(self.normalize_path, filter(self.is_accepted_filetype, [file])) | |
def normalize_path(self, path: Path) -> str: | |
return str(path.resolve()) | |
def is_accepted_filetype(self, entry: Path) -> bool: | |
return entry.is_file() and entry.suffix in self.allowed_extensions |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment