req_uninstall.py 23 KB

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