util.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. # mako/util.py
  2. # Copyright (C) 2006-2016 the Mako authors and contributors <see AUTHORS file>
  3. #
  4. # This module is part of Mako and is released under
  5. # the MIT License: http://www.opensource.org/licenses/mit-license.php
  6. import re
  7. import collections
  8. import codecs
  9. import os
  10. from mako import compat
  11. import operator
  12. def update_wrapper(decorated, fn):
  13. decorated.__wrapped__ = fn
  14. decorated.__name__ = fn.__name__
  15. return decorated
  16. class PluginLoader(object):
  17. def __init__(self, group):
  18. self.group = group
  19. self.impls = {}
  20. def load(self, name):
  21. if name in self.impls:
  22. return self.impls[name]()
  23. else:
  24. import pkg_resources
  25. for impl in pkg_resources.iter_entry_points(
  26. self.group,
  27. name):
  28. self.impls[name] = impl.load
  29. return impl.load()
  30. else:
  31. from mako import exceptions
  32. raise exceptions.RuntimeException(
  33. "Can't load plugin %s %s" %
  34. (self.group, name))
  35. def register(self, name, modulepath, objname):
  36. def load():
  37. mod = __import__(modulepath)
  38. for token in modulepath.split(".")[1:]:
  39. mod = getattr(mod, token)
  40. return getattr(mod, objname)
  41. self.impls[name] = load
  42. def verify_directory(dir):
  43. """create and/or verify a filesystem directory."""
  44. tries = 0
  45. while not os.path.exists(dir):
  46. try:
  47. tries += 1
  48. os.makedirs(dir, compat.octal("0775"))
  49. except:
  50. if tries > 5:
  51. raise
  52. def to_list(x, default=None):
  53. if x is None:
  54. return default
  55. if not isinstance(x, (list, tuple)):
  56. return [x]
  57. else:
  58. return x
  59. class memoized_property(object):
  60. """A read-only @property that is only evaluated once."""
  61. def __init__(self, fget, doc=None):
  62. self.fget = fget
  63. self.__doc__ = doc or fget.__doc__
  64. self.__name__ = fget.__name__
  65. def __get__(self, obj, cls):
  66. if obj is None:
  67. return self
  68. obj.__dict__[self.__name__] = result = self.fget(obj)
  69. return result
  70. class memoized_instancemethod(object):
  71. """Decorate a method memoize its return value.
  72. Best applied to no-arg methods: memoization is not sensitive to
  73. argument values, and will always return the same value even when
  74. called with different arguments.
  75. """
  76. def __init__(self, fget, doc=None):
  77. self.fget = fget
  78. self.__doc__ = doc or fget.__doc__
  79. self.__name__ = fget.__name__
  80. def __get__(self, obj, cls):
  81. if obj is None:
  82. return self
  83. def oneshot(*args, **kw):
  84. result = self.fget(obj, *args, **kw)
  85. memo = lambda *a, **kw: result
  86. memo.__name__ = self.__name__
  87. memo.__doc__ = self.__doc__
  88. obj.__dict__[self.__name__] = memo
  89. return result
  90. oneshot.__name__ = self.__name__
  91. oneshot.__doc__ = self.__doc__
  92. return oneshot
  93. class SetLikeDict(dict):
  94. """a dictionary that has some setlike methods on it"""
  95. def union(self, other):
  96. """produce a 'union' of this dict and another (at the key level).
  97. values in the second dict take precedence over that of the first"""
  98. x = SetLikeDict(**self)
  99. x.update(other)
  100. return x
  101. class FastEncodingBuffer(object):
  102. """a very rudimentary buffer that is faster than StringIO,
  103. but doesn't crash on unicode data like cStringIO."""
  104. def __init__(self, encoding=None, errors='strict', as_unicode=False):
  105. self.data = collections.deque()
  106. self.encoding = encoding
  107. if as_unicode:
  108. self.delim = compat.u('')
  109. else:
  110. self.delim = ''
  111. self.as_unicode = as_unicode
  112. self.errors = errors
  113. self.write = self.data.append
  114. def truncate(self):
  115. self.data = collections.deque()
  116. self.write = self.data.append
  117. def getvalue(self):
  118. if self.encoding:
  119. return self.delim.join(self.data).encode(self.encoding,
  120. self.errors)
  121. else:
  122. return self.delim.join(self.data)
  123. class LRUCache(dict):
  124. """A dictionary-like object that stores a limited number of items,
  125. discarding lesser used items periodically.
  126. this is a rewrite of LRUCache from Myghty to use a periodic timestamp-based
  127. paradigm so that synchronization is not really needed. the size management
  128. is inexact.
  129. """
  130. class _Item(object):
  131. def __init__(self, key, value):
  132. self.key = key
  133. self.value = value
  134. self.timestamp = compat.time_func()
  135. def __repr__(self):
  136. return repr(self.value)
  137. def __init__(self, capacity, threshold=.5):
  138. self.capacity = capacity
  139. self.threshold = threshold
  140. def __getitem__(self, key):
  141. item = dict.__getitem__(self, key)
  142. item.timestamp = compat.time_func()
  143. return item.value
  144. def values(self):
  145. return [i.value for i in dict.values(self)]
  146. def setdefault(self, key, value):
  147. if key in self:
  148. return self[key]
  149. else:
  150. self[key] = value
  151. return value
  152. def __setitem__(self, key, value):
  153. item = dict.get(self, key)
  154. if item is None:
  155. item = self._Item(key, value)
  156. dict.__setitem__(self, key, item)
  157. else:
  158. item.value = value
  159. self._manage_size()
  160. def _manage_size(self):
  161. while len(self) > self.capacity + self.capacity * self.threshold:
  162. bytime = sorted(dict.values(self),
  163. key=operator.attrgetter('timestamp'), reverse=True)
  164. for item in bytime[self.capacity:]:
  165. try:
  166. del self[item.key]
  167. except KeyError:
  168. # if we couldn't find a key, most likely some other thread
  169. # broke in on us. loop around and try again
  170. break
  171. # Regexp to match python magic encoding line
  172. _PYTHON_MAGIC_COMMENT_re = re.compile(
  173. r'[ \t\f]* \# .* coding[=:][ \t]*([-\w.]+)',
  174. re.VERBOSE)
  175. def parse_encoding(fp):
  176. """Deduce the encoding of a Python source file (binary mode) from magic
  177. comment.
  178. It does this in the same way as the `Python interpreter`__
  179. .. __: http://docs.python.org/ref/encodings.html
  180. The ``fp`` argument should be a seekable file object in binary mode.
  181. """
  182. pos = fp.tell()
  183. fp.seek(0)
  184. try:
  185. line1 = fp.readline()
  186. has_bom = line1.startswith(codecs.BOM_UTF8)
  187. if has_bom:
  188. line1 = line1[len(codecs.BOM_UTF8):]
  189. m = _PYTHON_MAGIC_COMMENT_re.match(line1.decode('ascii', 'ignore'))
  190. if not m:
  191. try:
  192. import parser
  193. parser.suite(line1.decode('ascii', 'ignore'))
  194. except (ImportError, SyntaxError):
  195. # Either it's a real syntax error, in which case the source
  196. # is not valid python source, or line2 is a continuation of
  197. # line1, in which case we don't want to scan line2 for a magic
  198. # comment.
  199. pass
  200. else:
  201. line2 = fp.readline()
  202. m = _PYTHON_MAGIC_COMMENT_re.match(
  203. line2.decode('ascii', 'ignore'))
  204. if has_bom:
  205. if m:
  206. raise SyntaxError(
  207. "python refuses to compile code with both a UTF8"
  208. " byte-order-mark and a magic encoding comment")
  209. return 'utf_8'
  210. elif m:
  211. return m.group(1)
  212. else:
  213. return None
  214. finally:
  215. fp.seek(pos)
  216. def sorted_dict_repr(d):
  217. """repr() a dictionary with the keys in order.
  218. Used by the lexer unit test to compare parse trees based on strings.
  219. """
  220. keys = list(d.keys())
  221. keys.sort()
  222. return "{" + ", ".join(["%r: %r" % (k, d[k]) for k in keys]) + "}"
  223. def restore__ast(_ast):
  224. """Attempt to restore the required classes to the _ast module if it
  225. appears to be missing them
  226. """
  227. if hasattr(_ast, 'AST'):
  228. return
  229. _ast.PyCF_ONLY_AST = 2 << 9
  230. m = compile("""\
  231. def foo(): pass
  232. class Bar(object): pass
  233. if False: pass
  234. baz = 'mako'
  235. 1 + 2 - 3 * 4 / 5
  236. 6 // 7 % 8 << 9 >> 10
  237. 11 & 12 ^ 13 | 14
  238. 15 and 16 or 17
  239. -baz + (not +18) - ~17
  240. baz and 'foo' or 'bar'
  241. (mako is baz == baz) is not baz != mako
  242. mako > baz < mako >= baz <= mako
  243. mako in baz not in mako""", '<unknown>', 'exec', _ast.PyCF_ONLY_AST)
  244. _ast.Module = type(m)
  245. for cls in _ast.Module.__mro__:
  246. if cls.__name__ == 'mod':
  247. _ast.mod = cls
  248. elif cls.__name__ == 'AST':
  249. _ast.AST = cls
  250. _ast.FunctionDef = type(m.body[0])
  251. _ast.ClassDef = type(m.body[1])
  252. _ast.If = type(m.body[2])
  253. _ast.Name = type(m.body[3].targets[0])
  254. _ast.Store = type(m.body[3].targets[0].ctx)
  255. _ast.Str = type(m.body[3].value)
  256. _ast.Sub = type(m.body[4].value.op)
  257. _ast.Add = type(m.body[4].value.left.op)
  258. _ast.Div = type(m.body[4].value.right.op)
  259. _ast.Mult = type(m.body[4].value.right.left.op)
  260. _ast.RShift = type(m.body[5].value.op)
  261. _ast.LShift = type(m.body[5].value.left.op)
  262. _ast.Mod = type(m.body[5].value.left.left.op)
  263. _ast.FloorDiv = type(m.body[5].value.left.left.left.op)
  264. _ast.BitOr = type(m.body[6].value.op)
  265. _ast.BitXor = type(m.body[6].value.left.op)
  266. _ast.BitAnd = type(m.body[6].value.left.left.op)
  267. _ast.Or = type(m.body[7].value.op)
  268. _ast.And = type(m.body[7].value.values[0].op)
  269. _ast.Invert = type(m.body[8].value.right.op)
  270. _ast.Not = type(m.body[8].value.left.right.op)
  271. _ast.UAdd = type(m.body[8].value.left.right.operand.op)
  272. _ast.USub = type(m.body[8].value.left.left.op)
  273. _ast.Or = type(m.body[9].value.op)
  274. _ast.And = type(m.body[9].value.values[0].op)
  275. _ast.IsNot = type(m.body[10].value.ops[0])
  276. _ast.NotEq = type(m.body[10].value.ops[1])
  277. _ast.Is = type(m.body[10].value.left.ops[0])
  278. _ast.Eq = type(m.body[10].value.left.ops[1])
  279. _ast.Gt = type(m.body[11].value.ops[0])
  280. _ast.Lt = type(m.body[11].value.ops[1])
  281. _ast.GtE = type(m.body[11].value.ops[2])
  282. _ast.LtE = type(m.body[11].value.ops[3])
  283. _ast.In = type(m.body[12].value.ops[0])
  284. _ast.NotIn = type(m.body[12].value.ops[1])
  285. def read_file(path, mode='rb'):
  286. fp = open(path, mode)
  287. try:
  288. data = fp.read()
  289. return data
  290. finally:
  291. fp.close()
  292. def read_python_file(path):
  293. fp = open(path, "rb")
  294. try:
  295. encoding = parse_encoding(fp)
  296. data = fp.read()
  297. if encoding:
  298. data = data.decode(encoding)
  299. return data
  300. finally:
  301. fp.close()