cygprofile: increase timeouts to allow showing web contents
[chromium-blink-merge.git] / tools / metrics / histograms / update_policies.py
blob346dcab18b55868cfc39ac1166328f51c8f3f505
1 # Copyright 2013 The Chromium Authors. All rights reserved.
2 # Use of this source code is governed by a BSD-style license that can be
3 # found in the LICENSE file.
5 """Updates EnterprisePolicies enum in histograms.xml file with policy
6 definitions read from policy_templates.json.
8 If the file was pretty-printed, the updated version is pretty-printed too.
9 """
11 import os
12 import re
13 import sys
15 from ast import literal_eval
16 from optparse import OptionParser
17 from xml.dom import minidom
19 sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'common'))
20 from diff_util import PromptUserToAcceptDiff
21 import path_util
23 import print_style
25 HISTOGRAMS_PATH = path_util.GetHistogramsFile()
26 POLICY_TEMPLATES_PATH = 'components/policy/resources/policy_templates.json'
27 ENUM_NAME = 'EnterprisePolicies'
29 class UserError(Exception):
30 def __init__(self, message):
31 Exception.__init__(self, message)
33 @property
34 def message(self):
35 return self.args[0]
38 def FlattenPolicies(policy_definitions, policy_list):
39 """Appends a list of policies defined in |policy_definitions| to
40 |policy_list|, flattening subgroups.
42 Args:
43 policy_definitions: A list of policy definitions and groups, as in
44 policy_templates.json file.
45 policy_list: A list that has policy definitions appended to it.
46 """
47 for policy in policy_definitions:
48 if policy['type'] == 'group':
49 FlattenPolicies(policy['policies'], policy_list)
50 else:
51 policy_list.append(policy)
54 def ParsePlaceholders(text):
55 """Parse placeholders in |text|, making it more human-readable. The format of
56 |text| is exactly the same as in captions in policy_templates.json: it can
57 contain XML tags (ph, ex) and $1-like substitutions. Note that this function
58 does only a very simple parsing that is not fully correct, but should be
59 enough for all practical situations.
61 Args:
62 text: A string containing placeholders.
64 Returns:
65 |text| with placeholders removed or replaced by readable text.
66 """
67 text = re.sub(r'\$\d+', '', text) # Remove $1-like substitutions.
68 text = re.sub(r'<[^>]+>', '', text) # Remove XML tags.
69 return text
72 def UpdateHistogramDefinitions(policy_templates, doc):
73 """Sets the children of <enum name="EnterprisePolicies" ...> node in |doc| to
74 values generated from policy ids contained in |policy_templates|.
76 Args:
77 policy_templates: A list of dictionaries, defining policies or policy
78 groups. The format is exactly the same as in
79 policy_templates.json file.
80 doc: A minidom.Document object representing parsed histogram definitions
81 XML file.
82 """
83 # Find EnterprisePolicies enum.
84 for enum_node in doc.getElementsByTagName('enum'):
85 if enum_node.attributes['name'].value == ENUM_NAME:
86 policy_enum_node = enum_node
87 break
88 else:
89 raise UserError('No policy enum node found')
91 # Remove existing values.
92 while policy_enum_node.hasChildNodes():
93 policy_enum_node.removeChild(policy_enum_node.lastChild)
95 # Add a "Generated from (...)" comment
96 comment = ' Generated from {0} '.format(POLICY_TEMPLATES_PATH)
97 policy_enum_node.appendChild(doc.createComment(comment))
99 # Add values generated from policy templates.
100 ordered_policies = []
101 FlattenPolicies(policy_templates['policy_definitions'], ordered_policies)
102 ordered_policies.sort(key=lambda policy: policy['id'])
103 for policy in ordered_policies:
104 node = doc.createElement('int')
105 node.attributes['value'] = str(policy['id'])
106 node.attributes['label'] = ParsePlaceholders(policy['caption'])
107 policy_enum_node.appendChild(node)
110 def main():
111 if len(sys.argv) > 1:
112 print >>sys.stderr, 'No arguments expected!'
113 sys.stderr.write(__doc__)
114 sys.exit(1)
116 with open(path_util.GetInputFile(POLICY_TEMPLATES_PATH), 'rb') as f:
117 policy_templates = literal_eval(f.read())
118 with open(HISTOGRAMS_PATH, 'rb') as f:
119 histograms_doc = minidom.parse(f)
120 f.seek(0)
121 xml = f.read()
123 UpdateHistogramDefinitions(policy_templates, histograms_doc)
124 new_xml = print_style.GetPrintStyle().PrettyPrintNode(histograms_doc)
125 if PromptUserToAcceptDiff(xml, new_xml, 'Is the updated version acceptable?'):
126 with open(HISTOGRAMS_PATH, 'wb') as f:
127 f.write(new_xml)
130 if __name__ == '__main__':
131 try:
132 main()
133 except UserError as e:
134 print >>sys.stderr, e.message
135 sys.exit(1)