blob: f29416ef64e753fa69ff8305f36e99413a703c11 [file] [log] [blame]
# Copyright 2020 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.
from __future__ import print_function
import argparse
import os
import subprocess
import sys
from css_generator import CSSStyleGenerator
from presubmit_support import RunGit
# TODO(calamity): extend this checker to find unused C++ variables
def FindInvalidCSSVariables(json_string, input_file, git_runner=RunGit):
style_generator = CSSStyleGenerator()
style_generator.AddJSONToModel(json_string, in_file=input_file)
context = style_generator.in_file_to_context[input_file]
if (not context or 'prefix' not in context):
raise KeyError('This tool only works on files with a CSS prefix.')
css_prefix = '--' + context['prefix'] + '-'
valid_names = style_generator.GetCSSVarNames()
found_names_list = git_runner([
'grep', '-ho',
'\\%s[a-z-]*' % css_prefix, '--', '*.css', '*.html', '*.js'
]).splitlines()
found_names = set()
for name in found_names_list:
rgb_suffix = '-rgb'
if name.endswith(rgb_suffix):
name = name[:-len(rgb_suffix)]
found_names.add(name)
return {
'unspecified': found_names.difference(valid_names),
'unused': valid_names.difference(found_names),
'css_prefix': css_prefix,
}
def main():
parser = argparse.ArgumentParser(
description='''Finds CSS variables in the codebase that are prefixed
with |input_file|'s CSS prefix but aren't specified in |input_file|.'''
)
# TODO(calamity): support multiple files if multiple json5 files have the
# same prefix.
parser.add_argument('target', help='source json5 color file')
args = parser.parse_args()
input_file = args.target
with open(input_file, 'r') as f:
result = FindInvalidCSSVariables(f.read(), input_file)
print('Has prefix %s but not in %s:' % (result['css_prefix'], input_file))
for name in sorted(result['unspecified']):
print(name)
print('\nGenerated by %s but not used in codebase:' % input_file)
for name in sorted(result['unused']):
print(name)
return 0
if __name__ == '__main__':
sys.exit(main())