pytex/PyTeX/paths/relative_paths.py

85 lines
2.7 KiB
Python

from pathlib import Path, PurePath, PosixPath, PurePosixPath, PureWindowsPath, WindowsPath
from typing import Union
from PyTeX.config.global_config import GlobalPyTeXConfig
from .enums import PyTeXRootDirType
import os
class PyTeXPurePath(PurePath):
def __new__(cls, *args):
if cls is PyTeXPurePath:
cls = PyTeXPureWindowsPath if os.name == 'nt' else PyTeXPurePosixPath
class PyTeXPurePosixPath(PurePosixPath, PyTeXPurePath):
pass
class PyTeXPureWindowsPath(PureWindowsPath, PyTeXPurePath):
pass
class PyTeXPath(Path):
def __new__(cls, pytex_root_dir_type: PyTeXRootDirType, *args, **kwargs):
self = super().__new__(cls, *args, **kwargs)
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:
if self._pytex_root_dir_type == PyTeXRootDirType.PYTEX_SOURCE:
self._relative_path = self.relative_to(self._root_dir)
else:
self._relative_path = self.relative_to(
self._root_dir / GlobalPyTeXConfig.wrapper_dir()
)
except ValueError:
raise ValueError # TODO
def root_dir_type(self) -> PyTeXRootDirType:
return self._pytex_root_dir_type
@property
def relative_path(self) -> Path:
return self._relative_path
def __truediv__(self, other):
if self._pytex_root_dir_type == PyTeXRootDirType.PYTEX_SOURCE:
return super().__truediv__(other)
else:
return super().__truediv__(GlobalPyTeXConfig.wrapper_dir()).__truediv__(other)
class PureRelativePath:
def __init__(self, relative_path: Union[str, PurePath]):
if type(relative_path) == PurePath:
self._relative_path: PurePath = relative_path
else:
self._relative_path: PurePath = PurePath(relative_path)
@property
def path(self) -> PurePath:
return self._relative_path
def __eq__(self, other):
return self.path == other.path
def __str__(self):
return str(self.path)
class RelativePath(PureRelativePath, PyTeXPath):
def __init__(self, path: Path, pytex_root_dir: PyTeXRootDirType):
self._absolute_path: Path = path
def absolute_path(self) -> Path:
return self._absolute_path