use delegation to pathlib.Path to implement RelativePath class

This commit is contained in:
Maximilian Keßler 2022-02-05 20:04:52 +01:00
parent b6d0d935ff
commit 4cf09b71a2

View file

@ -1,26 +1,15 @@
import os
from pathlib import Path, WindowsPath, PosixPath
from pathlib import Path
from ..config import GlobalPyTeXConfig
from PyTeX.build.enums.enums import PyTeXRootDirType
class RelativePath(Path):
class RelativePath:
"""
Represents a path that knows of its corresponding root directory
"""
def __new__(cls, pytex_root_dir_type: PyTeXRootDirType, *args, **kwargs):
if cls is RelativePath:
cls = RelativeWindowsPath if os.name == 'nt' else RelativePosixPath
self = cls._from_parts(args, init=False)
if not self._flavour.is_supported:
raise NotImplementedError("cannot instantiate %r on your system"
% (cls.__name__,))
self._init()
self.__init(pytex_root_dir_type)
return self
def __init(self, pytex_root_dir_type: PyTeXRootDirType):
def __init__(self, pytex_root_dir_type: PyTeXRootDirType, *args, **kwargs):
self._path = Path(*args, **kwargs)
self._pytex_root_dir_type: PyTeXRootDirType = pytex_root_dir_type
self._root_dir: Path = {
PyTeXRootDirType.BUILD: GlobalPyTeXConfig.build_root(),
@ -29,6 +18,31 @@ class RelativePath(Path):
PyTeXRootDirType.TEX_SOURCE: GlobalPyTeXConfig.tex_root()
}[self._pytex_root_dir_type]
def __getattr__(self, attr):
ret = getattr(self._path, attr)
if isinstance(ret, Path):
return RelativePath(self._pytex_root_dir_type, ret)
else:
return ret
def __truediv__(self, other):
if isinstance(other, RelativePath):
path = self._path.__truediv__(other.path)
else:
path = self._path.__truediv__(other)
return RelativePath(self._pytex_root_dir_type, path)
def __rtruediv__(self, other):
if isinstance(other, RelativePath):
path = self._path.__rtruediv__(other.path)
else:
path = self._path.__rtruediv__(other)
return RelativePath(self._pytex_root_dir_type, path)
@property
def path(self) -> Path:
return self._path
@property
def root_dir_type(self) -> PyTeXRootDirType:
return self._pytex_root_dir_type
@ -43,11 +57,3 @@ class RelativePath(Path):
return self.relative_to(self._root_dir)
except ValueError as e:
raise NotImplementedError
class RelativeWindowsPath(RelativePath, WindowsPath):
pass
class RelativePosixPath(RelativePath, PosixPath):
pass