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.

req_uninstall.py 21KB

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