_path.py 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. import os
  2. import sys
  3. from typing import Union
  4. _Path = Union[str, os.PathLike]
  5. def ensure_directory(path):
  6. """Ensure that the parent directory of `path` exists"""
  7. dirname = os.path.dirname(path)
  8. os.makedirs(dirname, exist_ok=True)
  9. def same_path(p1: _Path, p2: _Path) -> bool:
  10. """Differs from os.path.samefile because it does not require paths to exist.
  11. Purely string based (no comparison between i-nodes).
  12. >>> same_path("a/b", "./a/b")
  13. True
  14. >>> same_path("a/b", "a/./b")
  15. True
  16. >>> same_path("a/b", "././a/b")
  17. True
  18. >>> same_path("a/b", "./a/b/c/..")
  19. True
  20. >>> same_path("a/b", "../a/b/c")
  21. False
  22. >>> same_path("a", "a/b")
  23. False
  24. """
  25. return normpath(p1) == normpath(p2)
  26. def normpath(filename: _Path) -> str:
  27. """Normalize a file/dir name for comparison purposes."""
  28. # See pkg_resources.normalize_path for notes about cygwin
  29. file = os.path.abspath(filename) if sys.platform == 'cygwin' else filename
  30. return os.path.normcase(os.path.realpath(os.path.normpath(file)))