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.

343 lines
7.8KB

  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. def get_flat(self, key):
  144. """
  145. Return a value as a string. If the input is a list, the value returned is space-separated.
  146. :param key: key to use
  147. :type key: string
  148. """
  149. s = self[key]
  150. if isinstance(s, str): return s
  151. return ' '.join(s)
  152. def _get_list_value_for_modification(self, key):
  153. """
  154. Return a list value for further modification.
  155. The list may be modified inplace and there is no need to do this afterwards::
  156. self.table[var] = value
  157. """
  158. try:
  159. value = self.table[key]
  160. except KeyError:
  161. try: value = self.parent[key]
  162. except AttributeError: value = []
  163. if isinstance(value, list):
  164. value = value[:]
  165. else:
  166. value = [value]
  167. else:
  168. if not isinstance(value, list):
  169. value = [value]
  170. self.table[key] = value
  171. return value
  172. def append_value(self, var, val):
  173. """
  174. Appends a value to the specified config key::
  175. def build(bld):
  176. bld.env.append_value('CFLAGS', ['-O2'])
  177. The value must be a list or a tuple
  178. """
  179. if isinstance(val, str): # if there were string everywhere we could optimize this
  180. val = [val]
  181. current_value = self._get_list_value_for_modification(var)
  182. current_value.extend(val)
  183. def prepend_value(self, var, val):
  184. """
  185. Prepends a value to the specified item::
  186. def configure(conf):
  187. conf.env.prepend_value('CFLAGS', ['-O2'])
  188. The value must be a list or a tuple
  189. """
  190. if isinstance(val, str):
  191. val = [val]
  192. self.table[var] = val + self._get_list_value_for_modification(var)
  193. def append_unique(self, var, val):
  194. """
  195. Append a value to the specified item only if it's not already present::
  196. def build(bld):
  197. bld.env.append_unique('CFLAGS', ['-O2', '-g'])
  198. The value must be a list or a tuple
  199. """
  200. if isinstance(val, str):
  201. val = [val]
  202. current_value = self._get_list_value_for_modification(var)
  203. for x in val:
  204. if x not in current_value:
  205. current_value.append(x)
  206. def get_merged_dict(self):
  207. """
  208. Compute the merged dictionary from the fusion of self and all its parent
  209. :rtype: a ConfigSet object
  210. """
  211. table_list = []
  212. env = self
  213. while 1:
  214. table_list.insert(0, env.table)
  215. try: env = env.parent
  216. except AttributeError: break
  217. merged_table = {}
  218. for table in table_list:
  219. merged_table.update(table)
  220. return merged_table
  221. def store(self, filename):
  222. """
  223. Write the :py:class:`ConfigSet` data into a file. See :py:meth:`ConfigSet.load` for reading such files.
  224. :param filename: file to use
  225. :type filename: string
  226. """
  227. try:
  228. os.makedirs(os.path.split(filename)[0])
  229. except OSError:
  230. pass
  231. buf = []
  232. merged_table = self.get_merged_dict()
  233. keys = list(merged_table.keys())
  234. keys.sort()
  235. try:
  236. fun = ascii
  237. except NameError:
  238. fun = repr
  239. for k in keys:
  240. if k != 'undo_stack':
  241. buf.append('%s = %s\n' % (k, fun(merged_table[k])))
  242. Utils.writef(filename, ''.join(buf))
  243. def load(self, filename):
  244. """
  245. Retrieve the :py:class:`ConfigSet` data from a file. See :py:meth:`ConfigSet.store` for writing such files
  246. :param filename: file to use
  247. :type filename: string
  248. """
  249. tbl = self.table
  250. code = Utils.readf(filename, m='rU')
  251. for m in re_imp.finditer(code):
  252. g = m.group
  253. tbl[g(2)] = eval(g(3))
  254. Logs.debug('env: %s' % str(self.table))
  255. def update(self, d):
  256. """
  257. Dictionary interface: replace values from another dict
  258. :param d: object to use the value from
  259. :type d: dict-like object
  260. """
  261. for k, v in d.items():
  262. self[k] = v
  263. def stash(self):
  264. """
  265. Store the object state, to provide a kind of transaction support::
  266. env = ConfigSet()
  267. env.stash()
  268. try:
  269. env.append_value('CFLAGS', '-O3')
  270. call_some_method(env)
  271. finally:
  272. env.revert()
  273. The history is kept in a stack, and is lost during the serialization by :py:meth:`ConfigSet.store`
  274. """
  275. orig = self.table
  276. tbl = self.table = self.table.copy()
  277. for x in tbl.keys():
  278. tbl[x] = copy.deepcopy(tbl[x])
  279. self.undo_stack = self.undo_stack + [orig]
  280. def revert(self):
  281. """
  282. Reverts the object to a previous state. See :py:meth:`ConfigSet.stash`
  283. """
  284. self.table = self.undo_stack.pop(-1)