blob: 0f5da033b55eb0d0f5a2d29e29f15c8f7d4c5d7f [file] [log] [blame]
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Scans the Chromium source for histograms that are absent from histograms.xml.
This is a heuristic scan, so a clean run of this script does not guarantee that
all histograms in the Chromium source are properly mapped. Notably, field
trials are entirely ignored by this script.
import commands
import extract_histograms
import logging
import optparse
import os
import re
import sys
ADJACENT_C_STRING_REGEX = re.compile(r"""
(" # Opening quotation mark
[^"]*) # Literal string contents
" # Closing quotation mark
\s* # Any number of spaces
" # Another opening quotation mark
""", re.VERBOSE)
CONSTANT_REGEX = re.compile(r"""
(\w*::)? # Optional namespace
k[A-Z] # Match a constant identifier: 'k' followed by an uppercase letter
\w* # Match the rest of the constant identifier
$ # Make sure there's only the identifier, nothing else
""", re.VERBOSE)
HISTOGRAM_REGEX = re.compile(r"""
UMA_HISTOGRAM # Match the shared prefix for standard UMA histogram macros
\w* # Match the rest of the macro name, e.g. '_ENUMERATION'
\( # Match the opening parenthesis for the macro
\s* # Match any whitespace -- especially, any newlines
([^,]*) # Capture the first parameter to the macro
, # Match the comma that delineates the first parameter
""", re.VERBOSE)
class DirectoryNotFoundException(Exception):
"""Base class to distinguish locally defined exceptions from standard ones."""
def __init__(self, msg):
self.msg = msg
def __str__(self):
return self.msg
def findDefaultRoot():
"""Find the root of the chromium repo, in case the script is run from the
histograms dir.
string: path to the src dir of the repo.
DirectoryNotFoundException if the target directory cannot be found.
path = os.getcwd()
while path:
head, tail = os.path.split(path)
if tail == 'src':
return path
if path == head:
path = head
raise DirectoryNotFoundException('Could not find src/ dir')
def collapseAdjacentCStrings(string):
"""Collapses any adjacent C strings into a single string.
Useful to re-combine strings that were split across multiple lines to satisfy
the 80-col restriction.
string: The string to recombine, e.g. '"Foo"\n "bar"'
The collapsed string, e.g. "Foobar" for an input of '"Foo"\n "bar"'
while True:
collapsed = ADJACENT_C_STRING_REGEX.sub(r'\1', string, count=1)
if collapsed == string:
return collapsed
string = collapsed
def logNonLiteralHistogram(filename, histogram):
"""Logs a statement warning about a non-literal histogram name found in the
Chromium source.
Filters out known acceptable exceptions.
filename: The filename for the file containing the histogram, e.g.
histogram: The expression that evaluates to the name of the histogram, e.g.
'"FakeHistogram" + variant'
# Ignore histogram macros, which typically contain backslashes so that they
# can be formatted across lines.
if '\\' in histogram:
# Field trials are unique within a session, so are effectively constants.
if histogram.startswith('base::FieldTrial::MakeName'):
# Ignore histogram names that have been pulled out into C++ constants.
if CONSTANT_REGEX.match(histogram):
# TODO(isherman): This is still a little noisy... needs further filtering to
# reduce the noise.
logging.warning('%s contains non-literal histogram name <%s>', filename,
def readChromiumHistograms():
"""Searches the Chromium source for all histogram names.
Also prints warnings for any invocations of the UMA_HISTOGRAM_* macros with
names that might vary during a single run of the app.
A set cotaining any found literal histogram names.
"""'Scanning Chromium source for histograms...')
# Use git grep to find all invocations of the UMA_HISTOGRAM_* macros.
# Examples:
# 'path/to/ UMA_HISTOGRAM_COUNTS_100("FooGroup.FooName",'
locations = commands.getoutput('git gs UMA_HISTOGRAM').split('\n')
filenames = set([location.split(':')[0] for location in locations])
histograms = set()
for filename in filenames:
contents = ''
with open(filename, 'r') as f:
contents =
matches = set(HISTOGRAM_REGEX.findall(contents))
for histogram in matches:
histogram = collapseAdjacentCStrings(histogram)
# Must begin and end with a quotation mark.
if histogram[0] != '"' or histogram[-1] != '"':
logNonLiteralHistogram(filename, histogram)
# Must not include any quotation marks other than at the beginning or end.
histogram_stripped = histogram.strip('"')
if '"' in histogram_stripped:
logNonLiteralHistogram(filename, histogram)
return histograms
def readXmlHistograms(histograms_file_location):
"""Parses all histogram names from histograms.xml.
A set cotaining the parsed histogram names.
"""'Reading histograms from %s...' % histograms_file_location)
histograms = extract_histograms.ExtractHistograms(histograms_file_location)
return set(extract_histograms.ExtractNames(histograms))
def main():
# Find default paths.
default_root = findDefaultRoot()
default_histograms_path = os.path.join(
default_root, 'tools/metrics/histograms/histograms.xml')
# Parse command line options
parser = optparse.OptionParser()
'--root-directory', dest='root_directory', default=default_root,
help='scan within DIRECTORY for histograms [optional, defaults to "%s"]' %
'--histograms-file', dest='histograms_file_location',
help='read histogram definitions from FILE (relative to --root-directory) '
'[optional, defaults to "%s"]' % default_histograms_path,
(options, args) = parser.parse_args()
if args:
logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.INFO)
except EnvironmentError as e:
logging.error("Could not change to root directory: %s", e)
chromium_histograms = readChromiumHistograms()
xml_histograms = readXmlHistograms(options.histograms_file_location)
unmapped_histograms = sorted(chromium_histograms - xml_histograms)
if len(unmapped_histograms):'')'')'Histograms in Chromium but not in %s:' %
for histogram in unmapped_histograms:' %s', histogram)
else:'Success! No unmapped histograms found.')
if __name__ == '__main__':