Files
intern2020/internfiles/pth.py
2020-12-28 00:50:17 +00:00

39 lines
1.1 KiB
Python

import os
from slugify import slugify
class pth(str):
def __new__(cls, value, *args, **kw):
if not value:
value = ""
value = value.rstrip("/")
return str.__new__(cls, value, *args, **kw)
def __add__(self, add):
if isinstance(add, str) or isinstance(add, pth):
return pth(os.path.join(str(self), str(add))) # .rstrip("/")
else:
return super().__add__(add)
def __sub__(self, sub):
if isinstance(sub, int):
return pth("/".join(self.split("/")[:-sub]))
else:
return super().__sub__(sub)
def __contains__(self, path):
directory = os.path.join(os.path.realpath(str(self)), "")
file = os.path.realpath(str(path))
return os.path.commonprefix([file, directory]) == directory
def __getitem__(self, key):
return str(self).split("/")[key]
def slugify(self):
s = self.split("/")
s = s[:-1]
s2 = s[-1]
if "." in s[-1]:
s2 = ".".join([slugify(p) for p in s2])
return "/".join([slugify(p) for p in s] + [s2])