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.

286 lines
8.7 KiB

6 years ago
  1. # dblite.py module contributed by Ralf W. Grosse-Kunstleve.
  2. # Extended for Unicode by Steven Knight.
  3. from __future__ import print_function
  4. import os
  5. import pickle
  6. import shutil
  7. import time
  8. from SCons.compat import PICKLE_PROTOCOL
  9. keep_all_files = 00000
  10. ignore_corrupt_dbfiles = 0
  11. def corruption_warning(filename):
  12. print("Warning: Discarding corrupt database:", filename)
  13. try:
  14. unicode
  15. except NameError:
  16. def is_string(s):
  17. return isinstance(s, str)
  18. else:
  19. def is_string(s):
  20. return type(s) in (str, unicode)
  21. def is_bytes(s):
  22. return isinstance(s, bytes)
  23. try:
  24. unicode('a')
  25. except NameError:
  26. def unicode(s):
  27. return s
  28. dblite_suffix = '.dblite'
  29. # TODO: Does commenting this out break switching from py2/3?
  30. # if bytes is not str:
  31. # dblite_suffix += '.p3'
  32. tmp_suffix = '.tmp'
  33. class dblite(object):
  34. """
  35. Squirrel away references to the functions in various modules
  36. that we'll use when our __del__() method calls our sync() method
  37. during shutdown. We might get destroyed when Python is in the midst
  38. of tearing down the different modules we import in an essentially
  39. arbitrary order, and some of the various modules's global attributes
  40. may already be wiped out from under us.
  41. See the discussion at:
  42. http://mail.python.org/pipermail/python-bugs-list/2003-March/016877.html
  43. """
  44. _open = open
  45. _pickle_dump = staticmethod(pickle.dump)
  46. _pickle_protocol = PICKLE_PROTOCOL
  47. _os_chmod = os.chmod
  48. try:
  49. _os_chown = os.chown
  50. except AttributeError:
  51. _os_chown = None
  52. _os_rename = os.rename
  53. _os_unlink = os.unlink
  54. _shutil_copyfile = shutil.copyfile
  55. _time_time = time.time
  56. def __init__(self, file_base_name, flag, mode):
  57. assert flag in (None, "r", "w", "c", "n")
  58. if (flag is None): flag = "r"
  59. base, ext = os.path.splitext(file_base_name)
  60. if ext == dblite_suffix:
  61. # There's already a suffix on the file name, don't add one.
  62. self._file_name = file_base_name
  63. self._tmp_name = base + tmp_suffix
  64. else:
  65. self._file_name = file_base_name + dblite_suffix
  66. self._tmp_name = file_base_name + tmp_suffix
  67. self._flag = flag
  68. self._mode = mode
  69. self._dict = {}
  70. self._needs_sync = 00000
  71. if self._os_chown is not None and (os.geteuid() == 0 or os.getuid() == 0):
  72. # running as root; chown back to current owner/group when done
  73. try:
  74. statinfo = os.stat(self._file_name)
  75. self._chown_to = statinfo.st_uid
  76. self._chgrp_to = statinfo.st_gid
  77. except OSError as e:
  78. # db file doesn't exist yet.
  79. # Check os.environ for SUDO_UID, use if set
  80. self._chown_to = int(os.environ.get('SUDO_UID', -1))
  81. self._chgrp_to = int(os.environ.get('SUDO_GID', -1))
  82. else:
  83. self._chown_to = -1 # don't chown
  84. self._chgrp_to = -1 # don't chgrp
  85. if (self._flag == "n"):
  86. self._open(self._file_name, "wb", self._mode)
  87. else:
  88. try:
  89. f = self._open(self._file_name, "rb")
  90. except IOError as e:
  91. if (self._flag != "c"):
  92. raise e
  93. self._open(self._file_name, "wb", self._mode)
  94. else:
  95. p = f.read()
  96. if len(p) > 0:
  97. try:
  98. if bytes is not str:
  99. self._dict = pickle.loads(p, encoding='bytes')
  100. else:
  101. self._dict = pickle.loads(p)
  102. except (pickle.UnpicklingError, EOFError, KeyError):
  103. # Note how we catch KeyErrors too here, which might happen
  104. # when we don't have cPickle available (default pickle
  105. # throws it).
  106. if (ignore_corrupt_dbfiles == 0): raise
  107. if (ignore_corrupt_dbfiles == 1):
  108. corruption_warning(self._file_name)
  109. def close(self):
  110. if (self._needs_sync):
  111. self.sync()
  112. def __del__(self):
  113. self.close()
  114. def sync(self):
  115. self._check_writable()
  116. f = self._open(self._tmp_name, "wb", self._mode)
  117. self._pickle_dump(self._dict, f, self._pickle_protocol)
  118. f.close()
  119. # Windows doesn't allow renaming if the file exists, so unlink
  120. # it first, chmod'ing it to make sure we can do so. On UNIX, we
  121. # may not be able to chmod the file if it's owned by someone else
  122. # (e.g. from a previous run as root). We should still be able to
  123. # unlink() the file if the directory's writable, though, so ignore
  124. # any OSError exception thrown by the chmod() call.
  125. try:
  126. self._os_chmod(self._file_name, 0o777)
  127. except OSError:
  128. pass
  129. self._os_unlink(self._file_name)
  130. self._os_rename(self._tmp_name, self._file_name)
  131. if self._os_chown is not None and self._chown_to > 0: # don't chown to root or -1
  132. try:
  133. self._os_chown(self._file_name, self._chown_to, self._chgrp_to)
  134. except OSError:
  135. pass
  136. self._needs_sync = 00000
  137. if (keep_all_files):
  138. self._shutil_copyfile(
  139. self._file_name,
  140. self._file_name + "_" + str(int(self._time_time())))
  141. def _check_writable(self):
  142. if (self._flag == "r"):
  143. raise IOError("Read-only database: %s" % self._file_name)
  144. def __getitem__(self, key):
  145. return self._dict[key]
  146. def __setitem__(self, key, value):
  147. self._check_writable()
  148. if (not is_string(key)):
  149. raise TypeError("key `%s' must be a string but is %s" % (key, type(key)))
  150. if (not is_bytes(value)):
  151. raise TypeError("value `%s' must be a bytes but is %s" % (value, type(value)))
  152. self._dict[key] = value
  153. self._needs_sync = 0o001
  154. def keys(self):
  155. return list(self._dict.keys())
  156. def has_key(self, key):
  157. return key in self._dict
  158. def __contains__(self, key):
  159. return key in self._dict
  160. def iterkeys(self):
  161. # Wrapping name in () prevents fixer from "fixing" this
  162. return (self._dict.iterkeys)()
  163. __iter__ = iterkeys
  164. def __len__(self):
  165. return len(self._dict)
  166. def open(file, flag=None, mode=0o666):
  167. return dblite(file, flag, mode)
  168. def _exercise():
  169. db = open("tmp", "n")
  170. assert len(db) == 0
  171. db["foo"] = "bar"
  172. assert db["foo"] == "bar"
  173. db[unicode("ufoo")] = unicode("ubar")
  174. assert db[unicode("ufoo")] == unicode("ubar")
  175. db.sync()
  176. db = open("tmp", "c")
  177. assert len(db) == 2, len(db)
  178. assert db["foo"] == "bar"
  179. db["bar"] = "foo"
  180. assert db["bar"] == "foo"
  181. db[unicode("ubar")] = unicode("ufoo")
  182. assert db[unicode("ubar")] == unicode("ufoo")
  183. db.sync()
  184. db = open("tmp", "r")
  185. assert len(db) == 4, len(db)
  186. assert db["foo"] == "bar"
  187. assert db["bar"] == "foo"
  188. assert db[unicode("ufoo")] == unicode("ubar")
  189. assert db[unicode("ubar")] == unicode("ufoo")
  190. try:
  191. db.sync()
  192. except IOError as e:
  193. assert str(e) == "Read-only database: tmp.dblite"
  194. else:
  195. raise RuntimeError("IOError expected.")
  196. db = open("tmp", "w")
  197. assert len(db) == 4
  198. db["ping"] = "pong"
  199. db.sync()
  200. try:
  201. db[(1, 2)] = "tuple"
  202. except TypeError as e:
  203. assert str(e) == "key `(1, 2)' must be a string but is <type 'tuple'>", str(e)
  204. else:
  205. raise RuntimeError("TypeError exception expected")
  206. try:
  207. db["list"] = [1, 2]
  208. except TypeError as e:
  209. assert str(e) == "value `[1, 2]' must be a string but is <type 'list'>", str(e)
  210. else:
  211. raise RuntimeError("TypeError exception expected")
  212. db = open("tmp", "r")
  213. assert len(db) == 5
  214. db = open("tmp", "n")
  215. assert len(db) == 0
  216. dblite._open("tmp.dblite", "w")
  217. db = open("tmp", "r")
  218. dblite._open("tmp.dblite", "w").write("x")
  219. try:
  220. db = open("tmp", "r")
  221. except pickle.UnpicklingError:
  222. pass
  223. else:
  224. raise RuntimeError("pickle exception expected.")
  225. global ignore_corrupt_dbfiles
  226. ignore_corrupt_dbfiles = 2
  227. db = open("tmp", "r")
  228. assert len(db) == 0
  229. os.unlink("tmp.dblite")
  230. try:
  231. db = open("tmp", "w")
  232. except IOError as e:
  233. assert str(e) == "[Errno 2] No such file or directory: 'tmp.dblite'", str(e)
  234. else:
  235. raise RuntimeError("IOError expected.")
  236. if (__name__ == "__main__"):
  237. _exercise()
  238. # Local Variables:
  239. # tab-width:4
  240. # indent-tabs-mode:nil
  241. # End:
  242. # vim: set expandtab tabstop=4 shiftwidth=4: