req_uninstall.py 24 KB

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