Templating.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. #!/usr/bin/env python2
  2. #
  3. # Copyright 2011 Nick Mathewson, Michael Stone
  4. #
  5. # You may do anything with this work that copyright law would normally
  6. # restrict, so long as you retain the above notice(s) and this license
  7. # in all redistributed copies and derived works. There is no warranty.
  8. """
  9. This module contins a general-purpose specialization-based
  10. templating mechanism. Chutney uses it for string-substitution to
  11. build torrc files and other such things.
  12. First, there are a few classes to implement "Environments". An
  13. "Environment" is like a dictionary, but delegates keys that it can't
  14. find to a "parent" object, which can be an environment or a dict.
  15. >>> base = Environ(foo=99, bar=600)
  16. >>> derived1 = Environ(parent=base, bar=700, quux=32)
  17. >>> base["foo"]
  18. 99
  19. >>> sorted(base.keys())
  20. ['bar', 'foo']
  21. >>> derived1["foo"]
  22. 99
  23. >>> base["bar"]
  24. 600
  25. >>> derived1["bar"]
  26. 700
  27. >>> derived1["quux"]
  28. 32
  29. >>> sorted(derived1.keys())
  30. ['bar', 'foo', 'quux']
  31. You can declare an environment subclass with methods named
  32. _get_foo() to implement a dictionary whose 'foo' item is
  33. calculated on the fly.
  34. >>> class Specialized(Environ):
  35. ... def __init__(self, p=None, **kw):
  36. ... Environ.__init__(self, p, **kw)
  37. ... def _get_expensive_value(self, my):
  38. ... return "Let's pretend this is hard to compute"
  39. ...
  40. >>> s = Specialized(base, quux="hi")
  41. >>> s["quux"]
  42. 'hi'
  43. >>> s['expensive_value']
  44. "Let's pretend this is hard to compute"
  45. >>> sorted(s.keys())
  46. ['bar', 'expensive_value', 'foo', 'quux']
  47. There's an internal class that extends Python's string.Template
  48. with a slightly more useful syntax for us. (It allows more characters
  49. in its key types.)
  50. >>> bt = _BetterTemplate("Testing ${hello}, $goodbye$$, $foo , ${a:b:c}")
  51. >>> bt.safe_substitute({'a:b:c': "4"}, hello=1, goodbye=2, foo=3)
  52. 'Testing 1, 2$, 3 , 4'
  53. Finally, there's a Template class that implements templates for
  54. simple string substitution. Variables with names like $abc or
  55. ${abc} are replaced by their values; $$ is replaced by $, and
  56. ${include:foo} is replaced by the contents of the file "foo".
  57. >>> t = Template("${include:/dev/null} $hi_there")
  58. >>> sorted(t.freevars())
  59. ['hi_there']
  60. >>> t.format(dict(hi_there=99))
  61. ' 99'
  62. >>> t2 = Template("X$${include:$fname} $bar $baz")
  63. >>> t2.format(dict(fname="/dev/null", bar=33, baz="$foo", foo=1337))
  64. 'X 33 1337'
  65. >>> sorted(t2.freevars({'fname':"/dev/null"}))
  66. ['bar', 'baz', 'fname']
  67. """
  68. from __future__ import print_function
  69. from __future__ import with_statement
  70. import string
  71. import os
  72. # class _KeyError(KeyError):
  73. # pass
  74. _KeyError = KeyError
  75. class _DictWrapper(object):
  76. """Base class to implement a dictionary-like object with delegation.
  77. To use it, implement the _getitem method, and pass the optional
  78. 'parent' argument to the constructor.
  79. Lookups are satisfied first by calling _getitem(). If that
  80. fails with KeyError but the parent is present, lookups delegate
  81. to _parent.
  82. """
  83. # Fields
  84. # _parent: the parent object that lookups delegate to.
  85. def __init__(self, parent=None):
  86. self._parent = parent
  87. def _getitem(self, key, my):
  88. raise NotImplemented()
  89. def __getitem__(self, key):
  90. return self.lookup(key, self)
  91. def lookup(self, key, my):
  92. """As self[key], but parents are told when doing their lookups that
  93. the lookup is relative to a specialized environment 'my'. This
  94. is helpful when a parent environment has a value that depends
  95. on other values.
  96. """
  97. try:
  98. return self._getitem(key, my)
  99. except KeyError:
  100. pass
  101. if self._parent is None:
  102. raise _KeyError(key)
  103. try:
  104. lookup = self._parent.lookup
  105. except AttributeError:
  106. try:
  107. return self._parent[key]
  108. except KeyError:
  109. raise _KeyError(key)
  110. try:
  111. return lookup(key, my)
  112. except KeyError:
  113. raise _KeyError(key)
  114. class Environ(_DictWrapper):
  115. """An 'Environ' is used to define a set of key-value mappings with a
  116. fall-back parent Environ. When looking for keys in the
  117. Environ, any keys not found in this Environ are searched for in
  118. the parent.
  119. >>> animal = Environ(mobile=True,legs=4,can_program=False,can_meow=False)
  120. >>> biped = Environ(animal,legs=2)
  121. >>> cat = Environ(animal,can_meow=True)
  122. >>> human = Environ(biped,feathers=False,can_program=True)
  123. >>> chicken = Environ(biped,feathers=True)
  124. >>> human['legs']
  125. 2
  126. >>> human['can_meow']
  127. False
  128. >>> human['can_program']
  129. True
  130. >>> cat['legs']
  131. 4
  132. >>> cat['can_meow']
  133. True
  134. You can extend Environ to support values calculated at run-time by
  135. defining methods with names in the format _get_KEY():
  136. >>> class HomeEnv(Environ):
  137. ... def __init__(self, p=None, **kw):
  138. ... Environ.__init__(self, p, **kw)
  139. ... def _get_dotemacs(self, my):
  140. ... return os.path.join(my['homedir'], ".emacs")
  141. >>> h = HomeEnv(homedir="/tmp")
  142. >>> h['dotemacs']
  143. '/tmp/.emacs'
  144. The 'my' argument passed to these functions is the top-level
  145. dictionary that we're using for our lookup. This is useful
  146. when defining values that depend on other values which might in
  147. turn be overridden:
  148. >>> class Animal(Environ):
  149. ... def __init__(self, p=None, **kw):
  150. ... Environ.__init__(self, p, **kw)
  151. ... def _get_limbs(self, my):
  152. ... return my['legs'] + my['arms']
  153. >>> a = Animal(legs=2,arms=2)
  154. >>> spider = Environ(a, legs=8,arms=0)
  155. >>> squid = Environ(a, legs=0,arms=10)
  156. >>> squid['limbs']
  157. 10
  158. >>> spider['limbs']
  159. 8
  160. Note that if _get_limbs() had been defined as
  161. 'return self['legs']+self['arms']',
  162. both spider['limbs'] and squid['limbs'] would be given
  163. (incorrectly) as 4.
  164. """
  165. # Fields
  166. # _dict: dictionary holding the contents of this Environ that are
  167. # not inherited from the parent and are not computed on the fly.
  168. def __init__(self, parent=None, **kw):
  169. _DictWrapper.__init__(self, parent)
  170. self._dict = kw
  171. def _getitem(self, key, my):
  172. try:
  173. return self._dict[key]
  174. except KeyError:
  175. pass
  176. fn = getattr(self, "_get_%s" % key, None)
  177. if fn is not None:
  178. try:
  179. rv = fn(my)
  180. return rv
  181. except _KeyError:
  182. raise KeyError(key)
  183. raise KeyError(key)
  184. def __setitem__(self, key, val):
  185. self._dict[key] = val
  186. def keys(self):
  187. s = set()
  188. s.update(self._dict.keys())
  189. if self._parent is not None:
  190. s.update(self._parent.keys())
  191. s.update(name[5:] for name in dir(self) if name.startswith("_get_"))
  192. return s
  193. class IncluderDict(_DictWrapper):
  194. """Helper to implement ${include:} template substitution. Acts as a
  195. dictionary that maps include:foo to the contents of foo (relative to
  196. a search path if foo is a relative path), and delegates everything else
  197. to a parent.
  198. """
  199. # Fields
  200. # _includePath: a list of directories to consider when searching
  201. # for files given as relative paths.
  202. # _st_mtime: the most recent time when any of the files included
  203. # so far has been updated. (As seconds since the epoch).
  204. def __init__(self, parent, includePath=(".",)):
  205. """Create a new IncluderDict. Non-include entries are delegated to
  206. parent. Non-absolute paths are searched for relative to the
  207. paths listed in includePath.
  208. """
  209. _DictWrapper.__init__(self, parent)
  210. self._includePath = includePath
  211. self._st_mtime = 0
  212. def _getitem(self, key, my):
  213. if not key.startswith("include:"):
  214. raise KeyError(key)
  215. filename = key[len("include:"):]
  216. if os.path.isabs(filename):
  217. with open(filename, 'r') as f:
  218. stat = os.fstat(f.fileno())
  219. if stat.st_mtime > self._st_mtime:
  220. self._st_mtime = stat.st_mtime
  221. return f.read()
  222. for elt in self._includePath:
  223. fullname = os.path.join(elt, filename)
  224. if os.path.exists(fullname):
  225. with open(fullname, 'r') as f:
  226. stat = os.fstat(f.fileno())
  227. if stat.st_mtime > self._st_mtime:
  228. self._st_mtime = stat.st_mtime
  229. return f.read()
  230. raise KeyError(key)
  231. def getUpdateTime(self):
  232. return self._st_mtime
  233. class _BetterTemplate(string.Template):
  234. """Subclass of the standard string.Template that allows a wider range of
  235. characters in variable names.
  236. """
  237. idpattern = r'[a-z0-9:_/\.\-\/]+'
  238. def __init__(self, template):
  239. string.Template.__init__(self, template)
  240. class _FindVarsHelper(object):
  241. """Helper dictionary for finding the free variables in a template.
  242. It answers all requests for key lookups affirmatively, and remembers
  243. what it was asked for.
  244. """
  245. # Fields
  246. # _dflts: a dictionary of default values to treat specially
  247. # _vars: a set of all the keys that we've been asked to look up so far.
  248. def __init__(self, dflts):
  249. self._dflts = dflts
  250. self._vars = set()
  251. def __getitem__(self, var):
  252. return self.lookup(var, self)
  253. def lookup(self, var, my):
  254. self._vars.add(var)
  255. try:
  256. return self._dflts[var]
  257. except KeyError:
  258. return ""
  259. class Template(object):
  260. """A Template is a string pattern that allows repeated variable
  261. substitutions. These syntaxes are supported:
  262. $var -- expands to the value of var
  263. ${var} -- expands to the value of var
  264. $$ -- expands to a single $
  265. ${include:filename} -- expands to the contents of filename
  266. Substitutions are performed iteratively until no more are possible.
  267. """
  268. # Okay, actually, we stop after this many substitutions to avoid
  269. # infinite loops
  270. MAX_ITERATIONS = 32
  271. # Fields
  272. # _pat: The base pattern string to start our substitutions from
  273. # _includePath: a list of directories to search when including a file
  274. # by relative path.
  275. def __init__(self, pattern, includePath=(".",)):
  276. self._pat = pattern
  277. self._includePath = includePath
  278. def freevars(self, defaults=None):
  279. """Return a set containing all the free variables in this template"""
  280. if defaults is None:
  281. defaults = {}
  282. d = _FindVarsHelper(defaults)
  283. self.format(d)
  284. return d._vars
  285. def format(self, values):
  286. """Return a string containing this template, filled in with the
  287. values in the mapping 'values'.
  288. """
  289. values = IncluderDict(values, self._includePath)
  290. orig_val = self._pat
  291. nIterations = 0
  292. while True:
  293. v = _BetterTemplate(orig_val).substitute(values)
  294. if v == orig_val:
  295. return v
  296. orig_val = v
  297. nIterations += 1
  298. if nIterations > self.MAX_ITERATIONS:
  299. raise ValueError("Too many iterations in expanding template!")
  300. if __name__ == '__main__':
  301. import sys
  302. if len(sys.argv) == 1:
  303. import doctest
  304. doctest.testmod()
  305. print("done")
  306. else:
  307. for fn in sys.argv[1:]:
  308. with open(fn, 'r') as f:
  309. t = Template(f.read())
  310. print(fn, t.freevars())