blob: 9164de115554cdc3d2fa03df8f1369feb92fcc46 [file] [log] [blame]
wychen037f6e9e2017-01-10 17:14:561#!/usr/bin/env python
2# Copyright 2017 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.
5
6"""Find header files missing in GN.
7
8This script gets all the header files from ninja_deps, which is from the true
9dependency generated by the compiler, and report if they don't exist in GN.
10"""
11
12import argparse
13import json
14import os
15import re
wychen03629112017-05-25 20:37:1816import shutil
wychen037f6e9e2017-01-10 17:14:5617import subprocess
18import sys
wychen03629112017-05-25 20:37:1819import tempfile
wychenef74ec992017-04-27 06:28:2520from multiprocessing import Process, Queue
wychen037f6e9e2017-01-10 17:14:5621
nodir6a40e9402017-06-07 05:49:0322SRC_DIR = os.path.abspath(
23 os.path.join(os.path.abspath(os.path.dirname(__file__)), os.path.pardir))
24DEPOT_TOOLS_DIR = os.path.join(SRC_DIR, 'third_party', 'depot_tools')
25
wychen037f6e9e2017-01-10 17:14:5626
wychenef74ec992017-04-27 06:28:2527def GetHeadersFromNinja(out_dir, q):
wychen037f6e9e2017-01-10 17:14:5628 """Return all the header files from ninja_deps"""
wychenef74ec992017-04-27 06:28:2529
30 def NinjaSource():
nodir6a40e9402017-06-07 05:49:0331 cmd = [os.path.join(DEPOT_TOOLS_DIR, 'ninja'), '-C', out_dir, '-t', 'deps']
wychenef74ec992017-04-27 06:28:2532 # A negative bufsize means to use the system default, which usually
33 # means fully buffered.
34 popen = subprocess.Popen(cmd, stdout=subprocess.PIPE, bufsize=-1)
35 for line in iter(popen.stdout.readline, ''):
36 yield line.rstrip()
37
38 popen.stdout.close()
39 return_code = popen.wait()
40 if return_code:
41 raise subprocess.CalledProcessError(return_code, cmd)
42
wychen09692cd2017-05-26 01:57:1643 ans, err = set(), None
44 try:
wychen0735fd762017-06-03 07:53:2645 ans = ParseNinjaDepsOutput(NinjaSource(), out_dir)
wychen09692cd2017-05-26 01:57:1646 except Exception as e:
47 err = str(e)
48 q.put((ans, err))
wychen037f6e9e2017-01-10 17:14:5649
50
wychen0735fd762017-06-03 07:53:2651def ParseNinjaDepsOutput(ninja_out, out_dir):
wychen037f6e9e2017-01-10 17:14:5652 """Parse ninja output and get the header files"""
53 all_headers = set()
54
wychen97580de2017-06-13 00:52:4455 # Ninja always uses "/", even on Windows.
56 prefix = '../../'
wychen037f6e9e2017-01-10 17:14:5657
58 is_valid = False
wychenef74ec992017-04-27 06:28:2559 for line in ninja_out:
wychen037f6e9e2017-01-10 17:14:5660 if line.startswith(' '):
61 if not is_valid:
62 continue
63 if line.endswith('.h') or line.endswith('.hh'):
64 f = line.strip()
65 if f.startswith(prefix):
66 f = f[6:] # Remove the '../../' prefix
67 # build/ only contains build-specific files like build_config.h
68 # and buildflag.h, and system header files, so they should be
69 # skipped.
wychen0735fd762017-06-03 07:53:2670 if f.startswith(out_dir) or f.startswith('out'):
71 continue
wychen037f6e9e2017-01-10 17:14:5672 if not f.startswith('build'):
73 all_headers.add(f)
74 else:
75 is_valid = line.endswith('(VALID)')
76
77 return all_headers
78
79
wychenef74ec992017-04-27 06:28:2580def GetHeadersFromGN(out_dir, q):
wychen037f6e9e2017-01-10 17:14:5681 """Return all the header files from GN"""
wychen03629112017-05-25 20:37:1882
83 tmp = None
wychen09692cd2017-05-26 01:57:1684 ans, err = set(), None
wychen03629112017-05-25 20:37:1885 try:
wychen97580de2017-06-13 00:52:4486 # Argument |dir| is needed to make sure it's on the same drive on Windows.
87 # dir='' means dir='.', but doesn't introduce an unneeded prefix.
88 tmp = tempfile.mkdtemp(dir='')
wychen03629112017-05-25 20:37:1889 shutil.copy2(os.path.join(out_dir, 'args.gn'),
90 os.path.join(tmp, 'args.gn'))
91 # Do "gn gen" in a temp dir to prevent dirtying |out_dir|.
wychen97580de2017-06-13 00:52:4492 gn_exe = 'gn.bat' if sys.platform == 'win32' else 'gn'
nodir6a40e9402017-06-07 05:49:0393 subprocess.check_call([
wychen97580de2017-06-13 00:52:4494 os.path.join(DEPOT_TOOLS_DIR, gn_exe), 'gen', tmp, '--ide=json', '-q'])
wychen03629112017-05-25 20:37:1895 gn_json = json.load(open(os.path.join(tmp, 'project.json')))
wychen09692cd2017-05-26 01:57:1696 ans = ParseGNProjectJSON(gn_json, out_dir, tmp)
97 except Exception as e:
98 err = str(e)
wychen03629112017-05-25 20:37:1899 finally:
100 if tmp:
101 shutil.rmtree(tmp)
wychen09692cd2017-05-26 01:57:16102 q.put((ans, err))
wychen037f6e9e2017-01-10 17:14:56103
104
wychen03629112017-05-25 20:37:18105def ParseGNProjectJSON(gn, out_dir, tmp_out):
wychen037f6e9e2017-01-10 17:14:56106 """Parse GN output and get the header files"""
107 all_headers = set()
108
109 for _target, properties in gn['targets'].iteritems():
wychen55235782017-04-28 01:59:15110 sources = properties.get('sources', [])
111 public = properties.get('public', [])
112 # Exclude '"public": "*"'.
113 if type(public) is list:
114 sources += public
115 for f in sources:
wychen037f6e9e2017-01-10 17:14:56116 if f.endswith('.h') or f.endswith('.hh'):
117 if f.startswith('//'):
118 f = f[2:] # Strip the '//' prefix.
wychen03629112017-05-25 20:37:18119 if f.startswith(tmp_out):
120 f = out_dir + f[len(tmp_out):]
wychen037f6e9e2017-01-10 17:14:56121 all_headers.add(f)
122
123 return all_headers
124
125
wychenef74ec992017-04-27 06:28:25126def GetDepsPrefixes(q):
wychen037f6e9e2017-01-10 17:14:56127 """Return all the folders controlled by DEPS file"""
wychen09692cd2017-05-26 01:57:16128 prefixes, err = set(), None
129 try:
wychen97580de2017-06-13 00:52:44130 gclient_exe = 'gclient.bat' if sys.platform == 'win32' else 'gclient'
nodir6a40e9402017-06-07 05:49:03131 gclient_out = subprocess.check_output([
wychen97580de2017-06-13 00:52:44132 os.path.join(DEPOT_TOOLS_DIR, gclient_exe),
133 'recurse', '--no-progress', '-j1',
134 'python', '-c', 'import os;print os.environ["GCLIENT_DEP_PATH"]'],
135 universal_newlines=True)
wychen09692cd2017-05-26 01:57:16136 for i in gclient_out.split('\n'):
137 if i.startswith('src/'):
138 i = i[4:]
139 prefixes.add(i)
140 except Exception as e:
141 err = str(e)
142 q.put((prefixes, err))
wychen037f6e9e2017-01-10 17:14:56143
144
wychen0735fd762017-06-03 07:53:26145def IsBuildClean(out_dir):
nodir6a40e9402017-06-07 05:49:03146 cmd = [os.path.join(DEPOT_TOOLS_DIR, 'ninja'), '-C', out_dir, '-n']
wychen0735fd762017-06-03 07:53:26147 out = subprocess.check_output(cmd)
148 return 'no work to do.' in out
149
150
wychen037f6e9e2017-01-10 17:14:56151def ParseWhiteList(whitelist):
152 out = set()
153 for line in whitelist.split('\n'):
154 line = re.sub(r'#.*', '', line).strip()
155 if line:
156 out.add(line)
157 return out
158
159
wychene7a3d6482017-04-29 07:12:17160def FilterOutDepsedRepo(files, deps):
161 return {f for f in files if not any(f.startswith(d) for d in deps)}
162
163
164def GetNonExistingFiles(lst):
165 out = set()
166 for f in lst:
167 if not os.path.isfile(f):
168 out.add(f)
169 return out
170
171
wychen037f6e9e2017-01-10 17:14:56172def main():
wychen0735fd762017-06-03 07:53:26173
174 def DumpJson(data):
175 if args.json:
176 with open(args.json, 'w') as f:
177 json.dump(data, f)
178
179 def PrintError(msg):
180 DumpJson([])
181 parser.error(msg)
182
wychen03629112017-05-25 20:37:18183 parser = argparse.ArgumentParser(description='''
184 NOTE: Use ninja to build all targets in OUT_DIR before running
185 this script.''')
186 parser.add_argument('--out-dir', metavar='OUT_DIR', default='out/Release',
187 help='output directory of the build')
188 parser.add_argument('--json',
189 help='JSON output filename for missing headers')
190 parser.add_argument('--whitelist', help='file containing whitelist')
wychen0735fd762017-06-03 07:53:26191 parser.add_argument('--skip-dirty-check', action='store_true',
192 help='skip checking whether the build is dirty')
wychen037f6e9e2017-01-10 17:14:56193
194 args, _extras = parser.parse_known_args()
195
wychen03629112017-05-25 20:37:18196 if not os.path.isdir(args.out_dir):
197 parser.error('OUT_DIR "%s" does not exist.' % args.out_dir)
198
wychen0735fd762017-06-03 07:53:26199 if not args.skip_dirty_check and not IsBuildClean(args.out_dir):
200 dirty_msg = 'OUT_DIR looks dirty. You need to build all there.'
201 if args.json:
202 # Assume running on the bots. Silently skip this step.
203 # This is possible because "analyze" step can be wrong due to
204 # underspecified header files. See crbug.com/725877
205 print dirty_msg
206 DumpJson([])
207 return 0
208 else:
209 # Assume running interactively.
210 parser.error(dirty_msg)
211
wychenef74ec992017-04-27 06:28:25212 d_q = Queue()
213 d_p = Process(target=GetHeadersFromNinja, args=(args.out_dir, d_q,))
214 d_p.start()
215
216 gn_q = Queue()
217 gn_p = Process(target=GetHeadersFromGN, args=(args.out_dir, gn_q,))
218 gn_p.start()
219
220 deps_q = Queue()
221 deps_p = Process(target=GetDepsPrefixes, args=(deps_q,))
222 deps_p.start()
223
wychen09692cd2017-05-26 01:57:16224 d, d_err = d_q.get()
225 gn, gn_err = gn_q.get()
wychen037f6e9e2017-01-10 17:14:56226 missing = d - gn
wychene7a3d6482017-04-29 07:12:17227 nonexisting = GetNonExistingFiles(gn)
wychen037f6e9e2017-01-10 17:14:56228
wychen09692cd2017-05-26 01:57:16229 deps, deps_err = deps_q.get()
wychene7a3d6482017-04-29 07:12:17230 missing = FilterOutDepsedRepo(missing, deps)
231 nonexisting = FilterOutDepsedRepo(nonexisting, deps)
wychen037f6e9e2017-01-10 17:14:56232
wychenef74ec992017-04-27 06:28:25233 d_p.join()
234 gn_p.join()
235 deps_p.join()
236
wychen09692cd2017-05-26 01:57:16237 if d_err:
wychen0735fd762017-06-03 07:53:26238 PrintError(d_err)
wychen09692cd2017-05-26 01:57:16239 if gn_err:
wychen0735fd762017-06-03 07:53:26240 PrintError(gn_err)
wychen09692cd2017-05-26 01:57:16241 if deps_err:
wychen0735fd762017-06-03 07:53:26242 PrintError(deps_err)
wychen03629112017-05-25 20:37:18243 if len(GetNonExistingFiles(d)) > 0:
wychen0735fd762017-06-03 07:53:26244 print 'Non-existing files in ninja deps:', GetNonExistingFiles(d)
245 PrintError('Found non-existing files in ninja deps. You should ' +
246 'build all in OUT_DIR.')
wychen03629112017-05-25 20:37:18247 if len(d) == 0:
wychen0735fd762017-06-03 07:53:26248 PrintError('OUT_DIR looks empty. You should build all there.')
wychen03629112017-05-25 20:37:18249 if any((('/gen/' in i) for i in nonexisting)):
wychen0735fd762017-06-03 07:53:26250 PrintError('OUT_DIR looks wrong. You should build all there.')
wychen03629112017-05-25 20:37:18251
wychen037f6e9e2017-01-10 17:14:56252 if args.whitelist:
253 whitelist = ParseWhiteList(open(args.whitelist).read())
254 missing -= whitelist
wychen0735fd762017-06-03 07:53:26255 nonexisting -= whitelist
wychen037f6e9e2017-01-10 17:14:56256
257 missing = sorted(missing)
wychene7a3d6482017-04-29 07:12:17258 nonexisting = sorted(nonexisting)
wychen037f6e9e2017-01-10 17:14:56259
wychen0735fd762017-06-03 07:53:26260 DumpJson(sorted(missing + nonexisting))
wychen037f6e9e2017-01-10 17:14:56261
wychene7a3d6482017-04-29 07:12:17262 if len(missing) == 0 and len(nonexisting) == 0:
wychen037f6e9e2017-01-10 17:14:56263 return 0
264
wychene7a3d6482017-04-29 07:12:17265 if len(missing) > 0:
266 print '\nThe following files should be included in gn files:'
267 for i in missing:
268 print i
269
270 if len(nonexisting) > 0:
271 print '\nThe following non-existing files should be removed from gn files:'
272 for i in nonexisting:
273 print i
274
wychen037f6e9e2017-01-10 17:14:56275 return 1
276
277
278if __name__ == '__main__':
279 sys.exit(main())