jack2 codebase
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.

350 lines
7.9KB

  1. #!/usr/bin/env python
  2. # encoding: utf-8
  3. # Thomas Nagy, 2005-2010 (ita)
  4. """
  5. ConfigSet: a special dict
  6. The values put in :py:class:`ConfigSet` must be lists
  7. """
  8. import copy, re, os
  9. from waflib import Logs, Utils
  10. re_imp = re.compile('^(#)*?([^#=]*?)\ =\ (.*?)$', re.M)
  11. class ConfigSet(object):
  12. """
  13. A dict that honor serialization and parent relationships. The serialization format
  14. is human-readable (python-like) and performed by using eval() and repr().
  15. For high performance prefer pickle. Do not store functions as they are not serializable.
  16. The values can be accessed by attributes or by keys::
  17. from waflib.ConfigSet import ConfigSet
  18. env = ConfigSet()
  19. env.FOO = 'test'
  20. env['FOO'] = 'test'
  21. """
  22. __slots__ = ('table', 'parent')
  23. def __init__(self, filename=None):
  24. self.table = {}
  25. """
  26. Internal dict holding the object values
  27. """
  28. #self.parent = None
  29. if filename:
  30. self.load(filename)
  31. def __contains__(self, key):
  32. """
  33. Enable the *in* syntax::
  34. if 'foo' in env:
  35. print(env['foo'])
  36. """
  37. if key in self.table: return True
  38. try: return self.parent.__contains__(key)
  39. except AttributeError: return False # parent may not exist
  40. def keys(self):
  41. """Dict interface (unknown purpose)"""
  42. keys = set()
  43. cur = self
  44. while cur:
  45. keys.update(cur.table.keys())
  46. cur = getattr(cur, 'parent', None)
  47. keys = list(keys)
  48. keys.sort()
  49. return keys
  50. def __str__(self):
  51. """Text representation of the ConfigSet (for debugging purposes)"""
  52. return "\n".join(["%r %r" % (x, self.__getitem__(x)) for x in self.keys()])
  53. def __getitem__(self, key):
  54. """
  55. Dictionary interface: get value from key::
  56. def configure(conf):
  57. conf.env['foo'] = {}
  58. print(env['foo'])
  59. """
  60. try:
  61. while 1:
  62. x = self.table.get(key, None)
  63. if not x is None:
  64. return x
  65. self = self.parent
  66. except AttributeError:
  67. return []
  68. def __setitem__(self, key, value):
  69. """
  70. Dictionary interface: get value from key
  71. """
  72. self.table[key] = value
  73. def __delitem__(self, key):
  74. """
  75. Dictionary interface: get value from key
  76. """
  77. self[key] = []
  78. def __getattr__(self, name):
  79. """
  80. Attribute access provided for convenience. The following forms are equivalent::
  81. def configure(conf):
  82. conf.env.value
  83. conf.env['value']
  84. """
  85. if name in self.__slots__:
  86. return object.__getattr__(self, name)
  87. else:
  88. return self[name]
  89. def __setattr__(self, name, value):
  90. """
  91. Attribute access provided for convenience. The following forms are equivalent::
  92. def configure(conf):
  93. conf.env.value = x
  94. env['value'] = x
  95. """
  96. if name in self.__slots__:
  97. object.__setattr__(self, name, value)
  98. else:
  99. self[name] = value
  100. def __delattr__(self, name):
  101. """
  102. Attribute access provided for convenience. The following forms are equivalent::
  103. def configure(conf):
  104. del env.value
  105. del env['value']
  106. """
  107. if name in self.__slots__:
  108. object.__delattr__(self, name)
  109. else:
  110. del self[name]
  111. def derive(self):
  112. """
  113. Returns a new ConfigSet deriving from self. The copy returned
  114. will be a shallow copy::
  115. from waflib.ConfigSet import ConfigSet
  116. env = ConfigSet()
  117. env.append_value('CFLAGS', ['-O2'])
  118. child = env.derive()
  119. child.CFLAGS.append('test') # warning! this will modify 'env'
  120. child.CFLAGS = ['-O3'] # new list, ok
  121. child.append_value('CFLAGS', ['-O3']) # ok
  122. Use :py:func:`ConfigSet.detach` to detach the child from the parent.
  123. """
  124. newenv = ConfigSet()
  125. newenv.parent = self
  126. return newenv
  127. def detach(self):
  128. """
  129. Detach self from its parent (if existing)
  130. Modifying the parent :py:class:`ConfigSet` will not change the current object
  131. Modifying this :py:class:`ConfigSet` will not modify the parent one.
  132. """
  133. tbl = self.get_merged_dict()
  134. try:
  135. delattr(self, 'parent')
  136. except AttributeError:
  137. pass
  138. else:
  139. keys = tbl.keys()
  140. for x in keys:
  141. tbl[x] = copy.deepcopy(tbl[x])
  142. self.table = tbl
  143. return self
  144. def get_flat(self, key):
  145. """
  146. Return a value as a string. If the input is a list, the value returned is space-separated.
  147. :param key: key to use
  148. :type key: string
  149. """
  150. s = self[key]
  151. if isinstance(s, str): return s
  152. return ' '.join(s)
  153. def _get_list_value_for_modification(self, key):
  154. """
  155. Return a list value for further modification.
  156. The list may be modified inplace and there is no need to do this afterwards::
  157. self.table[var] = value
  158. """
  159. try:
  160. value = self.table[key]
  161. except KeyError:
  162. try: value = self.parent[key]
  163. except AttributeError: value = []
  164. if isinstance(value, list):
  165. value = value[:]
  166. else:
  167. value = [value]
  168. else:
  169. if not isinstance(value, list):
  170. value = [value]
  171. self.table[key] = value
  172. return value
  173. def append_value(self, var, val):
  174. """
  175. Appends a value to the specified config key::
  176. def build(bld):
  177. bld.env.append_value('CFLAGS', ['-O2'])
  178. The value must be a list or a tuple
  179. """
  180. if isinstance(val, str): # if there were string everywhere we could optimize this
  181. val = [val]
  182. current_value = self._get_list_value_for_modification(var)
  183. current_value.extend(val)
  184. def prepend_value(self, var, val):
  185. """
  186. Prepends a value to the specified item::
  187. def configure(conf):
  188. conf.env.prepend_value('CFLAGS', ['-O2'])
  189. The value must be a list or a tuple
  190. """
  191. if isinstance(val, str):
  192. val = [val]
  193. self.table[var] = val + self._get_list_value_for_modification(var)
  194. def append_unique(self, var, val):
  195. """
  196. Append a value to the specified item only if it's not already present::
  197. def build(bld):
  198. bld.env.append_unique('CFLAGS', ['-O2', '-g'])
  199. The value must be a list or a tuple
  200. """
  201. if isinstance(val, str):
  202. val = [val]
  203. current_value = self._get_list_value_for_modification(var)
  204. for x in val:
  205. if x not in current_value:
  206. current_value.append(x)
  207. def get_merged_dict(self):
  208. """
  209. Compute the merged dictionary from the fusion of self and all its parent
  210. :rtype: a ConfigSet object
  211. """
  212. table_list = []
  213. env = self
  214. while 1:
  215. table_list.insert(0, env.table)
  216. try: env = env.parent
  217. except AttributeError: break
  218. merged_table = {}
  219. for table in table_list:
  220. merged_table.update(table)
  221. return merged_table
  222. def store(self, filename):
  223. """
  224. Write the :py:class:`ConfigSet` data into a file. See :py:meth:`ConfigSet.load` for reading such files.
  225. :param filename: file to use
  226. :type filename: string
  227. """
  228. try:
  229. os.makedirs(os.path.split(filename)[0])
  230. except OSError:
  231. pass
  232. buf = []
  233. merged_table = self.get_merged_dict()
  234. keys = list(merged_table.keys())
  235. keys.sort()
  236. try:
  237. fun = ascii
  238. except NameError:
  239. fun = repr
  240. for k in keys:
  241. if k != 'undo_stack':
  242. buf.append('%s = %s\n' % (k, fun(merged_table[k])))
  243. Utils.writef(filename, ''.join(buf))
  244. def load(self, filename):
  245. """
  246. Retrieve the :py:class:`ConfigSet` data from a file. See :py:meth:`ConfigSet.store` for writing such files
  247. :param filename: file to use
  248. :type filename: string
  249. """
  250. tbl = self.table
  251. code = Utils.readf(filename, m='rU')
  252. for m in re_imp.finditer(code):
  253. g = m.group
  254. tbl[g(2)] = eval(g(3))
  255. Logs.debug('env: %s' % str(self.table))
  256. def update(self, d):
  257. """
  258. Dictionary interface: replace values from another dict
  259. :param d: object to use the value from
  260. :type d: dict-like object
  261. """
  262. for k, v in d.items():
  263. self[k] = v
  264. def stash(self):
  265. """
  266. Store the object state, to provide a kind of transaction support::
  267. env = ConfigSet()
  268. env.stash()
  269. try:
  270. env.append_value('CFLAGS', '-O3')
  271. call_some_method(env)
  272. finally:
  273. env.revert()
  274. The history is kept in a stack, and is lost during the serialization by :py:meth:`ConfigSet.store`
  275. """
  276. orig = self.table
  277. tbl = self.table = self.table.copy()
  278. for x in tbl.keys():
  279. tbl[x] = copy.deepcopy(tbl[x])
  280. self.undo_stack = self.undo_stack + [orig]
  281. def commit(self):
  282. """
  283. Commits transactional changes. See :py:meth:`ConfigSet.stash`
  284. """
  285. self.undo_stack.pop(-1)
  286. def revert(self):
  287. """
  288. Reverts the object to a previous state. See :py:meth:`ConfigSet.stash`
  289. """
  290. self.table = self.undo_stack.pop(-1)