m2m模型翻译
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

649 lines
24 KiB

6 months ago
  1. import functools
  2. import os
  3. import sys
  4. import sysconfig
  5. from importlib.util import cache_from_source
  6. from typing import Any, Callable, Dict, Generator, Iterable, List, Optional, Set, Tuple
  7. from pip._internal.exceptions import UninstallationError
  8. from pip._internal.locations import get_bin_prefix, get_bin_user
  9. from pip._internal.metadata import BaseDistribution
  10. from pip._internal.utils.compat import WINDOWS
  11. from pip._internal.utils.egg_link import egg_link_path_from_location
  12. from pip._internal.utils.logging import getLogger, indent_log
  13. from pip._internal.utils.misc import ask, normalize_path, renames, rmtree
  14. from pip._internal.utils.temp_dir import AdjacentTempDirectory, TempDirectory
  15. from pip._internal.utils.virtualenv import running_under_virtualenv
  16. logger = getLogger(__name__)
  17. def _script_names(
  18. bin_dir: str, script_name: str, is_gui: bool
  19. ) -> Generator[str, None, None]:
  20. """Create the fully qualified name of the files created by
  21. {console,gui}_scripts for the given ``dist``.
  22. Returns the list of file names
  23. """
  24. exe_name = os.path.join(bin_dir, script_name)
  25. yield exe_name
  26. if not WINDOWS:
  27. return
  28. yield f"{exe_name}.exe"
  29. yield f"{exe_name}.exe.manifest"
  30. if is_gui:
  31. yield f"{exe_name}-script.pyw"
  32. else:
  33. yield f"{exe_name}-script.py"
  34. def _unique(
  35. fn: Callable[..., Generator[Any, None, None]]
  36. ) -> Callable[..., Generator[Any, None, None]]:
  37. @functools.wraps(fn)
  38. def unique(*args: Any, **kw: Any) -> Generator[Any, None, None]:
  39. seen: Set[Any] = set()
  40. for item in fn(*args, **kw):
  41. if item not in seen:
  42. seen.add(item)
  43. yield item
  44. return unique
  45. @_unique
  46. def uninstallation_paths(dist: BaseDistribution) -> Generator[str, None, None]:
  47. """
  48. Yield all the uninstallation paths for dist based on RECORD-without-.py[co]
  49. Yield paths to all the files in RECORD. For each .py file in RECORD, add
  50. the .pyc and .pyo in the same directory.
  51. UninstallPathSet.add() takes care of the __pycache__ .py[co].
  52. If RECORD is not found, raises UninstallationError,
  53. with possible information from the INSTALLER file.
  54. https://packaging.python.org/specifications/recording-installed-packages/
  55. """
  56. location = dist.location
  57. assert location is not None, "not installed"
  58. entries = dist.iter_declared_entries()
  59. if entries is None:
  60. msg = f"Cannot uninstall {dist}, RECORD file not found."
  61. installer = dist.installer
  62. if not installer or installer == "pip":
  63. dep = f"{dist.raw_name}=={dist.version}"
  64. msg += (
  65. " You might be able to recover from this via: "
  66. f"'pip install --force-reinstall --no-deps {dep}'."
  67. )
  68. else:
  69. msg += f" Hint: The package was installed by {installer}."
  70. raise UninstallationError(msg)
  71. for entry in entries:
  72. path = os.path.join(location, entry)
  73. yield path
  74. if path.endswith(".py"):
  75. dn, fn = os.path.split(path)
  76. base = fn[:-3]
  77. path = os.path.join(dn, base + ".pyc")
  78. yield path
  79. path = os.path.join(dn, base + ".pyo")
  80. yield path
  81. def compact(paths: Iterable[str]) -> Set[str]:
  82. """Compact a path set to contain the minimal number of paths
  83. necessary to contain all paths in the set. If /a/path/ and
  84. /a/path/to/a/file.txt are both in the set, leave only the
  85. shorter path."""
  86. sep = os.path.sep
  87. short_paths: Set[str] = set()
  88. for path in sorted(paths, key=len):
  89. should_skip = any(
  90. path.startswith(shortpath.rstrip("*"))
  91. and path[len(shortpath.rstrip("*").rstrip(sep))] == sep
  92. for shortpath in short_paths
  93. )
  94. if not should_skip:
  95. short_paths.add(path)
  96. return short_paths
  97. def compress_for_rename(paths: Iterable[str]) -> Set[str]:
  98. """Returns a set containing the paths that need to be renamed.
  99. This set may include directories when the original sequence of paths
  100. included every file on disk.
  101. """
  102. case_map = {os.path.normcase(p): p for p in paths}
  103. remaining = set(case_map)
  104. unchecked = sorted({os.path.split(p)[0] for p in case_map.values()}, key=len)
  105. wildcards: Set[str] = set()
  106. def norm_join(*a: str) -> str:
  107. return os.path.normcase(os.path.join(*a))
  108. for root in unchecked:
  109. if any(os.path.normcase(root).startswith(w) for w in wildcards):
  110. # This directory has already been handled.
  111. continue
  112. all_files: Set[str] = set()
  113. all_subdirs: Set[str] = set()
  114. for dirname, subdirs, files in os.walk(root):
  115. all_subdirs.update(norm_join(root, dirname, d) for d in subdirs)
  116. all_files.update(norm_join(root, dirname, f) for f in files)
  117. # If all the files we found are in our remaining set of files to
  118. # remove, then remove them from the latter set and add a wildcard
  119. # for the directory.
  120. if not (all_files - remaining):
  121. remaining.difference_update(all_files)
  122. wildcards.add(root + os.sep)
  123. return set(map(case_map.__getitem__, remaining)) | wildcards
  124. def compress_for_output_listing(paths: Iterable[str]) -> Tuple[Set[str], Set[str]]:
  125. """Returns a tuple of 2 sets of which paths to display to user
  126. The first set contains paths that would be deleted. Files of a package
  127. are not added and the top-level directory of the package has a '*' added
  128. at the end - to signify that all it's contents are removed.
  129. The second set contains files that would have been skipped in the above
  130. folders.
  131. """
  132. will_remove = set(paths)
  133. will_skip = set()
  134. # Determine folders and files
  135. folders = set()
  136. files = set()
  137. for path in will_remove:
  138. if path.endswith(".pyc"):
  139. continue
  140. if path.endswith("__init__.py") or ".dist-info" in path:
  141. folders.add(os.path.dirname(path))
  142. files.add(path)
  143. _normcased_files = set(map(os.path.normcase, files))
  144. folders = compact(folders)
  145. # This walks the tree using os.walk to not miss extra folders
  146. # that might get added.
  147. for folder in folders:
  148. for dirpath, _, dirfiles in os.walk(folder):
  149. for fname in dirfiles:
  150. if fname.endswith(".pyc"):
  151. continue
  152. file_ = os.path.join(dirpath, fname)
  153. if (
  154. os.path.isfile(file_)
  155. and os.path.normcase(file_) not in _normcased_files
  156. ):
  157. # We are skipping this file. Add it to the set.
  158. will_skip.add(file_)
  159. will_remove = files | {os.path.join(folder, "*") for folder in folders}
  160. return will_remove, will_skip
  161. class StashedUninstallPathSet:
  162. """A set of file rename operations to stash files while
  163. tentatively uninstalling them."""
  164. def __init__(self) -> None:
  165. # Mapping from source file root to [Adjacent]TempDirectory
  166. # for files under that directory.
  167. self._save_dirs: Dict[str, TempDirectory] = {}
  168. # (old path, new path) tuples for each move that may need
  169. # to be undone.
  170. self._moves: List[Tuple[str, str]] = []
  171. def _get_directory_stash(self, path: str) -> str:
  172. """Stashes a directory.
  173. Directories are stashed adjacent to their original location if
  174. possible, or else moved/copied into the user's temp dir."""
  175. try:
  176. save_dir: TempDirectory = AdjacentTempDirectory(path)
  177. except OSError:
  178. save_dir = TempDirectory(kind="uninstall")
  179. self._save_dirs[os.path.normcase(path)] = save_dir
  180. return save_dir.path
  181. def _get_file_stash(self, path: str) -> str:
  182. """Stashes a file.
  183. If no root has been provided, one will be created for the directory
  184. in the user's temp directory."""
  185. path = os.path.normcase(path)
  186. head, old_head = os.path.dirname(path), None
  187. save_dir = None
  188. while head != old_head:
  189. try:
  190. save_dir = self._save_dirs[head]
  191. break
  192. except KeyError:
  193. pass
  194. head, old_head = os.path.dirname(head), head
  195. else:
  196. # Did not find any suitable root
  197. head = os.path.dirname(path)
  198. save_dir = TempDirectory(kind="uninstall")
  199. self._save_dirs[head] = save_dir
  200. relpath = os.path.relpath(path, head)
  201. if relpath and relpath != os.path.curdir:
  202. return os.path.join(save_dir.path, relpath)
  203. return save_dir.path
  204. def stash(self, path: str) -> str:
  205. """Stashes the directory or file and returns its new location.
  206. Handle symlinks as files to avoid modifying the symlink targets.
  207. """
  208. path_is_dir = os.path.isdir(path) and not os.path.islink(path)
  209. if path_is_dir:
  210. new_path = self._get_directory_stash(path)
  211. else:
  212. new_path = self._get_file_stash(path)
  213. self._moves.append((path, new_path))
  214. if path_is_dir and os.path.isdir(new_path):
  215. # If we're moving a directory, we need to
  216. # remove the destination first or else it will be
  217. # moved to inside the existing directory.
  218. # We just created new_path ourselves, so it will
  219. # be removable.
  220. os.rmdir(new_path)
  221. renames(path, new_path)
  222. return new_path
  223. def commit(self) -> None:
  224. """Commits the uninstall by removing stashed files."""
  225. for save_dir in self._save_dirs.values():
  226. save_dir.cleanup()
  227. self._moves = []
  228. self._save_dirs = {}
  229. def rollback(self) -> None:
  230. """Undoes the uninstall by moving stashed files back."""
  231. for p in self._moves:
  232. logger.info("Moving to %s\n from %s", *p)
  233. for new_path, path in self._moves:
  234. try:
  235. logger.debug("Replacing %s from %s", new_path, path)
  236. if os.path.isfile(new_path) or os.path.islink(new_path):
  237. os.unlink(new_path)
  238. elif os.path.isdir(new_path):
  239. rmtree(new_path)
  240. renames(path, new_path)
  241. except OSError as ex:
  242. logger.error("Failed to restore %s", new_path)
  243. logger.debug("Exception: %s", ex)
  244. self.commit()
  245. @property
  246. def can_rollback(self) -> bool:
  247. return bool(self._moves)
  248. class UninstallPathSet:
  249. """A set of file paths to be removed in the uninstallation of a
  250. requirement."""
  251. def __init__(self, dist: BaseDistribution) -> None:
  252. self._paths: Set[str] = set()
  253. self._refuse: Set[str] = set()
  254. self._pth: Dict[str, UninstallPthEntries] = {}
  255. self._dist = dist
  256. self._moved_paths = StashedUninstallPathSet()
  257. # Create local cache of normalize_path results. Creating an UninstallPathSet
  258. # can result in hundreds/thousands of redundant calls to normalize_path with
  259. # the same args, which hurts performance.
  260. self._normalize_path_cached = functools.lru_cache()(normalize_path)
  261. def _permitted(self, path: str) -> bool:
  262. """
  263. Return True if the given path is one we are permitted to
  264. remove/modify, False otherwise.
  265. """
  266. # aka is_local, but caching normalized sys.prefix
  267. if not running_under_virtualenv():
  268. return True
  269. return path.startswith(self._normalize_path_cached(sys.prefix))
  270. def add(self, path: str) -> None:
  271. head, tail = os.path.split(path)
  272. # we normalize the head to resolve parent directory symlinks, but not
  273. # the tail, since we only want to uninstall symlinks, not their targets
  274. path = os.path.join(self._normalize_path_cached(head), os.path.normcase(tail))
  275. if not os.path.exists(path):
  276. return
  277. if self._permitted(path):
  278. self._paths.add(path)
  279. else:
  280. self._refuse.add(path)
  281. # __pycache__ files can show up after 'installed-files.txt' is created,
  282. # due to imports
  283. if os.path.splitext(path)[1] == ".py":
  284. self.add(cache_from_source(path))
  285. def add_pth(self, pth_file: str, entry: str) -> None:
  286. pth_file = self._normalize_path_cached(pth_file)
  287. if self._permitted(pth_file):
  288. if pth_file not in self._pth:
  289. self._pth[pth_file] = UninstallPthEntries(pth_file)
  290. self._pth[pth_file].add(entry)
  291. else:
  292. self._refuse.add(pth_file)
  293. def remove(self, auto_confirm: bool = False, verbose: bool = False) -> None:
  294. """Remove paths in ``self._paths`` with confirmation (unless
  295. ``auto_confirm`` is True)."""
  296. if not self._paths:
  297. logger.info(
  298. "Can't uninstall '%s'. No files were found to uninstall.",
  299. self._dist.raw_name,
  300. )
  301. return
  302. dist_name_version = f"{self._dist.raw_name}-{self._dist.version}"
  303. logger.info("Uninstalling %s:", dist_name_version)
  304. with indent_log():
  305. if auto_confirm or self._allowed_to_proceed(verbose):
  306. moved = self._moved_paths
  307. for_rename = compress_for_rename(self._paths)
  308. for path in sorted(compact(for_rename)):
  309. moved.stash(path)
  310. logger.verbose("Removing file or directory %s", path)
  311. for pth in self._pth.values():
  312. pth.remove()
  313. logger.info("Successfully uninstalled %s", dist_name_version)
  314. def _allowed_to_proceed(self, verbose: bool) -> bool:
  315. """Display which files would be deleted and prompt for confirmation"""
  316. def _display(msg: str, paths: Iterable[str]) -> None:
  317. if not paths:
  318. return
  319. logger.info(msg)
  320. with indent_log():
  321. for path in sorted(compact(paths)):
  322. logger.info(path)
  323. if not verbose:
  324. will_remove, will_skip = compress_for_output_listing(self._paths)
  325. else:
  326. # In verbose mode, display all the files that are going to be
  327. # deleted.
  328. will_remove = set(self._paths)
  329. will_skip = set()
  330. _display("Would remove:", will_remove)
  331. _display("Would not remove (might be manually added):", will_skip)
  332. _display("Would not remove (outside of prefix):", self._refuse)
  333. if verbose:
  334. _display("Will actually move:", compress_for_rename(self._paths))
  335. return ask("Proceed (Y/n)? ", ("y", "n", "")) != "n"
  336. def rollback(self) -> None:
  337. """Rollback the changes previously made by remove()."""
  338. if not self._moved_paths.can_rollback:
  339. logger.error(
  340. "Can't roll back %s; was not uninstalled",
  341. self._dist.raw_name,
  342. )
  343. return
  344. logger.info("Rolling back uninstall of %s", self._dist.raw_name)
  345. self._moved_paths.rollback()
  346. for pth in self._pth.values():
  347. pth.rollback()
  348. def commit(self) -> None:
  349. """Remove temporary save dir: rollback will no longer be possible."""
  350. self._moved_paths.commit()
  351. @classmethod
  352. def from_dist(cls, dist: BaseDistribution) -> "UninstallPathSet":
  353. dist_location = dist.location
  354. info_location = dist.info_location
  355. if dist_location is None:
  356. logger.info(
  357. "Not uninstalling %s since it is not installed",
  358. dist.canonical_name,
  359. )
  360. return cls(dist)
  361. normalized_dist_location = normalize_path(dist_location)
  362. if not dist.local:
  363. logger.info(
  364. "Not uninstalling %s at %s, outside environment %s",
  365. dist.canonical_name,
  366. normalized_dist_location,
  367. sys.prefix,
  368. )
  369. return cls(dist)
  370. if normalized_dist_location in {
  371. p
  372. for p in {sysconfig.get_path("stdlib"), sysconfig.get_path("platstdlib")}
  373. if p
  374. }:
  375. logger.info(
  376. "Not uninstalling %s at %s, as it is in the standard library.",
  377. dist.canonical_name,
  378. normalized_dist_location,
  379. )
  380. return cls(dist)
  381. paths_to_remove = cls(dist)
  382. develop_egg_link = egg_link_path_from_location(dist.raw_name)
  383. # Distribution is installed with metadata in a "flat" .egg-info
  384. # directory. This means it is not a modern .dist-info installation, an
  385. # egg, or legacy editable.
  386. setuptools_flat_installation = (
  387. dist.installed_with_setuptools_egg_info
  388. and info_location is not None
  389. and os.path.exists(info_location)
  390. # If dist is editable and the location points to a ``.egg-info``,
  391. # we are in fact in the legacy editable case.
  392. and not info_location.endswith(f"{dist.setuptools_filename}.egg-info")
  393. )
  394. # Uninstall cases order do matter as in the case of 2 installs of the
  395. # same package, pip needs to uninstall the currently detected version
  396. if setuptools_flat_installation:
  397. if info_location is not None:
  398. paths_to_remove.add(info_location)
  399. installed_files = dist.iter_declared_entries()
  400. if installed_files is not None:
  401. for installed_file in installed_files:
  402. paths_to_remove.add(os.path.join(dist_location, installed_file))
  403. # FIXME: need a test for this elif block
  404. # occurs with --single-version-externally-managed/--record outside
  405. # of pip
  406. elif dist.is_file("top_level.txt"):
  407. try:
  408. namespace_packages = dist.read_text("namespace_packages.txt")
  409. except FileNotFoundError:
  410. namespaces = []
  411. else:
  412. namespaces = namespace_packages.splitlines(keepends=False)
  413. for top_level_pkg in [
  414. p
  415. for p in dist.read_text("top_level.txt").splitlines()
  416. if p and p not in namespaces
  417. ]:
  418. path = os.path.join(dist_location, top_level_pkg)
  419. paths_to_remove.add(path)
  420. paths_to_remove.add(f"{path}.py")
  421. paths_to_remove.add(f"{path}.pyc")
  422. paths_to_remove.add(f"{path}.pyo")
  423. elif dist.installed_by_distutils:
  424. raise UninstallationError(
  425. "Cannot uninstall {!r}. It is a distutils installed project "
  426. "and thus we cannot accurately determine which files belong "
  427. "to it which would lead to only a partial uninstall.".format(
  428. dist.raw_name,
  429. )
  430. )
  431. elif dist.installed_as_egg:
  432. # package installed by easy_install
  433. # We cannot match on dist.egg_name because it can slightly vary
  434. # i.e. setuptools-0.6c11-py2.6.egg vs setuptools-0.6rc11-py2.6.egg
  435. paths_to_remove.add(dist_location)
  436. easy_install_egg = os.path.split(dist_location)[1]
  437. easy_install_pth = os.path.join(
  438. os.path.dirname(dist_location),
  439. "easy-install.pth",
  440. )
  441. paths_to_remove.add_pth(easy_install_pth, "./" + easy_install_egg)
  442. elif dist.installed_with_dist_info:
  443. for path in uninstallation_paths(dist):
  444. paths_to_remove.add(path)
  445. elif develop_egg_link:
  446. # PEP 660 modern editable is handled in the ``.dist-info`` case
  447. # above, so this only covers the setuptools-style editable.
  448. with open(develop_egg_link) as fh:
  449. link_pointer = os.path.normcase(fh.readline().strip())
  450. normalized_link_pointer = paths_to_remove._normalize_path_cached(
  451. link_pointer
  452. )
  453. assert os.path.samefile(
  454. normalized_link_pointer, normalized_dist_location
  455. ), (
  456. f"Egg-link {develop_egg_link} (to {link_pointer}) does not match "
  457. f"installed location of {dist.raw_name} (at {dist_location})"
  458. )
  459. paths_to_remove.add(develop_egg_link)
  460. easy_install_pth = os.path.join(
  461. os.path.dirname(develop_egg_link), "easy-install.pth"
  462. )
  463. paths_to_remove.add_pth(easy_install_pth, dist_location)
  464. else:
  465. logger.debug(
  466. "Not sure how to uninstall: %s - Check: %s",
  467. dist,
  468. dist_location,
  469. )
  470. if dist.in_usersite:
  471. bin_dir = get_bin_user()
  472. else:
  473. bin_dir = get_bin_prefix()
  474. # find distutils scripts= scripts
  475. try:
  476. for script in dist.iter_distutils_script_names():
  477. paths_to_remove.add(os.path.join(bin_dir, script))
  478. if WINDOWS:
  479. paths_to_remove.add(os.path.join(bin_dir, f"{script}.bat"))
  480. except (FileNotFoundError, NotADirectoryError):
  481. pass
  482. # find console_scripts and gui_scripts
  483. def iter_scripts_to_remove(
  484. dist: BaseDistribution,
  485. bin_dir: str,
  486. ) -> Generator[str, None, None]:
  487. for entry_point in dist.iter_entry_points():
  488. if entry_point.group == "console_scripts":
  489. yield from _script_names(bin_dir, entry_point.name, False)
  490. elif entry_point.group == "gui_scripts":
  491. yield from _script_names(bin_dir, entry_point.name, True)
  492. for s in iter_scripts_to_remove(dist, bin_dir):
  493. paths_to_remove.add(s)
  494. return paths_to_remove
  495. class UninstallPthEntries:
  496. def __init__(self, pth_file: str) -> None:
  497. self.file = pth_file
  498. self.entries: Set[str] = set()
  499. self._saved_lines: Optional[List[bytes]] = None
  500. def add(self, entry: str) -> None:
  501. entry = os.path.normcase(entry)
  502. # On Windows, os.path.normcase converts the entry to use
  503. # backslashes. This is correct for entries that describe absolute
  504. # paths outside of site-packages, but all the others use forward
  505. # slashes.
  506. # os.path.splitdrive is used instead of os.path.isabs because isabs
  507. # treats non-absolute paths with drive letter markings like c:foo\bar
  508. # as absolute paths. It also does not recognize UNC paths if they don't
  509. # have more than "\\sever\share". Valid examples: "\\server\share\" or
  510. # "\\server\share\folder".
  511. if WINDOWS and not os.path.splitdrive(entry)[0]:
  512. entry = entry.replace("\\", "/")
  513. self.entries.add(entry)
  514. def remove(self) -> None:
  515. logger.verbose("Removing pth entries from %s:", self.file)
  516. # If the file doesn't exist, log a warning and return
  517. if not os.path.isfile(self.file):
  518. logger.warning("Cannot remove entries from nonexistent file %s", self.file)
  519. return
  520. with open(self.file, "rb") as fh:
  521. # windows uses '\r\n' with py3k, but uses '\n' with py2.x
  522. lines = fh.readlines()
  523. self._saved_lines = lines
  524. if any(b"\r\n" in line for line in lines):
  525. endline = "\r\n"
  526. else:
  527. endline = "\n"
  528. # handle missing trailing newline
  529. if lines and not lines[-1].endswith(endline.encode("utf-8")):
  530. lines[-1] = lines[-1] + endline.encode("utf-8")
  531. for entry in self.entries:
  532. try:
  533. logger.verbose("Removing entry: %s", entry)
  534. lines.remove((entry + endline).encode("utf-8"))
  535. except ValueError:
  536. pass
  537. with open(self.file, "wb") as fh:
  538. fh.writelines(lines)
  539. def rollback(self) -> bool:
  540. if self._saved_lines is None:
  541. logger.error("Cannot roll back changes to %s, none were made", self.file)
  542. return False
  543. logger.debug("Rolling %s back to previous state", self.file)
  544. with open(self.file, "wb") as fh:
  545. fh.writelines(self._saved_lines)
  546. return True