Upstreaming browser/ui/uikit_ui_util from iOS.
[chromium-blink-merge.git] / tools / metrics / histograms / pretty_print.py
blob42f4e6b4e48accb2a24323fb3c0631893c92a98c
1 #!/usr/bin/env python
2 # Copyright 2013 The Chromium Authors. All rights reserved.
3 # Use of this source code is governed by a BSD-style license that can be
4 # found in the LICENSE file.
6 """Pretty-prints the histograms.xml file, alphabetizing tags, wrapping text
7 at 80 chars, enforcing standard attribute ordering, and standardizing
8 indentation.
10 This is quite a bit more complicated than just calling tree.toprettyxml();
11 we need additional customization, like special attribute ordering in tags
12 and wrapping text nodes, so we implement our own full custom XML pretty-printer.
13 """
15 from __future__ import with_statement
17 import logging
18 import os
19 import shutil
20 import sys
21 import xml.dom.minidom
23 sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'common'))
24 import diff_util
25 import presubmit_util
27 import print_style
29 # Tags whose children we want to alphabetize. The key is the parent tag name,
30 # and the value is a pair of the tag name of the children we want to sort,
31 # and a key function that maps each child node to the desired sort key.
32 ALPHABETIZATION_RULES = {
33 'histograms': ('histogram', lambda n: n.attributes['name'].value.lower()),
34 'enums': ('enum', lambda n: n.attributes['name'].value.lower()),
35 'enum': ('int', lambda n: int(n.attributes['value'].value)),
36 'histogram_suffixes_list': (
37 'histogram_suffixes', lambda n: n.attributes['name'].value.lower()),
38 'histogram_suffixes': ('affected-histogram',
39 lambda n: n.attributes['name'].value.lower()),
43 class Error(Exception):
44 pass
47 def unsafeAppendChild(parent, child):
48 """Append child to parent's list of children, ignoring the possibility that it
49 is already in another node's childNodes list. Requires that the previous
50 parent of child is discarded (to avoid non-tree DOM graphs).
51 This can provide a significant speedup as O(n^2) operations are removed (in
52 particular, each child insertion avoids the need to traverse the old parent's
53 entire list of children)."""
54 child.parentNode = None
55 parent.appendChild(child)
56 child.parentNode = parent
59 def TransformByAlphabetizing(node):
60 """Transform the given XML by alphabetizing specific node types according to
61 the rules in ALPHABETIZATION_RULES.
63 Args:
64 node: The minidom node to transform.
66 Returns:
67 The minidom node, with children appropriately alphabetized. Note that the
68 transformation is done in-place, i.e. the original minidom tree is modified
69 directly.
70 """
71 if node.nodeType != xml.dom.minidom.Node.ELEMENT_NODE:
72 for c in node.childNodes:
73 TransformByAlphabetizing(c)
74 return node
76 # Element node with a tag name that we alphabetize the children of?
77 if node.tagName in ALPHABETIZATION_RULES:
78 # Put subnodes in a list of node,key pairs to allow for custom sorting.
79 subtag, key_function = ALPHABETIZATION_RULES[node.tagName]
80 subnodes = []
81 sort_key = -1
82 pending_node_indices = []
83 for c in node.childNodes:
84 if (c.nodeType == xml.dom.minidom.Node.ELEMENT_NODE and
85 c.tagName == subtag):
86 sort_key = key_function(c)
87 # Replace sort keys for delayed nodes.
88 for idx in pending_node_indices:
89 subnodes[idx][1] = sort_key
90 pending_node_indices = []
91 else:
92 # Subnodes that we don't want to rearrange use the next node's key,
93 # so they stay in the same relative position.
94 # Therefore we delay setting key until the next node is found.
95 pending_node_indices.append(len(subnodes))
97 subnodes.append( [c, sort_key] )
99 # Use last sort key for trailing unknown nodes.
100 for idx in pending_node_indices:
101 subnodes[idx][1] = sort_key
103 # Sort the subnode list.
104 subnodes.sort(key=lambda pair: pair[1])
106 # Re-add the subnodes, transforming each recursively.
107 while node.firstChild:
108 node.removeChild(node.firstChild)
109 for (c, _) in subnodes:
110 unsafeAppendChild(node, TransformByAlphabetizing(c))
111 return node
113 # Recursively handle other element nodes and other node types.
114 for c in node.childNodes:
115 TransformByAlphabetizing(c)
116 return node
119 def PrettyPrint(raw_xml):
120 """Pretty-print the given XML.
122 Args:
123 raw_xml: The contents of the histograms XML file, as a string.
125 Returns:
126 The pretty-printed version.
128 tree = xml.dom.minidom.parseString(raw_xml)
129 tree = TransformByAlphabetizing(tree)
130 return print_style.GetPrintStyle().PrettyPrintNode(tree)
133 def main():
134 presubmit_util.DoPresubmitMain(sys.argv, 'histograms.xml',
135 'histograms.before.pretty-print.xml',
136 'pretty_print.py', PrettyPrint)
138 if __name__ == '__main__':
139 main()