Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(57)

Side by Side Diff: telemetry/telemetry/util/js_template.py

Issue 2687773003: [Telemetry] Switch clients to new JavaScript API (batch 5) (Closed)
Patch Set: fix tests Created 3 years, 10 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
1 # Copyright 2016 The Chromium Authors. All rights reserved. 1 # Copyright 2016 The Chromium Authors. All rights reserved.
2 # Use of this source code is governed by a BSD-style license that can be 2 # Use of this source code is governed by a BSD-style license that can be
3 # found in the LICENSE file. 3 # found in the LICENSE file.
4 4
5 import json 5 import json
6 import re 6 import re
7 7
8 8
9 RE_REPLACEMENT_FIELD = re.compile(r'{{(?P<field_spec>[^}]*)}}') 9 RE_REPLACEMENT_FIELD = re.compile(r'{{(?P<field_spec>[^}]*)}}')
10 RE_FIELD_IDENTIFIER = re.compile(r'(?P<modifier>@)?(?P<name>\w+)$') 10 RE_FIELD_IDENTIFIER = re.compile(r'(?P<modifier>[@*])?(?P<name>\w+)$')
11 11
12 12
13 def RenderValue(value): 13 def RenderValue(value):
14 """Convert a Python value to a string with its JavaScript representation.""" 14 """Convert a Python value to a string with its JavaScript representation."""
15 return json.dumps(value, sort_keys=True) 15 return json.dumps(value, sort_keys=True)
16 16
17 17
18 def Render(template, **kwargs): 18 def Render(template, **kwargs):
19 """Helper method to interpolate Python values into JavaScript snippets. 19 """Helper method to interpolate Python values into JavaScript snippets.
20 20
21 Placeholders in the template, field names enclosed in double curly braces, 21 Placeholders in the template, field names enclosed in double curly braces,
22 are replaced with the value of the corresponding named argument. Prefixing 22 are replaced with the value of the corresponding named argument.
23 a field name with '@' causes the value to be inserted literally. 23
24 Prefixing a field name with '*' causes the value, expected to be a
25 sequence of individual values, to be all interpolated and separated by
26 commas.
27
28 Prefixing a field name with '@' causes the value to be inserted literally.
24 29
25 30
26 For example: 31 For example:
27 32
28 js_template.Render( 33 js_template.Render(
29 'var {{ @var_name }} = f({{ x }}, {{ y }});', 34 'var {{ @var_name }} = f({{ x }}, {{ *args }});',
30 var_name='foo', x=42, y='hello') 35 var_name='foo', x=42, args=('hello', 'there'))
31 36
32 Returns: 37 Returns:
33 38
34 'var foo = f(42, "hello");' 39 'var foo = f(42, "hello", "there");'
35 40
36 Args: 41 Args:
37 template: A string with a JavaScript template, tagged with {{ fields }} 42 template: A string with a JavaScript template, tagged with {{ fields }}
38 to interpolate with values. 43 to interpolate with values.
39 **kwargs: Values to be interpolated in the template. 44 **kwargs: Values to be interpolated in the template.
40 """ 45 """
41 unused = set(kwargs) 46 unused = set(kwargs)
42 47
43 def interpolate(m): 48 def interpolate(m):
44 field_spec = m.group('field_spec').strip() 49 field_spec = m.group('field_spec').strip()
45 field = RE_FIELD_IDENTIFIER.match(field_spec) 50 field = RE_FIELD_IDENTIFIER.match(field_spec)
46 if not field: 51 if not field:
47 raise KeyError(field_spec) 52 raise KeyError(field_spec)
48 key = field.group('name') 53 key = field.group('name')
49 value = kwargs[key] 54 value = kwargs[key]
50 unused.discard(key) 55 unused.discard(key)
51 if field.group('modifier') == '@': 56 if field.group('modifier') == '@':
52 if not isinstance(value, str): 57 if not isinstance(value, str):
53 raise ValueError('Literal value for %s must be a string' % field_spec) 58 raise ValueError('Literal value for %s must be a string' % field_spec)
54 return value 59 return value
60 elif field.group('modifier') == '*':
61 return ', '.join(RenderValue(v) for v in value)
55 else: 62 else:
56 return RenderValue(value) 63 return RenderValue(value)
57 64
58 result = RE_REPLACEMENT_FIELD.sub(interpolate, template) 65 result = RE_REPLACEMENT_FIELD.sub(interpolate, template)
59 if unused: 66 if unused:
60 raise TypeError('Unexpected arguments not used in template: %s.' % ( 67 raise TypeError('Unexpected arguments not used in template: %s.' % (
61 ', '.join(repr(str(k)) for k in sorted(unused)))) 68 ', '.join(repr(str(k)) for k in sorted(unused))))
62 return result 69 return result
OLDNEW
« no previous file with comments | « telemetry/telemetry/page/page_test_unittest.py ('k') | telemetry/telemetry/util/js_template_unittest.py » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698