utils.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. #!/usr/bin/env python
  2. # License: GPLv3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net>
  3. import os
  4. from collections.abc import Generator
  5. from contextlib import contextmanager
  6. _cwd = _home = ''
  7. def abspath(path: str, use_home: bool = False) -> str:
  8. base = home_path() if use_home else (_cwd or os.getcwd())
  9. return os.path.normpath(os.path.join(base, path))
  10. def home_path() -> str:
  11. return _home or os.path.expanduser('~')
  12. def cwd_path() -> str:
  13. return _cwd or os.getcwd()
  14. def expand_home(path: str) -> str:
  15. if path.startswith('~' + os.sep) or (os.altsep and path.startswith('~' + os.altsep)):
  16. return os.path.join(home_path(), path[2:].lstrip(os.sep + (os.altsep or '')))
  17. return path
  18. @contextmanager
  19. def set_paths(cwd: str = '', home: str = '') -> Generator[None, None, None]:
  20. global _cwd, _home
  21. orig = _cwd, _home
  22. try:
  23. _cwd, _home = cwd, home
  24. yield
  25. finally:
  26. _cwd, _home = orig
  27. class IdentityCompressor:
  28. def compress(self, data: bytes) -> bytes:
  29. return data
  30. def flush(self) -> bytes:
  31. return b''
  32. class ZlibCompressor:
  33. def __init__(self) -> None:
  34. import zlib
  35. self.c = zlib.compressobj()
  36. def compress(self, data: bytes) -> bytes:
  37. return self.c.compress(data)
  38. def flush(self) -> bytes:
  39. return self.c.flush()