|
| 1 | +"""Types for working with file trees.""" |
| 2 | + |
| 3 | +import os |
| 4 | +import posixpath |
| 5 | +import stat |
| 6 | +from functools import cached_property |
| 7 | +from pathlib import Path |
| 8 | +from typing import Union |
| 9 | + |
| 10 | +import attrs |
| 11 | +from typing_extensions import Self # PY310 |
| 12 | + |
| 13 | +__all__ = ('FileTree',) |
| 14 | + |
| 15 | + |
| 16 | +@attrs.define |
| 17 | +class UserDirEntry: |
| 18 | + """Partial reimplementation of :class:`os.DirEntry`. |
| 19 | +
|
| 20 | + :class:`os.DirEntry` can't be instantiated from Python, but this can. |
| 21 | + """ |
| 22 | + |
| 23 | + path: str = attrs.field(repr=False, converter=os.fspath) |
| 24 | + name: str = attrs.field(init=False) |
| 25 | + _stat: os.stat_result = attrs.field(init=False, repr=False, default=None) |
| 26 | + _lstat: os.stat_result = attrs.field(init=False, repr=False, default=None) |
| 27 | + |
| 28 | + def __attrs_post_init__(self) -> None: |
| 29 | + self.name = os.path.basename(self.path) |
| 30 | + |
| 31 | + def __fspath__(self) -> str: |
| 32 | + return self.path |
| 33 | + |
| 34 | + def stat(self, *, follow_symlinks: bool = True) -> os.stat_result: |
| 35 | + """Return stat_result object for the entry; cached per entry.""" |
| 36 | + if follow_symlinks: |
| 37 | + if self._stat is None: |
| 38 | + self._stat = os.stat(self.path, follow_symlinks=True) |
| 39 | + return self._stat |
| 40 | + else: |
| 41 | + if self._lstat is None: |
| 42 | + self._lstat = os.stat(self.path, follow_symlinks=False) |
| 43 | + return self._lstat |
| 44 | + |
| 45 | + def is_dir(self, *, follow_symlinks: bool = True) -> bool: |
| 46 | + """Return True if the entry is a directory; cached per entry.""" |
| 47 | + _stat = self.stat(follow_symlinks=follow_symlinks) |
| 48 | + return stat.S_ISDIR(_stat.st_mode) |
| 49 | + |
| 50 | + def is_file(self, *, follow_symlinks: bool = True) -> bool: |
| 51 | + """Return True if the entry is a file; cached per entry.""" |
| 52 | + _stat = self.stat(follow_symlinks=follow_symlinks) |
| 53 | + return stat.S_ISREG(_stat.st_mode) |
| 54 | + |
| 55 | + def is_symlink(self) -> bool: |
| 56 | + """Return True if the entry is a symlink; cached per entry.""" |
| 57 | + _stat = self.stat(follow_symlinks=False) |
| 58 | + return stat.S_ISLNK(_stat.st_mode) |
| 59 | + |
| 60 | + |
| 61 | +def as_direntry(obj: os.PathLike) -> Union[os.DirEntry, UserDirEntry]: |
| 62 | + """Convert PathLike into DirEntry-like object.""" |
| 63 | + if isinstance(obj, os.DirEntry): |
| 64 | + return obj |
| 65 | + return UserDirEntry(obj) |
| 66 | + |
| 67 | + |
| 68 | +@attrs.define |
| 69 | +class FileTree: |
| 70 | + """Represent a FileTree with cached metadata.""" |
| 71 | + |
| 72 | + direntry: Union[os.DirEntry, UserDirEntry] = attrs.field(repr=False, converter=as_direntry) |
| 73 | + parent: Union['FileTree', None] = attrs.field(repr=False, default=None) |
| 74 | + is_dir: bool = attrs.field(default=False) |
| 75 | + children: dict[str, 'FileTree'] = attrs.field(repr=False, factory=dict) |
| 76 | + name: str = attrs.field(init=False) |
| 77 | + |
| 78 | + def __attrs_post_init__(self): |
| 79 | + self.name = self.direntry.name |
| 80 | + self.children = { |
| 81 | + name: attrs.evolve(child, parent=self) for name, child in self.children.items() |
| 82 | + } |
| 83 | + |
| 84 | + @classmethod |
| 85 | + def read_from_filesystem( |
| 86 | + cls, |
| 87 | + direntry: os.PathLike, |
| 88 | + parent: Union['FileTree', None] = None, |
| 89 | + ) -> Self: |
| 90 | + """Read a FileTree from the filesystem. |
| 91 | +
|
| 92 | + Uses :func:`os.scandir` to walk the directory tree. |
| 93 | + """ |
| 94 | + self = cls(direntry, parent=parent) |
| 95 | + if self.direntry.is_dir(): |
| 96 | + self.is_dir = True |
| 97 | + self.children = { |
| 98 | + entry.name: FileTree.read_from_filesystem(entry, parent=self) |
| 99 | + for entry in os.scandir(self.direntry) |
| 100 | + } |
| 101 | + return self |
| 102 | + |
| 103 | + def __contains__(self, relpath: os.PathLike) -> bool: |
| 104 | + parts = Path(relpath).parts |
| 105 | + if len(parts) == 0: |
| 106 | + return False |
| 107 | + child = self.children.get(parts[0], False) |
| 108 | + return child and (len(parts) == 1 or posixpath.join(*parts[1:]) in child) |
| 109 | + |
| 110 | + def __fspath__(self): |
| 111 | + return self.direntry.path |
| 112 | + |
| 113 | + @cached_property |
| 114 | + def relative_path(self) -> str: |
| 115 | + """The path of the current FileTree, relative to the root. |
| 116 | +
|
| 117 | + Follows parents up to the root and joins with POSIX separators (/). |
| 118 | + Directories include trailing slashes for simpler matching. |
| 119 | + """ |
| 120 | + if self.parent is None: |
| 121 | + return '' |
| 122 | + |
| 123 | + return posixpath.join( |
| 124 | + self.parent.relative_path, |
| 125 | + f'{self.name}/' if self.is_dir else self.name, |
| 126 | + ) |
0 commit comments