/
plugin.py
446 lines (355 loc) · 14.2 KB
/
plugin.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
# Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0
# For details: https://github.com/nedbat/django_coverage_plugin/blob/master/NOTICE.txt
"""The Django template coverage plugin."""
from __future__ import print_function
import os.path
import re
try:
from coverage.exceptions import NoSource
except ImportError:
# for coverage 5.x
from coverage.misc import NoSource
import coverage.plugin
import django
import django.template
from django.template.base import Lexer, NodeList, Template, TextNode
from django.template.defaulttags import VerbatimNode
from django.templatetags.i18n import BlockTranslateNode
from six.moves import range
try:
from django.template.base import TokenType
def _token_name(token_type):
token_type.name.capitalize()
except ImportError:
# Django <2.1 uses separate constants for token types
from django.template.base import (
TOKEN_BLOCK,
TOKEN_MAPPING,
TOKEN_TEXT,
TOKEN_VAR,
)
class TokenType:
TEXT = TOKEN_TEXT
VAR = TOKEN_VAR
BLOCK = TOKEN_BLOCK
def _token_name(token_type):
return TOKEN_MAPPING[token_type]
class DjangoTemplatePluginException(Exception):
"""Used for any errors from the plugin itself."""
pass
# For debugging the plugin itself.
SHOW_PARSING = False
SHOW_TRACING = False
def check_debug():
"""Check that Django's template debugging is enabled.
Django's built-in "template debugging" records information the plugin needs
to do its work. Check that the setting is correct, and raise an exception
if it is not.
Returns True if the debug check was performed, False otherwise
"""
from django.conf import settings
if not settings.configured:
return False
# I _think_ this check is all that's needed and the 3 "hasattr" checks
# below can be removed, but it's not clear how to verify that
from django.apps import apps
if not apps.ready:
return False
# django.template.backends.django gets loaded lazily, so return false
# until they've been loaded
if not hasattr(django.template, "backends"):
return False
if not hasattr(django.template.backends, "django"):
return False
if not hasattr(django.template.backends.django, "DjangoTemplates"):
raise DjangoTemplatePluginException("Can't use non-Django templates.")
if not django.template.engines._engines:
return False
for engine in django.template.engines.all():
if not isinstance(engine, django.template.backends.django.DjangoTemplates):
raise DjangoTemplatePluginException(
"Can't use non-Django templates."
)
if not engine.engine.debug:
raise DjangoTemplatePluginException(
"Template debugging must be enabled in settings."
)
return True
if django.VERSION < (1, 8):
raise RuntimeError("Django Coverage Plugin requires Django 1.8 or higher")
if django.VERSION >= (1, 9):
# Since we are grabbing at internal details, we have to adapt as they
# change over versions.
def filename_for_frame(frame):
try:
return frame.f_locals["self"].origin.name
except (KeyError, AttributeError):
return None
def position_for_node(node):
try:
return node.token.position
except AttributeError:
return None
def position_for_token(token):
return token.position
else:
def filename_for_frame(frame):
try:
return frame.f_locals["self"].source[0].name
except (KeyError, AttributeError, IndexError):
return None
def position_for_node(node):
return node.source[1]
def position_for_token(token):
return token.source[1]
def read_template_source(filename):
"""Read the source of a Django template, returning the Unicode text."""
# Import this late to be sure we don't trigger settings machinery too
# early.
from django.conf import settings
if not settings.configured:
settings.configure()
with open(filename, "rb") as f:
# The FILE_CHARSET setting will be removed in 3.1:
# https://docs.djangoproject.com/en/3.0/ref/settings/#file-charset
if django.VERSION >= (3, 1):
charset = 'utf-8'
else:
charset = settings.FILE_CHARSET
text = f.read().decode(charset)
return text
class DjangoTemplatePlugin(
coverage.plugin.CoveragePlugin,
coverage.plugin.FileTracer,
):
def __init__(self, options):
extensions = options.get("template_extensions", "html,htm,txt")
self.extensions = [e.strip() for e in extensions.split(",")]
self.debug_checked = False
self.django_template_dir = os.path.normcase(os.path.realpath(
os.path.dirname(django.template.__file__)
))
self.source_map = {}
# --- CoveragePlugin methods
def sys_info(self):
return [
("django_template_dir", self.django_template_dir),
("environment", sorted(
("%s = %s" % (k, v))
for k, v in os.environ.items()
if "DJANGO" in k
)),
]
def file_tracer(self, filename):
if os.path.normcase(filename).startswith(self.django_template_dir):
if not self.debug_checked:
# Keep calling check_debug until it returns True, which it
# will only do after settings have been configured
self.debug_checked = check_debug()
return self
return None
def file_reporter(self, filename):
return FileReporter(filename)
def find_executable_files(self, src_dir):
# We're only interested in files that look like reasonable HTML
# files: Must end with one of our extensions, and must not have
# funny characters that probably mean they are editor junk.
rx = r"^[^.#~!$@%^&*()+=,]+\.(" + "|".join(self.extensions) + r")$"
for (dirpath, dirnames, filenames) in os.walk(src_dir):
for filename in filenames:
if re.search(rx, filename):
yield os.path.join(dirpath, filename)
# --- FileTracer methods
def has_dynamic_source_filename(self):
return True
# "render" is the public method, but "render_annotated" is an internal
# method sometimes implemented directly on nodes.
RENDER_METHODS = {"render", "render_annotated"}
def dynamic_source_filename(self, filename, frame):
if frame.f_code.co_name not in self.RENDER_METHODS:
return None
if 0:
dump_frame(frame, label="dynamic_source_filename")
filename = filename_for_frame(frame)
if filename is not None:
if filename.startswith("<"):
# String templates have a filename of "<unknown source>", and
# can't be reported on later, so ignore them.
return None
return filename
return None
def line_number_range(self, frame):
assert frame.f_code.co_name in self.RENDER_METHODS
if 0:
dump_frame(frame, label="line_number_range")
render_self = frame.f_locals['self']
if isinstance(render_self, (NodeList, Template)):
return -1, -1
position = position_for_node(render_self)
if position is None:
return -1, -1
if SHOW_TRACING:
print("{!r}: {}".format(render_self, position))
s_start, s_end = position
if isinstance(render_self, TextNode):
first_line = render_self.s.splitlines(True)[0]
if first_line.isspace():
s_start += len(first_line)
elif VerbatimNode and isinstance(render_self, VerbatimNode):
# VerbatimNode doesn't track source the same way. s_end only points
# to the end of the {% verbatim %} opening tag, not the entire
# content. Adjust it to cover all of it.
s_end += len(render_self.content)
elif isinstance(render_self, BlockTranslateNode):
# BlockTranslateNode has a list of text and variable tokens.
# Get the end of the contents by looking at the last token,
# and use its endpoint.
last_tokens = render_self.plural or render_self.singular
s_end = position_for_token(last_tokens[-1])[1]
filename = filename_for_frame(frame)
line_map = self.get_line_map(filename)
start = get_line_number(line_map, s_start)
end = get_line_number(line_map, s_end-1)
if start < 0 or end < 0:
start, end = -1, -1
if SHOW_TRACING:
print("line_number_range({}) -> {}".format(
filename, (start, end)
))
return start, end
# --- FileTracer helpers
def get_line_map(self, filename):
"""The line map for `filename`.
A line map is a list of character offsets, indicating where each line
in the text begins. For example, a line map like this::
[13, 19, 30]
means that line 2 starts at character 13, line 3 starts at 19, etc.
Line 1 always starts at character 0.
"""
if filename not in self.source_map:
template_source = read_template_source(filename)
if 0: # change to see the template text
for i in range(0, len(template_source), 10):
print("%3d: %r" % (i, template_source[i:i+10]))
self.source_map[filename] = make_line_map(template_source)
return self.source_map[filename]
class FileReporter(coverage.plugin.FileReporter):
def __init__(self, filename):
super(FileReporter, self).__init__(filename)
# TODO: html filenames are absolute.
self._source = None
def source(self):
if self._source is None:
try:
self._source = read_template_source(self.filename)
except (IOError, UnicodeError) as exc:
raise NoSource("Couldn't read {}: {}".format(self.filename, exc))
return self._source
def lines(self):
source_lines = set()
if SHOW_PARSING:
print("-------------- {}".format(self.filename))
if django.VERSION >= (1, 9):
lexer = Lexer(self.source())
else:
lexer = Lexer(self.source(), self.filename)
tokens = lexer.tokenize()
# Are we inside a comment?
comment = False
# Is this a template that extends another template?
extends = False
# Are we inside a block?
inblock = False
for token in tokens:
if SHOW_PARSING:
print(
"%10s %2d: %r" % (
_token_name(token.token_type),
token.lineno,
token.contents,
)
)
if token.token_type == TokenType.BLOCK:
if token.contents == "endcomment":
comment = False
continue
if comment:
continue
if token.token_type == TokenType.BLOCK:
if token.contents.startswith("endblock"):
inblock = False
elif token.contents.startswith("block"):
inblock = True
if extends:
continue
if extends and not inblock:
# In an inheriting tempalte, ignore all tags outside of
# blocks.
continue
if token.contents == "comment":
comment = True
if token.contents.startswith("end"):
continue
elif token.contents in ("else", "empty"):
continue
elif token.contents.startswith("elif"):
# NOTE: I don't like this, I want to be able to trace elif
# nodes, but the Django template engine doesn't track them
# in a way that we can get useful information from them.
continue
elif token.contents.startswith("extends"):
extends = True
source_lines.add(token.lineno)
elif token.token_type == TokenType.VAR:
source_lines.add(token.lineno)
elif token.token_type == TokenType.TEXT:
if extends and not inblock:
continue
# Text nodes often start with newlines, but we don't want to
# consider that first line to be part of the text.
lineno = token.lineno
lines = token.contents.splitlines(True)
num_lines = len(lines)
if lines[0].isspace():
lineno += 1
num_lines -= 1
source_lines.update(range(lineno, lineno+num_lines))
if SHOW_PARSING:
print("\t\t\tNow source_lines is: {!r}".format(source_lines))
return source_lines
def running_sum(seq):
total = 0
for num in seq:
total += num
yield total
def make_line_map(text):
line_lengths = [len(line) for line in text.splitlines(True)]
line_map = list(running_sum(line_lengths))
return line_map
def get_line_number(line_map, offset):
"""Find a line number, given a line map and a character offset."""
for lineno, line_offset in enumerate(line_map, start=1):
if line_offset > offset:
return lineno
return -1
def dump_frame(frame, label=""):
"""Dump interesting information about this frame."""
locals = dict(frame.f_locals)
self = locals.get('self', None)
context = locals.get('context', None)
if "__builtins__" in locals:
del locals["__builtins__"]
if label:
label = " ( %s ) " % label
print("-- frame --%s---------------------" % label)
print("{}:{}:{}".format(
os.path.basename(frame.f_code.co_filename),
frame.f_lineno,
type(self),
))
print(locals)
if self:
print("self:", self.__dict__)
if context:
print("context:", context.__dict__)
print("\\--")