blob: 2c3a51a15eb0d9109ddf78b3f28408a556254e6d [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
55 prefix = '..' + os.sep + '..' + os.sep
56
57 is_valid = False
wychenef74ec992017-04-27 06:28:2558 for line in ninja_out:
wychen037f6e9e2017-01-10 17:14:5659 if line.startswith(' '):
60 if not is_valid:
61 continue
62 if line.endswith('.h') or line.endswith('.hh'):
63 f = line.strip()
64 if f.startswith(prefix):
65 f = f[6:] # Remove the '../../' prefix
66 # build/ only contains build-specific files like build_config.h
67 # and buildflag.h, and system header files, so they should be
68 # skipped.
wychen0735fd762017-06-03 07:53:2669 if f.startswith(out_dir) or f.startswith('out'):
70 continue
wychen037f6e9e2017-01-10 17:14:5671 if not f.startswith('build'):
72 all_headers.add(f)
73 else:
74 is_valid = line.endswith('(VALID)')
75
76 return all_headers
77
78
wychenef74ec992017-04-27 06:28:2579def GetHeadersFromGN(out_dir, q):
wychen037f6e9e2017-01-10 17:14:5680 """Return all the header files from GN"""
wychen03629112017-05-25 20:37:1881
82 tmp = None
wychen09692cd2017-05-26 01:57:1683 ans, err = set(), None
wychen03629112017-05-25 20:37:1884 try:
85 tmp = tempfile.mkdtemp()
86 shutil.copy2(os.path.join(out_dir, 'args.gn'),
87 os.path.join(tmp, 'args.gn'))
88 # Do "gn gen" in a temp dir to prevent dirtying |out_dir|.
nodir6a40e9402017-06-07 05:49:0389 subprocess.check_call([
90 os.path.join(DEPOT_TOOLS_DIR, 'gn'), 'gen', tmp, '--ide=json', '-q'])
wychen03629112017-05-25 20:37:1891 gn_json = json.load(open(os.path.join(tmp, 'project.json')))
wychen09692cd2017-05-26 01:57:1692 ans = ParseGNProjectJSON(gn_json, out_dir, tmp)
93 except Exception as e:
94 err = str(e)
wychen03629112017-05-25 20:37:1895 finally:
96 if tmp:
97 shutil.rmtree(tmp)
wychen09692cd2017-05-26 01:57:1698 q.put((ans, err))
wychen037f6e9e2017-01-10 17:14:5699
100
wychen03629112017-05-25 20:37:18101def ParseGNProjectJSON(gn, out_dir, tmp_out):
wychen037f6e9e2017-01-10 17:14:56102 """Parse GN output and get the header files"""
103 all_headers = set()
104
105 for _target, properties in gn['targets'].iteritems():
wychen55235782017-04-28 01:59:15106 sources = properties.get('sources', [])
107 public = properties.get('public', [])
108 # Exclude '"public": "*"'.
109 if type(public) is list:
110 sources += public
111 for f in sources:
wychen037f6e9e2017-01-10 17:14:56112 if f.endswith('.h') or f.endswith('.hh'):
113 if f.startswith('//'):
114 f = f[2:] # Strip the '//' prefix.
wychen03629112017-05-25 20:37:18115 if f.startswith(tmp_out):
116 f = out_dir + f[len(tmp_out):]
wychen037f6e9e2017-01-10 17:14:56117 all_headers.add(f)
118
119 return all_headers
120
121
wychenef74ec992017-04-27 06:28:25122def GetDepsPrefixes(q):
wychen037f6e9e2017-01-10 17:14:56123 """Return all the folders controlled by DEPS file"""
wychen09692cd2017-05-26 01:57:16124 prefixes, err = set(), None
125 try:
nodir6a40e9402017-06-07 05:49:03126 gclient_out = subprocess.check_output([
127 os.path.join(DEPOT_TOOLS_DIR, 'gclient'),
128 'recurse', '--no-progress', '-j1',
129 'python', '-c', 'import os;print os.environ["GCLIENT_DEP_PATH"]'])
wychen09692cd2017-05-26 01:57:16130 for i in gclient_out.split('\n'):
131 if i.startswith('src/'):
132 i = i[4:]
133 prefixes.add(i)
134 except Exception as e:
135 err = str(e)
136 q.put((prefixes, err))
wychen037f6e9e2017-01-10 17:14:56137
138
wychen0735fd762017-06-03 07:53:26139def IsBuildClean(out_dir):
nodir6a40e9402017-06-07 05:49:03140 cmd = [os.path.join(DEPOT_TOOLS_DIR, 'ninja'), '-C', out_dir, '-n']
wychen0735fd762017-06-03 07:53:26141 out = subprocess.check_output(cmd)
142 return 'no work to do.' in out
143
144
wychen037f6e9e2017-01-10 17:14:56145def ParseWhiteList(whitelist):
146 out = set()
147 for line in whitelist.split('\n'):
148 line = re.sub(r'#.*', '', line).strip()
149 if line:
150 out.add(line)
151 return out
152
153
wychene7a3d6482017-04-29 07:12:17154def FilterOutDepsedRepo(files, deps):
155 return {f for f in files if not any(f.startswith(d) for d in deps)}
156
157
158def GetNonExistingFiles(lst):
159 out = set()
160 for f in lst:
161 if not os.path.isfile(f):
162 out.add(f)
163 return out
164
165
wychen037f6e9e2017-01-10 17:14:56166def main():
wychen0735fd762017-06-03 07:53:26167
168 def DumpJson(data):
169 if args.json:
170 with open(args.json, 'w') as f:
171 json.dump(data, f)
172
173 def PrintError(msg):
174 DumpJson([])
175 parser.error(msg)
176
wychen03629112017-05-25 20:37:18177 parser = argparse.ArgumentParser(description='''
178 NOTE: Use ninja to build all targets in OUT_DIR before running
179 this script.''')
180 parser.add_argument('--out-dir', metavar='OUT_DIR', default='out/Release',
181 help='output directory of the build')
182 parser.add_argument('--json',
183 help='JSON output filename for missing headers')
184 parser.add_argument('--whitelist', help='file containing whitelist')
wychen0735fd762017-06-03 07:53:26185 parser.add_argument('--skip-dirty-check', action='store_true',
186 help='skip checking whether the build is dirty')
wychen037f6e9e2017-01-10 17:14:56187
188 args, _extras = parser.parse_known_args()
189
wychen03629112017-05-25 20:37:18190 if not os.path.isdir(args.out_dir):
191 parser.error('OUT_DIR "%s" does not exist.' % args.out_dir)
192
wychen0735fd762017-06-03 07:53:26193 if not args.skip_dirty_check and not IsBuildClean(args.out_dir):
194 dirty_msg = 'OUT_DIR looks dirty. You need to build all there.'
195 if args.json:
196 # Assume running on the bots. Silently skip this step.
197 # This is possible because "analyze" step can be wrong due to
198 # underspecified header files. See crbug.com/725877
199 print dirty_msg
200 DumpJson([])
201 return 0
202 else:
203 # Assume running interactively.
204 parser.error(dirty_msg)
205
wychenef74ec992017-04-27 06:28:25206 d_q = Queue()
207 d_p = Process(target=GetHeadersFromNinja, args=(args.out_dir, d_q,))
208 d_p.start()
209
210 gn_q = Queue()
211 gn_p = Process(target=GetHeadersFromGN, args=(args.out_dir, gn_q,))
212 gn_p.start()
213
214 deps_q = Queue()
215 deps_p = Process(target=GetDepsPrefixes, args=(deps_q,))
216 deps_p.start()
217
wychen09692cd2017-05-26 01:57:16218 d, d_err = d_q.get()
219 gn, gn_err = gn_q.get()
wychen037f6e9e2017-01-10 17:14:56220 missing = d - gn
wychene7a3d6482017-04-29 07:12:17221 nonexisting = GetNonExistingFiles(gn)
wychen037f6e9e2017-01-10 17:14:56222
wychen09692cd2017-05-26 01:57:16223 deps, deps_err = deps_q.get()
wychene7a3d6482017-04-29 07:12:17224 missing = FilterOutDepsedRepo(missing, deps)
225 nonexisting = FilterOutDepsedRepo(nonexisting, deps)
wychen037f6e9e2017-01-10 17:14:56226
wychenef74ec992017-04-27 06:28:25227 d_p.join()
228 gn_p.join()
229 deps_p.join()
230
wychen09692cd2017-05-26 01:57:16231 if d_err:
wychen0735fd762017-06-03 07:53:26232 PrintError(d_err)
wychen09692cd2017-05-26 01:57:16233 if gn_err:
wychen0735fd762017-06-03 07:53:26234 PrintError(gn_err)
wychen09692cd2017-05-26 01:57:16235 if deps_err:
wychen0735fd762017-06-03 07:53:26236 PrintError(deps_err)
wychen03629112017-05-25 20:37:18237 if len(GetNonExistingFiles(d)) > 0:
wychen0735fd762017-06-03 07:53:26238 print 'Non-existing files in ninja deps:', GetNonExistingFiles(d)
239 PrintError('Found non-existing files in ninja deps. You should ' +
240 'build all in OUT_DIR.')
wychen03629112017-05-25 20:37:18241 if len(d) == 0:
wychen0735fd762017-06-03 07:53:26242 PrintError('OUT_DIR looks empty. You should build all there.')
wychen03629112017-05-25 20:37:18243 if any((('/gen/' in i) for i in nonexisting)):
wychen0735fd762017-06-03 07:53:26244 PrintError('OUT_DIR looks wrong. You should build all there.')
wychen03629112017-05-25 20:37:18245
wychen037f6e9e2017-01-10 17:14:56246 if args.whitelist:
247 whitelist = ParseWhiteList(open(args.whitelist).read())
248 missing -= whitelist
wychen0735fd762017-06-03 07:53:26249 nonexisting -= whitelist
wychen037f6e9e2017-01-10 17:14:56250
251 missing = sorted(missing)
wychene7a3d6482017-04-29 07:12:17252 nonexisting = sorted(nonexisting)
wychen037f6e9e2017-01-10 17:14:56253
wychen0735fd762017-06-03 07:53:26254 DumpJson(sorted(missing + nonexisting))
wychen037f6e9e2017-01-10 17:14:56255
wychene7a3d6482017-04-29 07:12:17256 if len(missing) == 0 and len(nonexisting) == 0:
wychen037f6e9e2017-01-10 17:14:56257 return 0
258
wychene7a3d6482017-04-29 07:12:17259 if len(missing) > 0:
260 print '\nThe following files should be included in gn files:'
261 for i in missing:
262 print i
263
264 if len(nonexisting) > 0:
265 print '\nThe following non-existing files should be removed from gn files:'
266 for i in nonexisting:
267 print i
268
wychen037f6e9e2017-01-10 17:14:56269 return 1
270
271
272if __name__ == '__main__':
273 sys.exit(main())