codekingpro/portable-devtools
114k
1import os2import sys3from typing import Union4 5if sys.version_info >= (3, 9):6 StrPath = Union[str, os.PathLike[str]] # Same as _typeshed.StrPath7else:8 StrPath = Union[str, os.PathLike]9 10 11def ensure_directory(path):12 """Ensure that the parent directory of `path` exists"""13 dirname = os.path.dirname(path)14 os.makedirs(dirname, exist_ok=True)15 16 17def same_path(p1: StrPath, p2: StrPath) -> bool:18 """Differs from os.path.samefile because it does not require paths to exist.19 Purely string based (no comparison between i-nodes).20 >>> same_path("a/b", "./a/b")21 True22 >>> same_path("a/b", "a/./b")23 True24 >>> same_path("a/b", "././a/b")25 True26 >>> same_path("a/b", "./a/b/c/..")27 True28 >>> same_path("a/b", "../a/b/c")29 False30 >>> same_path("a", "a/b")31 False32 """33 return normpath(p1) == normpath(p2)34 35 36def normpath(filename: StrPath) -> str:37 """Normalize a file/dir name for comparison purposes."""38 # See pkg_resources.normalize_path for notes about cygwin39 file = os.path.abspath(filename) if sys.platform == 'cygwin' else filename40 return os.path.normcase(os.path.realpath(os.path.normpath(file)))41 