Debian Codegraph @

pipeline/templatetags/pipeline.py

raw
1 import logging
2 import re
3 import subprocess
4
5 from django import template
6 from django.contrib.staticfiles.storage import staticfiles_storage
7 from django.template.base import VariableDoesNotExist
8 from django.template.loader import render_to_string
9 from django.utils.safestring import mark_safe
10
11 from ..collector import default_collector
12 from ..conf import settings
13 from ..exceptions import CompilerError
14 from ..packager import PackageNotFound, Packager
15 from ..utils import guess_type
16
17 logger = logging.getLogger(__name__)
18
19 register = template.Library()
20
21
22 class PipelineMixin:
23 request = None
24 _request_var = None
25
26 @property
27 def request_var(self):
28 if not self._request_var:
29 self._request_var = template.Variable("request")
30 return self._request_var
31
32 def package_for(self, package_name, package_type):
33 package = {
34 "js": getattr(settings, "JAVASCRIPT", {}).get(package_name, {}),
35 "css": getattr(settings, "STYLESHEETS", {}).get(package_name, {}),
36 }[package_type]
37
38 if package:
39 package = {package_name: package}
40
41 packager = {
42 "js": Packager(css_packages={}, js_packages=package),
43 "css": Packager(css_packages=package, js_packages={}),
44 }[package_type]
45
46 return packager.package_for(package_type, package_name)
47
48 def render(self, context):
49 try:
50 self.request = self.request_var.resolve(context)
51 except VariableDoesNotExist:
52 pass
53
54 def render_compressed(self, package, package_name, package_type):
55 """Render HTML for the package.
56
57 If ``PIPELINE_ENABLED`` is ``True``, this will render the package's
58 output file (using :py:meth:`render_compressed_output`). Otherwise,
59 this will render the package's source files (using
60 :py:meth:`render_compressed_sources`).
61
62 Subclasses can override this method to provide custom behavior for
63 determining what to render.
64 """
65 if settings.PIPELINE_ENABLED:
66 return self.render_compressed_output(package, package_name, package_type)
67 else:
68 return self.render_compressed_sources(package, package_name, package_type)
69
70 def render_compressed_output(self, package, package_name, package_type):
71 """Render HTML for using the package's output file.
72
73 Subclasses can override this method to provide custom behavior for
74 rendering the output file.
75 """
76 method = getattr(self, f"render_{package_type}")
77
78 return method(package, package.output_filename)
79
80 def render_compressed_sources(self, package, package_name, package_type):
81 """Render HTML for using the package's list of source files.
82
83 Each source file will first be collected, if
84 ``PIPELINE_COLLECTOR_ENABLED`` is ``True``.
85
86 If there are any errors compiling any of the source files, an
87 ``SHOW_ERRORS_INLINE`` is ``True``, those errors will be shown at
88 the top of the page.
89
90 Subclasses can override this method to provide custom behavior for
91 rendering the source files.
92 """
93 if settings.PIPELINE_COLLECTOR_ENABLED:
94 default_collector.collect(self.request)
95
96 packager = Packager()
97 method = getattr(self, f"render_individual_{package_type}")
98
99 try:
100 paths = packager.compile(package.paths)
101 except CompilerError as e:
102 if settings.SHOW_ERRORS_INLINE:
103 method = getattr(self, f"render_error_{package_type}")
104 return method(package_name, e)
105 else:
106 raise
107
108 templates = packager.pack_templates(package)
109
110 return method(package, paths, templates=templates)
111
112 def render_error(self, package_type, package_name, e):
113 # Remove any ANSI escape sequences in the output.
114 error_output = re.sub(
115 re.compile(r"(?:\x1B[@-_]|[\x80-\x9F])[0-?]*[ -/]*[@-~]"),
116 "",
117 e.error_output,
118 )
119
120 return render_to_string(
121 "pipeline/compile_error.html",
122 {
123 "package_type": package_type,
124 "package_name": package_name,
125 "command": subprocess.list2cmdline(e.command),
126 "errors": error_output,
127 },
128 )
129
130
131 class StylesheetNode(PipelineMixin, template.Node):
132 def __init__(self, name):
133 self.name = name
134
135 def render(self, context):
136 super().render(context)
137 package_name = template.Variable(self.name).resolve(context)
138
139 try:
140 package = self.package_for(package_name, "css")
141 except PackageNotFound:
142 w = "Package %r is unknown. Check PIPELINE['STYLESHEETS'] in your settings."
143 logger.warning(w, package_name)
144 # fail silently, do not return anything if an invalid group is specified
145 return ""
146 return self.render_compressed(package, package_name, "css")
147
148 def render_css(self, package, path):
149 template_name = package.template_name or "pipeline/css.html"
150 context = package.extra_context
151 context.update(
152 {
153 "type": guess_type(path, "text/css"),
154 "url": mark_safe(staticfiles_storage.url(path)),
155 }
156 )
157 return render_to_string(template_name, context)
158
159 def render_individual_css(self, package, paths, **kwargs):
160 tags = [self.render_css(package, path) for path in paths]
161 return "\n".join(tags)
162
163 def render_error_css(self, package_name, e):
164 return super().render_error("CSS", package_name, e)
165
166
167 class JavascriptNode(PipelineMixin, template.Node):
168 def __init__(self, name):
169 self.name = name
170
171 def render(self, context):
172 super().render(context)
173 package_name = template.Variable(self.name).resolve(context)
174
175 try:
176 package = self.package_for(package_name, "js")
177 except PackageNotFound:
178 w = "Package %r is unknown. Check PIPELINE['JAVASCRIPT'] in your settings."
179 logger.warning(w, package_name)
180 # fail silently, do not return anything if an invalid group is specified
181 return ""
182 return self.render_compressed(package, package_name, "js")
183
184 def render_js(self, package, path):
185 template_name = package.template_name or "pipeline/js.html"
186 context = package.extra_context
187 context.update(
188 {
189 "type": guess_type(path, "text/javascript"),
190 "url": mark_safe(staticfiles_storage.url(path)),
191 }
192 )
193 return render_to_string(template_name, context)
194
195 def render_inline(self, package, js):
196 context = package.extra_context
197 context.update({"source": js})
198 return render_to_string("pipeline/inline_js.html", context)
199
200 def render_individual_js(self, package, paths, templates=None):
201 tags = [self.render_js(package, js) for js in paths]
202 if templates:
203 tags.append(self.render_inline(package, templates))
204 return "\n".join(tags)
205
206 def render_error_js(self, package_name, e):
207 return super().render_error("JavaScript", package_name, e)
208
209
210 @register.tag
211 def stylesheet(parser, token):
212 try:
213 tag_name, name = token.split_contents()
214 except ValueError:
215 e = (
216 "%r requires exactly one argument: the name "
217 "of a group in the PIPELINE.STYLESHEETS setting"
218 )
219 raise template.TemplateSyntaxError(e % token.split_contents()[0])
220 return StylesheetNode(name)
221
222
223 @register.tag
224 def javascript(parser, token):
225 try:
226 tag_name, name = token.split_contents()
227 except ValueError:
228 e = (
229 "%r requires exactly one argument: the name "
230 "of a group in the PIPELINE.JAVASVRIPT setting"
231 )
232 raise template.TemplateSyntaxError(e % token.split_contents()[0])
233 return JavascriptNode(name)