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

Side by Side Diff: third_party/polymer/v1_0/find_unused_elements.py

Issue 1918333005: Add script to find unused Polymer elements (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: with Created 4 years, 7 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
« no previous file with comments | « no previous file | third_party/polymer/v1_0/reproduce.sh » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(Empty)
1 #!/usr/bin/python2
2
3 # Copyright 2016 The Chromium Authors. All rights reserved.
4 # Use of this source code is governed by a BSD-style license that can be
5 # found in the LICENSE file.
6
7 """Identifies Polymer elements that downloaded but not used by Chrome.
8
9 Only finds "first-order" unused elements; re-run after removing unused elements
10 to check if other elements have become unused.
11 """
12
13 import os
14 import re
15 import subprocess
16
17
18 class UnusedElementsDetector:
19 """Finds unused Polymer elements."""
20
21 # Unused elements to ignore because we plan to use them soon.
22 __whitelist = (
23 # TODO(dschuyler): Use element or remove from whitelist.
24 'carbon-route',
25 # TODO(tsergeant): Use element or remove from whitelist.
26 'iron-scroll-threshold',
27 # Necessary for closure.
28 'polymer-externs',
29 )
30
31 @staticmethod
32 def __StripHtmlComments(filename):
33 """Returns the contents of an HTML file with <!-- --> comments stripped.
34
35 Not a real parser.
36
37 Args:
38 filename: The name of the file to read.
39
40 Returns:
41 A string consisting of the file contents with comments removed.
42 """
43 with open(filename) as f:
44 return re.sub('<!--.*?-->', '', f.read(), flags=re.MULTILINE|re.DOTALL)
45
46 @staticmethod
47 def __StripJsComments(filename):
48 """Returns the minified contents of a JavaScript file with comments and
49 grit directives removed.
50
51 Args:
52 filename: The name of the file to read.
53
54 Returns:
55 A string consisting of the minified file contents with comments and grit
56 directives removed.
57 """
58 with open(filename) as f:
59 text = f.read()
60 text = re.sub('<if .*?>', '', text)
61 text = re.sub('</if>', '', text)
62
63 proc = subprocess.Popen(['uglifyjs', filename], stdout=subprocess.PIPE)
64 return proc.stdout.read()
65
66 @staticmethod
67 def __StripComments(filename):
68 """Returns the contents of a JavaScript or HTML file with comments removed.
69
70 Args:
71 filename: The name of the file to read.
72
73 Returns:
74 A string consisting of the file contents processed via
75 __StripHtmlComments or __StripJsComments.
76 """
77 if filename.endswith('.html'):
78 text = UnusedElementsDetector.__StripHtmlComments(filename)
79 elif filename.endswith('.js'):
80 text = UnusedElementsDetector.__StripJsComments(filename)
81 else:
82 assert False, 'Invalid filename: %s' % filename
83 return text
84
85 @staticmethod
86 def Run():
87 """Finds unused Polymer elements and prints a summary."""
88 proc = subprocess.Popen(
89 ['git', 'rev-parse', '--show-toplevel'],
90 stdout=subprocess.PIPE)
91 src_dir = proc.stdout.read().strip()
92 polymer_dir = os.path.dirname(os.path.realpath(__file__))
93 components_dir = os.path.join(polymer_dir, 'components-chromium')
94
95 elements = []
96 for name in os.listdir(components_dir):
97 path = os.path.join(components_dir, name)
98 if os.path.isdir(path):
99 elements.append(name)
100
101 relevant_src_dirs = (
102 os.path.join(src_dir, 'chrome'),
103 os.path.join(src_dir, 'ui'),
104 os.path.join(src_dir, 'components'),
105 components_dir
106 )
107
108 for element in elements:
109 if element in UnusedElementsDetector.__whitelist:
110 continue
Dan Beam 2016/05/03 19:22:08 what does this do?
michaelpg 2016/05/03 21:29:19 removed
111
112 unused_elements = []
113 for element in elements:
114 if (element not in UnusedElementsDetector.__whitelist and
115 not UnusedElementsDetector.__IsImported(element, relevant_src_dirs)):
116 unused_elements.append(element)
117
118 if len(unused_elements):
Dan Beam 2016/05/03 19:22:08 i think this can be just if unused_elements:
michaelpg 2016/05/03 21:29:19 Done.
119 print 'Found unused elements: %s\nRemove from bower.json and re-run ' \
120 'reproduce.sh, or add to whitelist in %s' % (
121 ', '.join(unused_elements), os.path.basename(__file__))
122
123 @staticmethod
124 def __IsImported(element_dir, dirs):
125 """Returns whether the element directory is used in HTML or JavaScript.
126
127 Args:
128 element_dir: The name of the element's directory.
129 dirs: The directories in which to check for usage.
130
131 Returns:
132 True if the element's directory is used in |dirs|.
133 """
134 polymer_dir = os.path.dirname(os.path.realpath(__file__))
135 components_dir = os.path.join(polymer_dir, 'components-chromium')
136 for path in dirs:
137 # Find an import or script referencing the tag's directory.
138 for (dirpath, _, filenames) in os.walk(path):
139 # Ignore the element's own files.
140 if dirpath.startswith(os.path.join(components_dir, element_dir)):
141 continue
142
143 for filename in filenames:
144 if not filename.endswith('.html') and not filename.endswith('.js'):
145 continue
146
147 # Skip generated files that may include the element source.
148 if filename in ('crisper.js', 'vulcanized.html'):
149 continue
150
151 with open(os.path.join(dirpath, filename)) as f:
152 text = f.read()
153 if not re.search('/%s/' % element_dir, text):
154 continue
155
156 # Check the file again, ignoring comments (e.g. example imports and
157 # scripts).
158 if re.search('/%s' % element_dir,
159 UnusedElementsDetector.__StripComments(
160 os.path.join(dirpath, filename))):
161 return True
162 return False
163
164
165 UnusedElementsDetector.Run()
OLDNEW
« no previous file with comments | « no previous file | third_party/polymer/v1_0/reproduce.sh » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698