req_uninstall.py 23 KB

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