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

Side by Side Diff: tools/metrics/histograms/update_histogram_enum.py

Issue 170233008: Add presubmit check and automatic update script for ExtensionPermission enum. (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: Cleanup Created 6 years, 9 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 2013 The Chromium Authors. All rights reserved. 1 # Copyright 2014 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 """Updates ExtensionFunctions enum in histograms.xml file with values read from 5 """Updates enums in histograms.xml file with values read from provided C++ enum.
6 extension_function_histogram_value.h.
7 6
8 If the file was pretty-printed, the updated version is pretty-printed too. 7 If the file was pretty-printed, the updated version is pretty-printed too.
9 """ 8 """
10 9
11 import logging 10 import logging
12 import os 11 import print_style
13 import re 12 import re
14 import sys 13 import sys
15 14
16 from xml.dom import minidom 15 from xml.dom import minidom
17 import print_style 16 from diffutil import PromptUserToAcceptDiff
18
19 # Import the metrics/common module.
20 sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'common'))
21 from diff_util import PromptUserToAcceptDiff
22
23 HISTOGRAMS_PATH = 'histograms.xml'
24 ENUM_NAME = 'ExtensionFunctions'
25
26 EXTENSION_FUNCTIONS_HISTOGRAM_VALUE_PATH = \
27 '../../../extensions/browser/extension_function_histogram_value.h'
28 ENUM_START_MARKER = "^enum HistogramValue {"
29 ENUM_END_MARKER = "^ENUM_BOUNDARY"
30
31 17
32 class UserError(Exception): 18 class UserError(Exception):
33 def __init__(self, message): 19 def __init__(self, message):
34 Exception.__init__(self, message) 20 Exception.__init__(self, message)
35 21
36 @property 22 @property
37 def message(self): 23 def message(self):
38 return self.args[0] 24 return self.args[0]
39 25
40 def ExtractRegexGroup(line, regex): 26
41 m = re.match(regex, line) 27 def Log(message):
42 if m: 28 logging.info(message)
43 return m.group(1)
44 else:
45 return None
46 29
47 30
48 def ReadHistogramValues(filename): 31 def ExtractRegexGroup(line, regex):
49 """Returns a list of pairs (label, value) corresponding to HistogramValue. 32 m = re.match(regex, line)
33 if m:
34 return m.group(1)
Jeffrey Yasskin 2014/03/25 01:26:36 Note that this will throw an IndexError if the reg
35 else:
36 return None
50 37
51 Reads the extension_function_histogram_value.h file, locates the 38
52 HistogramValue enum definition and returns a pair for each entry. 39 def ReadHistogramValues(filename, start_marker, end_marker):
40 """Reads in values from |filename|, returning a list of (label, value) pairs
41 corresponding to the enum framed by |start_marker| and |end_marker|.
53 """ 42 """
54
55 # Read the file as a list of lines 43 # Read the file as a list of lines
56 with open(filename) as f: 44 with open(filename) as f:
57 content = f.readlines() 45 content = f.readlines()
58 46
59 # Locate the enum definition and collect all entries in it 47 # Locate the enum definition and collect all entries in it
60 inside_enum = False # We haven't found the enum definition yet 48 inside_enum = False # We haven't found the enum definition yet
61 result = [] 49 result = []
62 for line in content: 50 for line in content:
63 line = line.strip() 51 line = line.strip()
64 if inside_enum: 52 if inside_enum:
65 # Exit condition: we reached last enum value 53 # Exit condition: we reached last enum value
66 if re.match(ENUM_END_MARKER, line): 54 if re.match(end_marker, line):
67 inside_enum = False 55 inside_enum = False
68 else: 56 else:
69 # Inside enum: generate new xml entry 57 # Inside enum: generate new xml entry
70 label = ExtractRegexGroup(line.strip(), "^([\w]+)") 58 label = ExtractRegexGroup(line.strip(), "^([\w]+)")
71 if label: 59 if label:
72 result.append((label, enum_value)) 60 result.append((label, enum_value))
73 enum_value += 1 61 enum_value += 1
74 else: 62 else:
75 if re.match(ENUM_START_MARKER, line): 63 if re.match(start_marker, line):
76 inside_enum = True 64 inside_enum = True
77 enum_value = 0 # Start at 'UNKNOWN' 65 enum_value = 0 # Start at 'UNKNOWN'
78 return result 66 return result
79 67
80 68
81 def UpdateHistogramDefinitions(histogram_values, document): 69 def UpdateHistogramDefinitions(histogram_enum_name, source_enum_values,
82 """Sets the children of <enum name="ExtensionFunctions" ...> node in 70 source_enum_path, document):
83 |document| to values generated from policy ids contained in 71 """Sets the children of <enum name=|histogram_enum_name| ...> node in
84 |policy_templates|. 72 |document| to values generated from (label, value) pairs contained in
85 73 |source_enum_values|.
86 Args:
87 histogram_values: A list of pairs (label, value) defining each extension
88 function
89 document: A minidom.Document object representing parsed histogram
90 definitions XML file.
91
92 """ 74 """
93 # Find ExtensionFunctions enum. 75 # Find ExtensionFunctions enum.
94 for enum_node in document.getElementsByTagName('enum'): 76 for enum_node in document.getElementsByTagName('enum'):
95 if enum_node.attributes['name'].value == ENUM_NAME: 77 if enum_node.attributes['name'].value == histogram_enum_name:
96 extension_functions_enum_node = enum_node 78 histogram_enum_node = enum_node
97 break 79 break
98 else: 80 else:
99 raise UserError('No policy enum node found') 81 raise UserError('No {0} enum node found'.format(histogram_enum_name))
100 82
101 # Remove existing values. 83 # Remove existing values.
102 while extension_functions_enum_node.hasChildNodes(): 84 while histogram_enum_node.hasChildNodes():
103 extension_functions_enum_node.removeChild( 85 histogram_enum_node.removeChild(histogram_enum_node.lastChild)
104 extension_functions_enum_node.lastChild)
105 86
106 # Add a "Generated from (...)" comment 87 # Add a "Generated from (...)" comment
107 comment = ' Generated from {0} '.format( 88 comment = ' Generated from {0} '.format(source_enum_path)
108 EXTENSION_FUNCTIONS_HISTOGRAM_VALUE_PATH) 89 histogram_enum_node.appendChild(document.createComment(comment))
109 extension_functions_enum_node.appendChild(document.createComment(comment))
110 90
111 # Add values generated from policy templates. 91 # Add values generated from policy templates.
112 for (label, value) in histogram_values: 92 for (label, value) in source_enum_values:
113 node = document.createElement('int') 93 node = document.createElement('int')
114 node.attributes['value'] = str(value) 94 node.attributes['value'] = str(value)
115 node.attributes['label'] = label 95 node.attributes['label'] = label
116 extension_functions_enum_node.appendChild(node) 96 histogram_enum_node.appendChild(node)
117 97
118 def Log(message):
119 logging.info(message)
120 98
121 def main(): 99 def UpdateHistogramEnum(histogram_enum_name, source_enum_path,
100 start_marker, end_marker):
101 """Updates |histogram_enum_name| enum in histograms.xml file with values
102 read from |source_enum_path|, where |start_marker| and |end_marker| indicate
103 the beginning and end of the source enum definition, respectively.
104 """
105 # TODO(ahernandez.miralles): The line below is present in nearly every
106 # file in this directory; factor out into a central location
107 HISTOGRAMS_PATH = 'histograms.xml'
ahernandez 2014/03/17 22:58:42 This seems like it would be better in a separate C
108
122 if len(sys.argv) > 1: 109 if len(sys.argv) > 1:
123 print >>sys.stderr, 'No arguments expected!' 110 print >>sys.stderr, 'No arguments expected!'
124 sys.stderr.write(__doc__) 111 sys.stderr.write(__doc__)
125 sys.exit(1) 112 sys.exit(1)
126 113
127 Log('Reading histogram enum definition from "%s".' 114 Log('Reading histogram enum definition from "{0}".'.format(source_enum_path))
128 % (EXTENSION_FUNCTIONS_HISTOGRAM_VALUE_PATH)) 115 source_enum_values = ReadHistogramValues(source_enum_path, start_marker,
129 histogram_values = ReadHistogramValues( 116 end_marker)
130 EXTENSION_FUNCTIONS_HISTOGRAM_VALUE_PATH)
131 117
132 Log('Reading existing histograms from "%s".' % (HISTOGRAMS_PATH)) 118 Log('Reading existing histograms from "{0}".'.format(HISTOGRAMS_PATH))
133 with open(HISTOGRAMS_PATH, 'rb') as f: 119 with open(HISTOGRAMS_PATH, 'rb') as f:
134 histograms_doc = minidom.parse(f) 120 histograms_doc = minidom.parse(f)
135 f.seek(0) 121 f.seek(0)
136 xml = f.read() 122 xml = f.read()
137 123
138 Log('Comparing histograms enum with new enum definition.') 124 Log('Comparing histograms enum with new enum definition.')
139 UpdateHistogramDefinitions(histogram_values, histograms_doc) 125 UpdateHistogramDefinitions(histogram_enum_name, source_enum_values,
126 source_enum_path, histograms_doc)
140 127
141 Log('Writing out new histograms file.') 128 Log('Writing out new histograms file.')
142 new_xml = print_style.GetPrintStyle().PrettyPrintNode(histograms_doc) 129 new_xml = print_style.GetPrintStyle().PrettyPrintNode(histograms_doc)
143
144 if PromptUserToAcceptDiff(xml, new_xml, 'Is the updated version acceptable?'): 130 if PromptUserToAcceptDiff(xml, new_xml, 'Is the updated version acceptable?'):
145 with open(HISTOGRAMS_PATH, 'wb') as f: 131 with open(HISTOGRAMS_PATH, 'wb') as f:
146 f.write(new_xml) 132 f.write(new_xml)
147 133
148 Log('Done.') 134 Log('Done.')
149
150
151 if __name__ == '__main__':
152 main()
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698