pathlib.py 26 KB

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