fstransactions.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. # Copyright (C) 2012, Ansgar Burchardt <ansgar@debian.org>
  2. #
  3. # This program is free software; you can redistribute it and/or modify
  4. # it under the terms of the GNU General Public License as published by
  5. # the Free Software Foundation; either version 2 of the License, or
  6. # (at your option) any later version.
  7. #
  8. # This program is distributed in the hope that it will be useful,
  9. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. # GNU General Public License for more details.
  12. #
  13. # You should have received a copy of the GNU General Public License along
  14. # with this program; if not, write to the Free Software Foundation, Inc.,
  15. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  16. """Transactions for filesystem actions
  17. """
  18. import errno
  19. import os
  20. import shutil
  21. from typing import IO, Optional
  22. class _FilesystemAction:
  23. @property
  24. def temporary_name(self) -> str:
  25. raise NotImplementedError()
  26. def check_for_temporary(self) -> None:
  27. try:
  28. if os.path.exists(self.temporary_name):
  29. raise OSError(errno.EEXIST, os.strerror(errno.EEXIST), self.temporary_name)
  30. except NotImplementedError:
  31. pass
  32. class _FilesystemCopyAction(_FilesystemAction):
  33. def __init__(self, source, destination, link=True, symlink=False, mode=None):
  34. self.destination = destination
  35. self.need_cleanup = False
  36. dirmode = 0o2755
  37. if mode is not None:
  38. dirmode = 0o2700 | mode
  39. # Allow +x for group and others if they have +r.
  40. if dirmode & 0o0040:
  41. dirmode = dirmode | 0o0010
  42. if dirmode & 0o0004:
  43. dirmode = dirmode | 0o0001
  44. self.check_for_temporary()
  45. destdir = os.path.dirname(self.destination)
  46. if not os.path.exists(destdir):
  47. os.makedirs(destdir, dirmode)
  48. if symlink:
  49. os.symlink(source, self.destination)
  50. elif link:
  51. try:
  52. os.link(source, self.destination)
  53. except OSError:
  54. shutil.copy2(source, self.destination)
  55. else:
  56. shutil.copy2(source, self.destination)
  57. self.need_cleanup = True
  58. if mode is not None:
  59. os.chmod(self.destination, mode)
  60. @property
  61. def temporary_name(self):
  62. return self.destination
  63. def commit(self):
  64. pass
  65. def rollback(self):
  66. if self.need_cleanup:
  67. os.unlink(self.destination)
  68. self.need_cleanup = False
  69. class _FilesystemUnlinkAction(_FilesystemAction):
  70. def __init__(self, path: str):
  71. self.path: str = path
  72. self.need_cleanup: bool = False
  73. self.check_for_temporary()
  74. os.rename(self.path, self.temporary_name)
  75. self.need_cleanup: bool = True
  76. @property
  77. def temporary_name(self) -> str:
  78. return "{0}.dak-rm".format(self.path)
  79. def commit(self) -> None:
  80. if self.need_cleanup:
  81. os.unlink(self.temporary_name)
  82. self.need_cleanup = False
  83. def rollback(self) -> None:
  84. if self.need_cleanup:
  85. os.rename(self.temporary_name, self.path)
  86. self.need_cleanup = False
  87. class _FilesystemCreateAction(_FilesystemAction):
  88. def __init__(self, path: str):
  89. self.path: str = path
  90. self.need_cleanup: bool = True
  91. @property
  92. def temporary_name(self) -> str:
  93. return self.path
  94. def commit(self) -> None:
  95. pass
  96. def rollback(self) -> None:
  97. if self.need_cleanup:
  98. os.unlink(self.path)
  99. self.need_cleanup = False
  100. class FilesystemTransaction:
  101. """transactions for filesystem actions"""
  102. def __init__(self):
  103. self.actions = []
  104. def copy(self, source: str, destination: str, link: bool = False, symlink: bool = False, mode: Optional[int] = None) -> None:
  105. """copy `source` to `destination`
  106. :param source: source file
  107. :param destination: destination file
  108. :param link: try hardlinking, falling back to copying
  109. :param symlink: create a symlink instead of copying
  110. :param mode: permissions to change `destination` to
  111. """
  112. if isinstance(mode, str):
  113. mode = int(mode, 8)
  114. self.actions.append(_FilesystemCopyAction(source, destination, link=link, symlink=symlink, mode=mode))
  115. def move(self, source: str, destination: str, mode: Optional[int] = None) -> None:
  116. """move `source` to `destination`
  117. :param source: source file
  118. :param destination: destination file
  119. :param mode: permissions to change `destination` to
  120. """
  121. self.copy(source, destination, link=True, mode=mode)
  122. self.unlink(source)
  123. def unlink(self, path: str) -> None:
  124. """unlink `path`
  125. :param path: file to unlink
  126. """
  127. self.actions.append(_FilesystemUnlinkAction(path))
  128. def create(self, path: str, mode: Optional[int] = None, text: bool = True) -> IO:
  129. """create `filename` and return file handle
  130. :param path: file to create
  131. :param mode: permissions for the new file
  132. :param text: open file in text mode
  133. :return: file handle of the new file
  134. """
  135. if isinstance(mode, str):
  136. mode = int(mode, 8)
  137. destdir = os.path.dirname(path)
  138. if not os.path.exists(destdir):
  139. os.makedirs(destdir, 0o2775)
  140. if os.path.exists(path):
  141. raise OSError(errno.EEXIST, os.strerror(errno.EEXIST), path)
  142. fh = open(path, 'w' if text else 'wb')
  143. self.actions.append(_FilesystemCreateAction(path))
  144. if mode is not None:
  145. os.chmod(path, mode)
  146. return fh
  147. def commit(self):
  148. """Commit all recorded actions."""
  149. try:
  150. for action in self.actions:
  151. action.commit()
  152. except:
  153. self.rollback()
  154. raise
  155. finally:
  156. self.actions = []
  157. def rollback(self):
  158. """Undo all recorded actions."""
  159. try:
  160. for action in self.actions:
  161. action.rollback()
  162. finally:
  163. self.actions = []
  164. def __enter__(self):
  165. return self
  166. def __exit__(self, type, value, traceback):
  167. if type is None:
  168. self.commit()
  169. else:
  170. self.rollback()
  171. return None