merge.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  1. """Contains the core functionality that manages merging of assets.
  2. """
  3. from __future__ import with_statement
  4. import contextlib
  5. try:
  6. from urllib.request import Request as URLRequest, urlopen
  7. from urllib.error import HTTPError
  8. except ImportError:
  9. from urllib2 import Request as URLRequest, urlopen
  10. from urllib2 import HTTPError
  11. import logging
  12. from io import open
  13. from webassets.six.moves import filter
  14. from .utils import cmp_debug_levels, StringIO, hash_func
  15. __all__ = ('FileHunk', 'MemoryHunk', 'merge', 'FilterTool',
  16. 'MoreThanOneFilterError', 'NoFilters')
  17. # Log which is used to output low-level information about what the build does.
  18. # This is setup such that it does not output just because the root level
  19. # "webassets" logger is set to level DEBUG (for example via the commandline
  20. # --verbose option). Instead, the messages are only shown when an environment
  21. # variable is set.
  22. # However, we might want to change this in the future. The CLI --verbose option
  23. # could instead just set the level to NOTICE, for example.
  24. log = logging.getLogger('webassets.debug')
  25. log.addHandler(logging.StreamHandler())
  26. import os
  27. if os.environ.get('WEBASSETS_DEBUG'):
  28. log.setLevel(logging.DEBUG)
  29. else:
  30. log.setLevel(logging.ERROR)
  31. class BaseHunk(object):
  32. """Abstract base class.
  33. """
  34. def mtime(self):
  35. raise NotImplementedError()
  36. def id(self):
  37. return hash_func(self.data())
  38. def __eq__(self, other):
  39. if isinstance(other, BaseHunk):
  40. # Allow class to be used as a unique dict key.
  41. return hash_func(self) == hash_func(other)
  42. return False
  43. def data(self):
  44. raise NotImplementedError()
  45. def save(self, filename):
  46. with open(filename, 'w', encoding='utf-8') as f:
  47. f.write(self.data())
  48. class FileHunk(BaseHunk):
  49. """Exposes a single file through as a hunk.
  50. """
  51. def __init__(self, filename):
  52. self.filename = filename
  53. def __repr__(self):
  54. return '<%s %s>' % (self.__class__.__name__, self.filename)
  55. def mtime(self):
  56. pass
  57. def data(self):
  58. f = open(self.filename, 'r', encoding='utf-8')
  59. try:
  60. return f.read()
  61. finally:
  62. f.close()
  63. class UrlHunk(BaseHunk):
  64. """Represents a file that is referenced by an Url.
  65. If an environment is given, it's cache will be used to cache the url
  66. contents, and to access it, as allowed by the etag/last modified headers.
  67. """
  68. def __init__(self, url, env=None):
  69. self.url = url
  70. self.env = env
  71. def __repr__(self):
  72. return '<%s %s>' % (self.__class__.__name__, self.url)
  73. def data(self):
  74. if not hasattr(self, '_data'):
  75. request = URLRequest(self.url)
  76. # Look in the cache for etag / last modified headers to use
  77. # TODO: "expires" header could be supported
  78. if self.env and self.env.cache:
  79. headers = self.env.cache.get(
  80. ('url', 'headers', self.url))
  81. if headers:
  82. etag, lmod = headers
  83. if etag: request.add_header('If-None-Match', etag)
  84. if lmod: request.add_header('If-Modified-Since', lmod)
  85. # Make a request
  86. try:
  87. response = urlopen(request)
  88. except HTTPError as e:
  89. if e.code != 304:
  90. raise
  91. # Use the cached version of the url
  92. self._data = self.env.cache.get(('url', 'contents', self.url))
  93. else:
  94. with contextlib.closing(response):
  95. self._data = response.read()
  96. # Cache the info from this request
  97. if self.env and self.env.cache:
  98. self.env.cache.set(
  99. ('url', 'headers', self.url),
  100. (response.headers.get("ETag"),
  101. response.headers.get("Last-Modified")))
  102. self.env.cache.set(('url', 'contents', self.url), self._data)
  103. return self._data
  104. class MemoryHunk(BaseHunk):
  105. """Content that is no longer a direct representation of a source file. It
  106. might have filters applied, and is probably the result of merging multiple
  107. individual source files together.
  108. """
  109. def __init__(self, data, files=None):
  110. self._data = data
  111. self.files = files or []
  112. def __repr__(self):
  113. # Include a has of the data. We want this during logging, so we
  114. # can see which hunks contain identical content. Because this is
  115. # a question of performance, make sure to log in such a way that
  116. # when logging is disabled, this won't be called, i.e.: don't
  117. # %s-format yourself, let logging do it as needed.
  118. return '<%s %s>' % (self.__class__.__name__, hash_func(self))
  119. def mtime(self):
  120. pass
  121. def data(self):
  122. if hasattr(self._data, 'read'):
  123. return self._data.read()
  124. return self._data
  125. def save(self, filename):
  126. f = open(filename, 'w', encoding='utf-8')
  127. try:
  128. f.write(self.data())
  129. finally:
  130. f.close()
  131. def merge(hunks, separator=None):
  132. """Merge the given list of hunks, returning a new ``MemoryHunk`` object.
  133. """
  134. # TODO: combine the list of source files, we'd like to collect them
  135. # The linebreak is important in certain cases for Javascript
  136. # files, like when a last line is a //-comment.
  137. if not separator:
  138. separator = '\n'
  139. return MemoryHunk(separator.join([h.data() for h in hunks]))
  140. class MoreThanOneFilterError(Exception):
  141. def __init__(self, message, filters):
  142. Exception.__init__(self, message)
  143. self.filters = filters
  144. class NoFilters(Exception):
  145. pass
  146. class FilterTool(object):
  147. """Can apply filters to hunk objects, while using the cache.
  148. If ``no_cache_read`` is given, then the cache will not be considered for
  149. this operation (though the result will still be written to the cache).
  150. ``kwargs`` are options that should be passed along to the filters.
  151. """
  152. VALID_TRANSFORMS = ('input', 'output',)
  153. VALID_FUNCS = ('open', 'concat',)
  154. def __init__(self, cache=None, no_cache_read=False, kwargs=None):
  155. self.cache = cache
  156. self.no_cache_read = no_cache_read
  157. self.kwargs = kwargs or {}
  158. def _wrap_cache(self, key, func):
  159. """Return cache value ``key``, or run ``func``.
  160. """
  161. if self.cache:
  162. if not self.no_cache_read:
  163. log.debug('Checking cache for key %s', key)
  164. content = self.cache.get(key)
  165. if not content in (False, None):
  166. log.debug('Using cached result for %s', key)
  167. return MemoryHunk(content)
  168. content = func().getvalue()
  169. if self.cache:
  170. log.debug('Storing result in cache with key %s', key,)
  171. self.cache.set(key, content)
  172. return MemoryHunk(content)
  173. def apply(self, hunk, filters, type, kwargs=None):
  174. """Apply the given list of filters to the hunk, returning a new
  175. ``MemoryHunk`` object.
  176. ``kwargs`` are options that should be passed along to the filters.
  177. If ``hunk`` is a file hunk, a ``source_path`` key will automatically
  178. be added to ``kwargs``.
  179. """
  180. assert type in self.VALID_TRANSFORMS
  181. log.debug('Need to run method "%s" of filters (%s) on hunk %s with '
  182. 'kwargs=%s', type, filters, hunk, kwargs)
  183. filters = [f for f in filters if getattr(f, type, None)]
  184. if not filters: # Short-circuit
  185. log.debug('No filters have "%s" methods, returning hunk '
  186. 'unchanged' % (type,))
  187. return hunk
  188. kwargs_final = self.kwargs.copy()
  189. kwargs_final.update(kwargs or {})
  190. def func():
  191. data = StringIO(hunk.data())
  192. for filter in filters:
  193. log.debug('Running method "%s" of %s with kwargs=%s',
  194. type, filter, kwargs_final)
  195. out = StringIO(u'') # For 2.x, StringIO().getvalue() returns str
  196. getattr(filter, type)(data, out, **kwargs_final)
  197. data = out
  198. data.seek(0)
  199. return data
  200. additional_cache_keys = []
  201. if kwargs_final:
  202. for filter in filters:
  203. additional_cache_keys += filter.get_additional_cache_keys(**kwargs_final)
  204. # Note that the key used to cache this hunk is different from the key
  205. # the hunk will expose to subsequent merges, i.e. hunk.key() is always
  206. # based on the actual content, and does not match the cache key. The
  207. # latter also includes information about for example the filters used.
  208. #
  209. # It wouldn't have to be this way. Hunk could subsequently expose their
  210. # cache key through hunk.key(). This would work as well, but would be
  211. # an inferior solution: Imagine a source file which receives
  212. # non-substantial changes, in the sense that they do not affect the
  213. # filter output, for example whitespace. If a hunk's key is the cache
  214. # key, such a change would invalidate the caches for all subsequent
  215. # operations on this hunk as well, even though it didn't actually
  216. # change after all.
  217. key = ("hunk", hunk, tuple(filters), type, additional_cache_keys)
  218. return self._wrap_cache(key, func)
  219. def apply_func(self, filters, type, args, kwargs=None, cache_key=None):
  220. """Apply a filter that is not a "stream in, stream out" transform (i.e.
  221. like the input() and output() filter methods). Instead, the filter
  222. method is given the arguments in ``args`` and should then produce an
  223. output stream. This is used, e.g., for the concat() and open() filter
  224. methods.
  225. Only one such filter can run per operation.
  226. ``cache_key`` may be a list of additional values to use as the cache
  227. key, in addition to the default key (the filter and arguments).
  228. """
  229. assert type in self.VALID_FUNCS
  230. log.debug('Need to run method "%s" of one of the filters (%s) '
  231. 'with args=%s, kwargs=%s', type, filters, args, kwargs)
  232. filters = [f for f in filters if getattr(f, type, None)]
  233. if not filters: # Short-circuit
  234. log.debug('No filters have a "%s" method' % type)
  235. raise NoFilters()
  236. if len(filters) > 1:
  237. raise MoreThanOneFilterError(
  238. 'These filters cannot be combined: %s' % (
  239. ', '.join([f.name for f in filters])), filters)
  240. kwargs_final = self.kwargs.copy()
  241. kwargs_final.update(kwargs or {})
  242. def func():
  243. filter = filters[0]
  244. out = StringIO(u'') # For 2.x, StringIO().getvalue() returns str
  245. log.debug('Running method "%s" of %s with args=%s, kwargs=%s',
  246. type, filter, args, kwargs)
  247. getattr(filter, type)(out, *args, **kwargs_final)
  248. return out
  249. additional_cache_keys = []
  250. if kwargs_final:
  251. for filter in filters:
  252. additional_cache_keys += filter.get_additional_cache_keys(**kwargs_final)
  253. key = ("hunk", args, tuple(filters), type, cache_key or [], additional_cache_keys)
  254. return self._wrap_cache(key, func)
  255. def merge_filters(filters1, filters2):
  256. """Merge two filter lists into one.
  257. Duplicate filters are removed. Since filter order is important, the order
  258. of the arguments to this function also matter. Duplicates are always
  259. removed from the second filter set if they exist in the first.
  260. The result will always be ``filters1``, with additional unique filters
  261. from ``filters2`` appended. Within the context of a hierarchy, you want
  262. ``filters2`` to be the parent.
  263. This function presumes that all the given filters inherit from ``Filter``,
  264. which properly implements operators to determine duplicate filters.
  265. """
  266. result = list(filters1[:])
  267. if filters2:
  268. for f in filters2:
  269. if not f in result:
  270. result.append(f)
  271. return result
  272. def select_filters(filters, level):
  273. """Return from the list in ``filters`` those filters which indicate that
  274. they should run for the given debug level.
  275. """
  276. return [f for f in filters
  277. if f.max_debug_level is None or
  278. cmp_debug_levels(level, f.max_debug_level) <= 0]