pathlib.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724
  1. import atexit
  2. import contextlib
  3. import fnmatch
  4. import importlib.util
  5. import itertools
  6. import os
  7. import shutil
  8. import sys
  9. import uuid
  10. import warnings
  11. from enum import Enum
  12. from errno import EBADF
  13. from errno import ELOOP
  14. from errno import ENOENT
  15. from errno import ENOTDIR
  16. from functools import partial
  17. from os.path import expanduser
  18. from os.path import expandvars
  19. from os.path import isabs
  20. from os.path import sep
  21. from pathlib import Path
  22. from pathlib import PurePath
  23. from posixpath import sep as posix_sep
  24. from types import ModuleType
  25. from typing import Callable
  26. from typing import Dict
  27. from typing import Iterable
  28. from typing import Iterator
  29. from typing import Optional
  30. from typing import Set
  31. from typing import TypeVar
  32. from typing import Union
  33. from _pytest.compat import assert_never
  34. from _pytest.outcomes import skip
  35. from _pytest.warning_types import PytestWarning
  36. LOCK_TIMEOUT = 60 * 60 * 24 * 3
  37. _AnyPurePath = TypeVar("_AnyPurePath", bound=PurePath)
  38. # The following function, variables and comments were
  39. # copied from cpython 3.9 Lib/pathlib.py file.
  40. # EBADF - guard against macOS `stat` throwing EBADF
  41. _IGNORED_ERRORS = (ENOENT, ENOTDIR, EBADF, ELOOP)
  42. _IGNORED_WINERRORS = (
  43. 21, # ERROR_NOT_READY - drive exists but is not accessible
  44. 1921, # ERROR_CANT_RESOLVE_FILENAME - fix for broken symlink pointing to itself
  45. )
  46. def _ignore_error(exception):
  47. return (
  48. getattr(exception, "errno", None) in _IGNORED_ERRORS
  49. or getattr(exception, "winerror", None) in _IGNORED_WINERRORS
  50. )
  51. def get_lock_path(path: _AnyPurePath) -> _AnyPurePath:
  52. return path.joinpath(".lock")
  53. def on_rm_rf_error(func, path: str, exc, *, start_path: Path) -> bool:
  54. """Handle known read-only errors during rmtree.
  55. The returned value is used only by our own tests.
  56. """
  57. exctype, excvalue = exc[:2]
  58. # Another process removed the file in the middle of the "rm_rf" (xdist for example).
  59. # More context: https://github.com/pytest-dev/pytest/issues/5974#issuecomment-543799018
  60. if isinstance(excvalue, FileNotFoundError):
  61. return False
  62. if not isinstance(excvalue, PermissionError):
  63. warnings.warn(
  64. PytestWarning(f"(rm_rf) error removing {path}\n{exctype}: {excvalue}")
  65. )
  66. return False
  67. if func not in (os.rmdir, os.remove, os.unlink):
  68. if func not in (os.open,):
  69. warnings.warn(
  70. PytestWarning(
  71. "(rm_rf) unknown function {} when removing {}:\n{}: {}".format(
  72. func, path, exctype, excvalue
  73. )
  74. )
  75. )
  76. return False
  77. # Chmod + retry.
  78. import stat
  79. def chmod_rw(p: str) -> None:
  80. mode = os.stat(p).st_mode
  81. os.chmod(p, mode | stat.S_IRUSR | stat.S_IWUSR)
  82. # For files, we need to recursively go upwards in the directories to
  83. # ensure they all are also writable.
  84. p = Path(path)
  85. if p.is_file():
  86. for parent in p.parents:
  87. chmod_rw(str(parent))
  88. # Stop when we reach the original path passed to rm_rf.
  89. if parent == start_path:
  90. break
  91. chmod_rw(str(path))
  92. func(path)
  93. return True
  94. def ensure_extended_length_path(path: Path) -> Path:
  95. """Get the extended-length version of a path (Windows).
  96. On Windows, by default, the maximum length of a path (MAX_PATH) is 260
  97. characters, and operations on paths longer than that fail. But it is possible
  98. to overcome this by converting the path to "extended-length" form before
  99. performing the operation:
  100. https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file#maximum-path-length-limitation
  101. On Windows, this function returns the extended-length absolute version of path.
  102. On other platforms it returns path unchanged.
  103. """
  104. if sys.platform.startswith("win32"):
  105. path = path.resolve()
  106. path = Path(get_extended_length_path_str(str(path)))
  107. return path
  108. def get_extended_length_path_str(path: str) -> str:
  109. """Convert a path to a Windows extended length path."""
  110. long_path_prefix = "\\\\?\\"
  111. unc_long_path_prefix = "\\\\?\\UNC\\"
  112. if path.startswith((long_path_prefix, unc_long_path_prefix)):
  113. return path
  114. # UNC
  115. if path.startswith("\\\\"):
  116. return unc_long_path_prefix + path[2:]
  117. return long_path_prefix + path
  118. def rm_rf(path: Path) -> None:
  119. """Remove the path contents recursively, even if some elements
  120. are read-only."""
  121. path = ensure_extended_length_path(path)
  122. onerror = partial(on_rm_rf_error, start_path=path)
  123. shutil.rmtree(str(path), onerror=onerror)
  124. def find_prefixed(root: Path, prefix: str) -> Iterator[Path]:
  125. """Find all elements in root that begin with the prefix, case insensitive."""
  126. l_prefix = prefix.lower()
  127. for x in root.iterdir():
  128. if x.name.lower().startswith(l_prefix):
  129. yield x
  130. def extract_suffixes(iter: Iterable[PurePath], prefix: str) -> Iterator[str]:
  131. """Return the parts of the paths following the prefix.
  132. :param iter: Iterator over path names.
  133. :param prefix: Expected prefix of the path names.
  134. """
  135. p_len = len(prefix)
  136. for p in iter:
  137. yield p.name[p_len:]
  138. def find_suffixes(root: Path, prefix: str) -> Iterator[str]:
  139. """Combine find_prefixes and extract_suffixes."""
  140. return extract_suffixes(find_prefixed(root, prefix), prefix)
  141. def parse_num(maybe_num) -> int:
  142. """Parse number path suffixes, returns -1 on error."""
  143. try:
  144. return int(maybe_num)
  145. except ValueError:
  146. return -1
  147. def _force_symlink(
  148. root: Path, target: Union[str, PurePath], link_to: Union[str, Path]
  149. ) -> None:
  150. """Helper to create the current symlink.
  151. It's full of race conditions that are reasonably OK to ignore
  152. for the context of best effort linking to the latest test run.
  153. The presumption being that in case of much parallelism
  154. the inaccuracy is going to be acceptable.
  155. """
  156. current_symlink = root.joinpath(target)
  157. try:
  158. current_symlink.unlink()
  159. except OSError:
  160. pass
  161. try:
  162. current_symlink.symlink_to(link_to)
  163. except Exception:
  164. pass
  165. def make_numbered_dir(root: Path, prefix: str, mode: int = 0o700) -> Path:
  166. """Create a directory with an increased number as suffix for the given prefix."""
  167. for i in range(10):
  168. # try up to 10 times to create the folder
  169. max_existing = max(map(parse_num, find_suffixes(root, prefix)), default=-1)
  170. new_number = max_existing + 1
  171. new_path = root.joinpath(f"{prefix}{new_number}")
  172. try:
  173. new_path.mkdir(mode=mode)
  174. except Exception:
  175. pass
  176. else:
  177. _force_symlink(root, prefix + "current", new_path)
  178. return new_path
  179. else:
  180. raise OSError(
  181. "could not create numbered dir with prefix "
  182. "{prefix} in {root} after 10 tries".format(prefix=prefix, root=root)
  183. )
  184. def create_cleanup_lock(p: Path) -> Path:
  185. """Create a lock to prevent premature folder cleanup."""
  186. lock_path = get_lock_path(p)
  187. try:
  188. fd = os.open(str(lock_path), os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o644)
  189. except FileExistsError as e:
  190. raise OSError(f"cannot create lockfile in {p}") from e
  191. else:
  192. pid = os.getpid()
  193. spid = str(pid).encode()
  194. os.write(fd, spid)
  195. os.close(fd)
  196. if not lock_path.is_file():
  197. raise OSError("lock path got renamed after successful creation")
  198. return lock_path
  199. def register_cleanup_lock_removal(lock_path: Path, register=atexit.register):
  200. """Register a cleanup function for removing a lock, by default on atexit."""
  201. pid = os.getpid()
  202. def cleanup_on_exit(lock_path: Path = lock_path, original_pid: int = pid) -> None:
  203. current_pid = os.getpid()
  204. if current_pid != original_pid:
  205. # fork
  206. return
  207. try:
  208. lock_path.unlink()
  209. except OSError:
  210. pass
  211. return register(cleanup_on_exit)
  212. def maybe_delete_a_numbered_dir(path: Path) -> None:
  213. """Remove a numbered directory if its lock can be obtained and it does
  214. not seem to be in use."""
  215. path = ensure_extended_length_path(path)
  216. lock_path = None
  217. try:
  218. lock_path = create_cleanup_lock(path)
  219. parent = path.parent
  220. garbage = parent.joinpath(f"garbage-{uuid.uuid4()}")
  221. path.rename(garbage)
  222. rm_rf(garbage)
  223. except OSError:
  224. # known races:
  225. # * other process did a cleanup at the same time
  226. # * deletable folder was found
  227. # * process cwd (Windows)
  228. return
  229. finally:
  230. # If we created the lock, ensure we remove it even if we failed
  231. # to properly remove the numbered dir.
  232. if lock_path is not None:
  233. try:
  234. lock_path.unlink()
  235. except OSError:
  236. pass
  237. def ensure_deletable(path: Path, consider_lock_dead_if_created_before: float) -> bool:
  238. """Check if `path` is deletable based on whether the lock file is expired."""
  239. if path.is_symlink():
  240. return False
  241. lock = get_lock_path(path)
  242. try:
  243. if not lock.is_file():
  244. return True
  245. except OSError:
  246. # we might not have access to the lock file at all, in this case assume
  247. # we don't have access to the entire directory (#7491).
  248. return False
  249. try:
  250. lock_time = lock.stat().st_mtime
  251. except Exception:
  252. return False
  253. else:
  254. if lock_time < consider_lock_dead_if_created_before:
  255. # We want to ignore any errors while trying to remove the lock such as:
  256. # - PermissionDenied, like the file permissions have changed since the lock creation;
  257. # - FileNotFoundError, in case another pytest process got here first;
  258. # and any other cause of failure.
  259. with contextlib.suppress(OSError):
  260. lock.unlink()
  261. return True
  262. return False
  263. def try_cleanup(path: Path, consider_lock_dead_if_created_before: float) -> None:
  264. """Try to cleanup a folder if we can ensure it's deletable."""
  265. if ensure_deletable(path, consider_lock_dead_if_created_before):
  266. maybe_delete_a_numbered_dir(path)
  267. def cleanup_candidates(root: Path, prefix: str, keep: int) -> Iterator[Path]:
  268. """List candidates for numbered directories to be removed - follows py.path."""
  269. max_existing = max(map(parse_num, find_suffixes(root, prefix)), default=-1)
  270. max_delete = max_existing - keep
  271. paths = find_prefixed(root, prefix)
  272. paths, paths2 = itertools.tee(paths)
  273. numbers = map(parse_num, extract_suffixes(paths2, prefix))
  274. for path, number in zip(paths, numbers):
  275. if number <= max_delete:
  276. yield path
  277. def cleanup_numbered_dir(
  278. root: Path, prefix: str, keep: int, consider_lock_dead_if_created_before: float
  279. ) -> None:
  280. """Cleanup for lock driven numbered directories."""
  281. for path in cleanup_candidates(root, prefix, keep):
  282. try_cleanup(path, consider_lock_dead_if_created_before)
  283. for path in root.glob("garbage-*"):
  284. try_cleanup(path, consider_lock_dead_if_created_before)
  285. def make_numbered_dir_with_cleanup(
  286. root: Path,
  287. prefix: str,
  288. keep: int,
  289. lock_timeout: float,
  290. mode: int,
  291. ) -> Path:
  292. """Create a numbered dir with a cleanup lock and remove old ones."""
  293. e = None
  294. for i in range(10):
  295. try:
  296. p = make_numbered_dir(root, prefix, mode)
  297. lock_path = create_cleanup_lock(p)
  298. register_cleanup_lock_removal(lock_path)
  299. except Exception as exc:
  300. e = exc
  301. else:
  302. consider_lock_dead_if_created_before = p.stat().st_mtime - lock_timeout
  303. # Register a cleanup for program exit
  304. atexit.register(
  305. cleanup_numbered_dir,
  306. root,
  307. prefix,
  308. keep,
  309. consider_lock_dead_if_created_before,
  310. )
  311. return p
  312. assert e is not None
  313. raise e
  314. def resolve_from_str(input: str, rootpath: Path) -> Path:
  315. input = expanduser(input)
  316. input = expandvars(input)
  317. if isabs(input):
  318. return Path(input)
  319. else:
  320. return rootpath.joinpath(input)
  321. def fnmatch_ex(pattern: str, path: Union[str, "os.PathLike[str]"]) -> bool:
  322. """A port of FNMatcher from py.path.common which works with PurePath() instances.
  323. The difference between this algorithm and PurePath.match() is that the
  324. latter matches "**" glob expressions for each part of the path, while
  325. this algorithm uses the whole path instead.
  326. For example:
  327. "tests/foo/bar/doc/test_foo.py" matches pattern "tests/**/doc/test*.py"
  328. with this algorithm, but not with PurePath.match().
  329. This algorithm was ported to keep backward-compatibility with existing
  330. settings which assume paths match according this logic.
  331. References:
  332. * https://bugs.python.org/issue29249
  333. * https://bugs.python.org/issue34731
  334. """
  335. path = PurePath(path)
  336. iswin32 = sys.platform.startswith("win")
  337. if iswin32 and sep not in pattern and posix_sep in pattern:
  338. # Running on Windows, the pattern has no Windows path separators,
  339. # and the pattern has one or more Posix path separators. Replace
  340. # the Posix path separators with the Windows path separator.
  341. pattern = pattern.replace(posix_sep, sep)
  342. if sep not in pattern:
  343. name = path.name
  344. else:
  345. name = str(path)
  346. if path.is_absolute() and not os.path.isabs(pattern):
  347. pattern = f"*{os.sep}{pattern}"
  348. return fnmatch.fnmatch(name, pattern)
  349. def parts(s: str) -> Set[str]:
  350. parts = s.split(sep)
  351. return {sep.join(parts[: i + 1]) or sep for i in range(len(parts))}
  352. def symlink_or_skip(src, dst, **kwargs):
  353. """Make a symlink, or skip the test in case symlinks are not supported."""
  354. try:
  355. os.symlink(str(src), str(dst), **kwargs)
  356. except OSError as e:
  357. skip(f"symlinks not supported: {e}")
  358. class ImportMode(Enum):
  359. """Possible values for `mode` parameter of `import_path`."""
  360. prepend = "prepend"
  361. append = "append"
  362. importlib = "importlib"
  363. class ImportPathMismatchError(ImportError):
  364. """Raised on import_path() if there is a mismatch of __file__'s.
  365. This can happen when `import_path` is called multiple times with different filenames that has
  366. the same basename but reside in packages
  367. (for example "/tests1/test_foo.py" and "/tests2/test_foo.py").
  368. """
  369. def import_path(
  370. p: Union[str, "os.PathLike[str]"],
  371. *,
  372. mode: Union[str, ImportMode] = ImportMode.prepend,
  373. root: Path,
  374. ) -> ModuleType:
  375. """Import and return a module from the given path, which can be a file (a module) or
  376. a directory (a package).
  377. The import mechanism used is controlled by the `mode` parameter:
  378. * `mode == ImportMode.prepend`: the directory containing the module (or package, taking
  379. `__init__.py` files into account) will be put at the *start* of `sys.path` before
  380. being imported with `__import__.
  381. * `mode == ImportMode.append`: same as `prepend`, but the directory will be appended
  382. to the end of `sys.path`, if not already in `sys.path`.
  383. * `mode == ImportMode.importlib`: uses more fine control mechanisms provided by `importlib`
  384. to import the module, which avoids having to use `__import__` and muck with `sys.path`
  385. at all. It effectively allows having same-named test modules in different places.
  386. :param root:
  387. Used as an anchor when mode == ImportMode.importlib to obtain
  388. a unique name for the module being imported so it can safely be stored
  389. into ``sys.modules``.
  390. :raises ImportPathMismatchError:
  391. If after importing the given `path` and the module `__file__`
  392. are different. Only raised in `prepend` and `append` modes.
  393. """
  394. mode = ImportMode(mode)
  395. path = Path(p)
  396. if not path.exists():
  397. raise ImportError(path)
  398. if mode is ImportMode.importlib:
  399. module_name = module_name_from_path(path, root)
  400. for meta_importer in sys.meta_path:
  401. spec = meta_importer.find_spec(module_name, [str(path.parent)])
  402. if spec is not None:
  403. break
  404. else:
  405. spec = importlib.util.spec_from_file_location(module_name, str(path))
  406. if spec is None:
  407. raise ImportError(f"Can't find module {module_name} at location {path}")
  408. mod = importlib.util.module_from_spec(spec)
  409. sys.modules[module_name] = mod
  410. spec.loader.exec_module(mod) # type: ignore[union-attr]
  411. insert_missing_modules(sys.modules, module_name)
  412. return mod
  413. pkg_path = resolve_package_path(path)
  414. if pkg_path is not None:
  415. pkg_root = pkg_path.parent
  416. names = list(path.with_suffix("").relative_to(pkg_root).parts)
  417. if names[-1] == "__init__":
  418. names.pop()
  419. module_name = ".".join(names)
  420. else:
  421. pkg_root = path.parent
  422. module_name = path.stem
  423. # Change sys.path permanently: restoring it at the end of this function would cause surprising
  424. # problems because of delayed imports: for example, a conftest.py file imported by this function
  425. # might have local imports, which would fail at runtime if we restored sys.path.
  426. if mode is ImportMode.append:
  427. if str(pkg_root) not in sys.path:
  428. sys.path.append(str(pkg_root))
  429. elif mode is ImportMode.prepend:
  430. if str(pkg_root) != sys.path[0]:
  431. sys.path.insert(0, str(pkg_root))
  432. else:
  433. assert_never(mode)
  434. importlib.import_module(module_name)
  435. mod = sys.modules[module_name]
  436. if path.name == "__init__.py":
  437. return mod
  438. ignore = os.environ.get("PY_IGNORE_IMPORTMISMATCH", "")
  439. if ignore != "1":
  440. module_file = mod.__file__
  441. if module_file.endswith((".pyc", ".pyo")):
  442. module_file = module_file[:-1]
  443. if module_file.endswith(os.path.sep + "__init__.py"):
  444. module_file = module_file[: -(len(os.path.sep + "__init__.py"))]
  445. try:
  446. is_same = _is_same(str(path), module_file)
  447. except FileNotFoundError:
  448. is_same = False
  449. if not is_same:
  450. raise ImportPathMismatchError(module_name, module_file, path)
  451. return mod
  452. # Implement a special _is_same function on Windows which returns True if the two filenames
  453. # compare equal, to circumvent os.path.samefile returning False for mounts in UNC (#7678).
  454. if sys.platform.startswith("win"):
  455. def _is_same(f1: str, f2: str) -> bool:
  456. return Path(f1) == Path(f2) or os.path.samefile(f1, f2)
  457. else:
  458. def _is_same(f1: str, f2: str) -> bool:
  459. return os.path.samefile(f1, f2)
  460. def module_name_from_path(path: Path, root: Path) -> str:
  461. """
  462. Return a dotted module name based on the given path, anchored on root.
  463. For example: path="projects/src/tests/test_foo.py" and root="/projects", the
  464. resulting module name will be "src.tests.test_foo".
  465. """
  466. path = path.with_suffix("")
  467. try:
  468. relative_path = path.relative_to(root)
  469. except ValueError:
  470. # If we can't get a relative path to root, use the full path, except
  471. # for the first part ("d:\\" or "/" depending on the platform, for example).
  472. path_parts = path.parts[1:]
  473. else:
  474. # Use the parts for the relative path to the root path.
  475. path_parts = relative_path.parts
  476. return ".".join(path_parts)
  477. def insert_missing_modules(modules: Dict[str, ModuleType], module_name: str) -> None:
  478. """
  479. Used by ``import_path`` to create intermediate modules when using mode=importlib.
  480. When we want to import a module as "src.tests.test_foo" for example, we need
  481. to create empty modules "src" and "src.tests" after inserting "src.tests.test_foo",
  482. otherwise "src.tests.test_foo" is not importable by ``__import__``.
  483. """
  484. module_parts = module_name.split(".")
  485. while module_name:
  486. if module_name not in modules:
  487. module = ModuleType(
  488. module_name,
  489. doc="Empty module created by pytest's importmode=importlib.",
  490. )
  491. modules[module_name] = module
  492. module_parts.pop(-1)
  493. module_name = ".".join(module_parts)
  494. def resolve_package_path(path: Path) -> Optional[Path]:
  495. """Return the Python package path by looking for the last
  496. directory upwards which still contains an __init__.py.
  497. Returns None if it can not be determined.
  498. """
  499. result = None
  500. for parent in itertools.chain((path,), path.parents):
  501. if parent.is_dir():
  502. if not parent.joinpath("__init__.py").is_file():
  503. break
  504. if not parent.name.isidentifier():
  505. break
  506. result = parent
  507. return result
  508. def visit(
  509. path: Union[str, "os.PathLike[str]"], recurse: Callable[["os.DirEntry[str]"], bool]
  510. ) -> Iterator["os.DirEntry[str]"]:
  511. """Walk a directory recursively, in breadth-first order.
  512. Entries at each directory level are sorted.
  513. """
  514. # Skip entries with symlink loops and other brokenness, so the caller doesn't
  515. # have to deal with it.
  516. entries = []
  517. for entry in os.scandir(path):
  518. try:
  519. entry.is_file()
  520. except OSError as err:
  521. if _ignore_error(err):
  522. continue
  523. raise
  524. entries.append(entry)
  525. entries.sort(key=lambda entry: entry.name)
  526. yield from entries
  527. for entry in entries:
  528. if entry.is_dir() and recurse(entry):
  529. yield from visit(entry.path, recurse)
  530. def absolutepath(path: Union[Path, str]) -> Path:
  531. """Convert a path to an absolute path using os.path.abspath.
  532. Prefer this over Path.resolve() (see #6523).
  533. Prefer this over Path.absolute() (not public, doesn't normalize).
  534. """
  535. return Path(os.path.abspath(str(path)))
  536. def commonpath(path1: Path, path2: Path) -> Optional[Path]:
  537. """Return the common part shared with the other path, or None if there is
  538. no common part.
  539. If one path is relative and one is absolute, returns None.
  540. """
  541. try:
  542. return Path(os.path.commonpath((str(path1), str(path2))))
  543. except ValueError:
  544. return None
  545. def bestrelpath(directory: Path, dest: Path) -> str:
  546. """Return a string which is a relative path from directory to dest such
  547. that directory/bestrelpath == dest.
  548. The paths must be either both absolute or both relative.
  549. If no such path can be determined, returns dest.
  550. """
  551. assert isinstance(directory, Path)
  552. assert isinstance(dest, Path)
  553. if dest == directory:
  554. return os.curdir
  555. # Find the longest common directory.
  556. base = commonpath(directory, dest)
  557. # Can be the case on Windows for two absolute paths on different drives.
  558. # Can be the case for two relative paths without common prefix.
  559. # Can be the case for a relative path and an absolute path.
  560. if not base:
  561. return str(dest)
  562. reldirectory = directory.relative_to(base)
  563. reldest = dest.relative_to(base)
  564. return os.path.join(
  565. # Back from directory to base.
  566. *([os.pardir] * len(reldirectory.parts)),
  567. # Forward from base to dest.
  568. *reldest.parts,
  569. )
  570. # Originates from py. path.local.copy(), with siginficant trims and adjustments.
  571. # TODO(py38): Replace with shutil.copytree(..., symlinks=True, dirs_exist_ok=True)
  572. def copytree(source: Path, target: Path) -> None:
  573. """Recursively copy a source directory to target."""
  574. assert source.is_dir()
  575. for entry in visit(source, recurse=lambda entry: not entry.is_symlink()):
  576. x = Path(entry)
  577. relpath = x.relative_to(source)
  578. newx = target / relpath
  579. newx.parent.mkdir(exist_ok=True)
  580. if x.is_symlink():
  581. newx.symlink_to(os.readlink(x))
  582. elif x.is_file():
  583. shutil.copyfile(x, newx)
  584. elif x.is_dir():
  585. newx.mkdir(exist_ok=True)