import os from pathlib import Path, WindowsPath, PosixPath from PyTeX.build.config import GlobalPyTeXConfig from PyTeX.build.paths import PyTeXRootDirType class RelativePath(Path): """ 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): self._pytex_root_dir_type: PyTeXRootDirType = pytex_root_dir_type self._root_dir: Path = { PyTeXRootDirType.BUILD: GlobalPyTeXConfig.build_root(), PyTeXRootDirType.PYTEX_SOURCE: GlobalPyTeXConfig.source_root(), PyTeXRootDirType.DOC: GlobalPyTeXConfig.doc_root(), PyTeXRootDirType.TEX_SOURCE: GlobalPyTeXConfig.tex_root() }[self._pytex_root_dir_type] try: self._relative_path = self.relative_to(self._root_dir) except ValueError as e: raise NotImplementedError @property def root_dir_type(self) -> PyTeXRootDirType: return self._pytex_root_dir_type @property def root_dir(self) -> Path: return self._root_dir @property def relative_path(self): return self._relative_path class RelativeWindowsPath(RelativePath, WindowsPath): pass class RelativePosixPath(RelativePath, PosixPath): pass