req_uninstall.py 23 KB

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