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.

426 lines
13 KiB

6 years ago
  1. """SCons.SConsign
  2. Writing and reading information to the .sconsign file or files.
  3. """
  4. #
  5. # Copyright (c) 2001 - 2017 The SCons Foundation
  6. #
  7. # Permission is hereby granted, free of charge, to any person obtaining
  8. # a copy of this software and associated documentation files (the
  9. # "Software"), to deal in the Software without restriction, including
  10. # without limitation the rights to use, copy, modify, merge, publish,
  11. # distribute, sublicense, and/or sell copies of the Software, and to
  12. # permit persons to whom the Software is furnished to do so, subject to
  13. # the following conditions:
  14. #
  15. # The above copyright notice and this permission notice shall be included
  16. # in all copies or substantial portions of the Software.
  17. #
  18. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
  19. # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
  20. # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  21. # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  22. # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  23. # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  24. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  25. #
  26. from __future__ import print_function
  27. __revision__ = "src/engine/SCons/SConsign.py rel_3.0.0:4395:8972f6a2f699 2017/09/18 12:59:24 bdbaddog"
  28. import SCons.compat
  29. import os
  30. import pickle
  31. import SCons.dblite
  32. import SCons.Warnings
  33. from SCons.compat import PICKLE_PROTOCOL
  34. def corrupt_dblite_warning(filename):
  35. SCons.Warnings.warn(SCons.Warnings.CorruptSConsignWarning,
  36. "Ignoring corrupt .sconsign file: %s"%filename)
  37. SCons.dblite.ignore_corrupt_dbfiles = 1
  38. SCons.dblite.corruption_warning = corrupt_dblite_warning
  39. # XXX Get rid of the global array so this becomes re-entrant.
  40. sig_files = []
  41. # Info for the database SConsign implementation (now the default):
  42. # "DataBase" is a dictionary that maps top-level SConstruct directories
  43. # to open database handles.
  44. # "DB_Module" is the Python database module to create the handles.
  45. # "DB_Name" is the base name of the database file (minus any
  46. # extension the underlying DB module will add).
  47. DataBase = {}
  48. DB_Module = SCons.dblite
  49. DB_Name = ".sconsign"
  50. DB_sync_list = []
  51. def Get_DataBase(dir):
  52. global DataBase, DB_Module, DB_Name
  53. top = dir.fs.Top
  54. if not os.path.isabs(DB_Name) and top.repositories:
  55. mode = "c"
  56. for d in [top] + top.repositories:
  57. if dir.is_under(d):
  58. try:
  59. return DataBase[d], mode
  60. except KeyError:
  61. path = d.entry_abspath(DB_Name)
  62. try: db = DataBase[d] = DB_Module.open(path, mode)
  63. except (IOError, OSError): pass
  64. else:
  65. if mode != "r":
  66. DB_sync_list.append(db)
  67. return db, mode
  68. mode = "r"
  69. try:
  70. return DataBase[top], "c"
  71. except KeyError:
  72. db = DataBase[top] = DB_Module.open(DB_Name, "c")
  73. DB_sync_list.append(db)
  74. return db, "c"
  75. except TypeError:
  76. print("DataBase =", DataBase)
  77. raise
  78. def Reset():
  79. """Reset global state. Used by unit tests that end up using
  80. SConsign multiple times to get a clean slate for each test."""
  81. global sig_files, DB_sync_list
  82. sig_files = []
  83. DB_sync_list = []
  84. normcase = os.path.normcase
  85. def write():
  86. global sig_files
  87. for sig_file in sig_files:
  88. sig_file.write(sync=0)
  89. for db in DB_sync_list:
  90. try:
  91. syncmethod = db.sync
  92. except AttributeError:
  93. pass # Not all dbm modules have sync() methods.
  94. else:
  95. syncmethod()
  96. try:
  97. closemethod = db.close
  98. except AttributeError:
  99. pass # Not all dbm modules have close() methods.
  100. else:
  101. closemethod()
  102. class SConsignEntry(object):
  103. """
  104. Wrapper class for the generic entry in a .sconsign file.
  105. The Node subclass populates it with attributes as it pleases.
  106. XXX As coded below, we do expect a '.binfo' attribute to be added,
  107. but we'll probably generalize this in the next refactorings.
  108. """
  109. __slots__ = ("binfo", "ninfo", "__weakref__")
  110. current_version_id = 2
  111. def __init__(self):
  112. # Create an object attribute from the class attribute so it ends up
  113. # in the pickled data in the .sconsign file.
  114. #_version_id = self.current_version_id
  115. pass
  116. def convert_to_sconsign(self):
  117. self.binfo.convert_to_sconsign()
  118. def convert_from_sconsign(self, dir, name):
  119. self.binfo.convert_from_sconsign(dir, name)
  120. def __getstate__(self):
  121. state = getattr(self, '__dict__', {}).copy()
  122. for obj in type(self).mro():
  123. for name in getattr(obj,'__slots__',()):
  124. if hasattr(self, name):
  125. state[name] = getattr(self, name)
  126. state['_version_id'] = self.current_version_id
  127. try:
  128. del state['__weakref__']
  129. except KeyError:
  130. pass
  131. return state
  132. def __setstate__(self, state):
  133. for key, value in state.items():
  134. if key not in ('_version_id','__weakref__'):
  135. setattr(self, key, value)
  136. class Base(object):
  137. """
  138. This is the controlling class for the signatures for the collection of
  139. entries associated with a specific directory. The actual directory
  140. association will be maintained by a subclass that is specific to
  141. the underlying storage method. This class provides a common set of
  142. methods for fetching and storing the individual bits of information
  143. that make up signature entry.
  144. """
  145. def __init__(self):
  146. self.entries = {}
  147. self.dirty = False
  148. self.to_be_merged = {}
  149. def get_entry(self, filename):
  150. """
  151. Fetch the specified entry attribute.
  152. """
  153. return self.entries[filename]
  154. def set_entry(self, filename, obj):
  155. """
  156. Set the entry.
  157. """
  158. self.entries[filename] = obj
  159. self.dirty = True
  160. def do_not_set_entry(self, filename, obj):
  161. pass
  162. def store_info(self, filename, node):
  163. entry = node.get_stored_info()
  164. entry.binfo.merge(node.get_binfo())
  165. self.to_be_merged[filename] = node
  166. self.dirty = True
  167. def do_not_store_info(self, filename, node):
  168. pass
  169. def merge(self):
  170. for key, node in self.to_be_merged.items():
  171. entry = node.get_stored_info()
  172. try:
  173. ninfo = entry.ninfo
  174. except AttributeError:
  175. # This happens with SConf Nodes, because the configuration
  176. # subsystem takes direct control over how the build decision
  177. # is made and its information stored.
  178. pass
  179. else:
  180. ninfo.merge(node.get_ninfo())
  181. self.entries[key] = entry
  182. self.to_be_merged = {}
  183. class DB(Base):
  184. """
  185. A Base subclass that reads and writes signature information
  186. from a global .sconsign.db* file--the actual file suffix is
  187. determined by the database module.
  188. """
  189. def __init__(self, dir):
  190. Base.__init__(self)
  191. self.dir = dir
  192. db, mode = Get_DataBase(dir)
  193. # Read using the path relative to the top of the Repository
  194. # (self.dir.tpath) from which we're fetching the signature
  195. # information.
  196. path = normcase(dir.get_tpath())
  197. try:
  198. rawentries = db[path]
  199. except KeyError:
  200. pass
  201. else:
  202. try:
  203. self.entries = pickle.loads(rawentries)
  204. if not isinstance(self.entries, dict):
  205. self.entries = {}
  206. raise TypeError
  207. except KeyboardInterrupt:
  208. raise
  209. except Exception as e:
  210. SCons.Warnings.warn(SCons.Warnings.CorruptSConsignWarning,
  211. "Ignoring corrupt sconsign entry : %s (%s)\n"%(self.dir.get_tpath(), e))
  212. for key, entry in self.entries.items():
  213. entry.convert_from_sconsign(dir, key)
  214. if mode == "r":
  215. # This directory is actually under a repository, which means
  216. # likely they're reaching in directly for a dependency on
  217. # a file there. Don't actually set any entry info, so we
  218. # won't try to write to that .sconsign.dblite file.
  219. self.set_entry = self.do_not_set_entry
  220. self.store_info = self.do_not_store_info
  221. global sig_files
  222. sig_files.append(self)
  223. def write(self, sync=1):
  224. if not self.dirty:
  225. return
  226. self.merge()
  227. db, mode = Get_DataBase(self.dir)
  228. # Write using the path relative to the top of the SConstruct
  229. # directory (self.dir.path), not relative to the top of
  230. # the Repository; we only write to our own .sconsign file,
  231. # not to .sconsign files in Repositories.
  232. path = normcase(self.dir.get_internal_path())
  233. for key, entry in self.entries.items():
  234. entry.convert_to_sconsign()
  235. db[path] = pickle.dumps(self.entries, PICKLE_PROTOCOL)
  236. if sync:
  237. try:
  238. syncmethod = db.sync
  239. except AttributeError:
  240. # Not all anydbm modules have sync() methods.
  241. pass
  242. else:
  243. syncmethod()
  244. class Dir(Base):
  245. def __init__(self, fp=None, dir=None):
  246. """
  247. fp - file pointer to read entries from
  248. """
  249. Base.__init__(self)
  250. if not fp:
  251. return
  252. self.entries = pickle.load(fp)
  253. if not isinstance(self.entries, dict):
  254. self.entries = {}
  255. raise TypeError
  256. if dir:
  257. for key, entry in self.entries.items():
  258. entry.convert_from_sconsign(dir, key)
  259. class DirFile(Dir):
  260. """
  261. Encapsulates reading and writing a per-directory .sconsign file.
  262. """
  263. def __init__(self, dir):
  264. """
  265. dir - the directory for the file
  266. """
  267. self.dir = dir
  268. self.sconsign = os.path.join(dir.get_internal_path(), '.sconsign')
  269. try:
  270. fp = open(self.sconsign, 'rb')
  271. except IOError:
  272. fp = None
  273. try:
  274. Dir.__init__(self, fp, dir)
  275. except KeyboardInterrupt:
  276. raise
  277. except:
  278. SCons.Warnings.warn(SCons.Warnings.CorruptSConsignWarning,
  279. "Ignoring corrupt .sconsign file: %s"%self.sconsign)
  280. global sig_files
  281. sig_files.append(self)
  282. def write(self, sync=1):
  283. """
  284. Write the .sconsign file to disk.
  285. Try to write to a temporary file first, and rename it if we
  286. succeed. If we can't write to the temporary file, it's
  287. probably because the directory isn't writable (and if so,
  288. how did we build anything in this directory, anyway?), so
  289. try to write directly to the .sconsign file as a backup.
  290. If we can't rename, try to copy the temporary contents back
  291. to the .sconsign file. Either way, always try to remove
  292. the temporary file at the end.
  293. """
  294. if not self.dirty:
  295. return
  296. self.merge()
  297. temp = os.path.join(self.dir.get_internal_path(), '.scons%d' % os.getpid())
  298. try:
  299. file = open(temp, 'wb')
  300. fname = temp
  301. except IOError:
  302. try:
  303. file = open(self.sconsign, 'wb')
  304. fname = self.sconsign
  305. except IOError:
  306. return
  307. for key, entry in self.entries.items():
  308. entry.convert_to_sconsign()
  309. pickle.dump(self.entries, file, PICKLE_PROTOCOL)
  310. file.close()
  311. if fname != self.sconsign:
  312. try:
  313. mode = os.stat(self.sconsign)[0]
  314. os.chmod(self.sconsign, 0o666)
  315. os.unlink(self.sconsign)
  316. except (IOError, OSError):
  317. # Try to carry on in the face of either OSError
  318. # (things like permission issues) or IOError (disk
  319. # or network issues). If there's a really dangerous
  320. # issue, it should get re-raised by the calls below.
  321. pass
  322. try:
  323. os.rename(fname, self.sconsign)
  324. except OSError:
  325. # An OSError failure to rename may indicate something
  326. # like the directory has no write permission, but
  327. # the .sconsign file itself might still be writable,
  328. # so try writing on top of it directly. An IOError
  329. # here, or in any of the following calls, would get
  330. # raised, indicating something like a potentially
  331. # serious disk or network issue.
  332. open(self.sconsign, 'wb').write(open(fname, 'rb').read())
  333. os.chmod(self.sconsign, mode)
  334. try:
  335. os.unlink(temp)
  336. except (IOError, OSError):
  337. pass
  338. ForDirectory = DB
  339. def File(name, dbm_module=None):
  340. """
  341. Arrange for all signatures to be stored in a global .sconsign.db*
  342. file.
  343. """
  344. global ForDirectory, DB_Name, DB_Module
  345. if name is None:
  346. ForDirectory = DirFile
  347. DB_Module = None
  348. else:
  349. ForDirectory = DB
  350. DB_Name = name
  351. if not dbm_module is None:
  352. DB_Module = dbm_module
  353. # Local Variables:
  354. # tab-width:4
  355. # indent-tabs-mode:nil
  356. # End:
  357. # vim: set expandtab tabstop=4 shiftwidth=4: