blob: c5095e618d5fa6d0e94f615be988d00cb85babae [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
22
wychenef74ec992017-04-27 06:28:2523def GetHeadersFromNinja(out_dir, q):
wychen037f6e9e2017-01-10 17:14:5624 """Return all the header files from ninja_deps"""
wychenef74ec992017-04-27 06:28:2525
26 def NinjaSource():
27 cmd = ['ninja', '-C', out_dir, '-t', 'deps']
28 # A negative bufsize means to use the system default, which usually
29 # means fully buffered.
30 popen = subprocess.Popen(cmd, stdout=subprocess.PIPE, bufsize=-1)
31 for line in iter(popen.stdout.readline, ''):
32 yield line.rstrip()
33
34 popen.stdout.close()
35 return_code = popen.wait()
36 if return_code:
37 raise subprocess.CalledProcessError(return_code, cmd)
38
wychen09692cd2017-05-26 01:57:1639 ans, err = set(), None
40 try:
wychen0735fd762017-06-03 07:53:2641 ans = ParseNinjaDepsOutput(NinjaSource(), out_dir)
wychen09692cd2017-05-26 01:57:1642 except Exception as e:
43 err = str(e)
44 q.put((ans, err))
wychen037f6e9e2017-01-10 17:14:5645
46
wychen0735fd762017-06-03 07:53:2647def ParseNinjaDepsOutput(ninja_out, out_dir):
wychen037f6e9e2017-01-10 17:14:5648 """Parse ninja output and get the header files"""
49 all_headers = set()
50
51 prefix = '..' + os.sep + '..' + os.sep
52
53 is_valid = False
wychenef74ec992017-04-27 06:28:2554 for line in ninja_out:
wychen037f6e9e2017-01-10 17:14:5655 if line.startswith(' '):
56 if not is_valid:
57 continue
58 if line.endswith('.h') or line.endswith('.hh'):
59 f = line.strip()
60 if f.startswith(prefix):
61 f = f[6:] # Remove the '../../' prefix
62 # build/ only contains build-specific files like build_config.h
63 # and buildflag.h, and system header files, so they should be
64 # skipped.
wychen0735fd762017-06-03 07:53:2665 if f.startswith(out_dir) or f.startswith('out'):
66 continue
wychen037f6e9e2017-01-10 17:14:5667 if not f.startswith('build'):
68 all_headers.add(f)
69 else:
70 is_valid = line.endswith('(VALID)')
71
72 return all_headers
73
74
wychenef74ec992017-04-27 06:28:2575def GetHeadersFromGN(out_dir, q):
wychen037f6e9e2017-01-10 17:14:5676 """Return all the header files from GN"""
wychen03629112017-05-25 20:37:1877
78 tmp = None
wychen09692cd2017-05-26 01:57:1679 ans, err = set(), None
wychen03629112017-05-25 20:37:1880 try:
81 tmp = tempfile.mkdtemp()
82 shutil.copy2(os.path.join(out_dir, 'args.gn'),
83 os.path.join(tmp, 'args.gn'))
84 # Do "gn gen" in a temp dir to prevent dirtying |out_dir|.
85 subprocess.check_call(['gn', 'gen', tmp, '--ide=json', '-q'])
86 gn_json = json.load(open(os.path.join(tmp, 'project.json')))
wychen09692cd2017-05-26 01:57:1687 ans = ParseGNProjectJSON(gn_json, out_dir, tmp)
88 except Exception as e:
89 err = str(e)
wychen03629112017-05-25 20:37:1890 finally:
91 if tmp:
92 shutil.rmtree(tmp)
wychen09692cd2017-05-26 01:57:1693 q.put((ans, err))
wychen037f6e9e2017-01-10 17:14:5694
95
wychen03629112017-05-25 20:37:1896def ParseGNProjectJSON(gn, out_dir, tmp_out):
wychen037f6e9e2017-01-10 17:14:5697 """Parse GN output and get the header files"""
98 all_headers = set()
99
100 for _target, properties in gn['targets'].iteritems():
wychen55235782017-04-28 01:59:15101 sources = properties.get('sources', [])
102 public = properties.get('public', [])
103 # Exclude '"public": "*"'.
104 if type(public) is list:
105 sources += public
106 for f in sources:
wychen037f6e9e2017-01-10 17:14:56107 if f.endswith('.h') or f.endswith('.hh'):
108 if f.startswith('//'):
109 f = f[2:] # Strip the '//' prefix.
wychen03629112017-05-25 20:37:18110 if f.startswith(tmp_out):
111 f = out_dir + f[len(tmp_out):]
wychen037f6e9e2017-01-10 17:14:56112 all_headers.add(f)
113
114 return all_headers
115
116
wychenef74ec992017-04-27 06:28:25117def GetDepsPrefixes(q):
wychen037f6e9e2017-01-10 17:14:56118 """Return all the folders controlled by DEPS file"""
wychen09692cd2017-05-26 01:57:16119 prefixes, err = set(), None
120 try:
121 gclient_out = subprocess.check_output(
122 ['gclient', 'recurse', '--no-progress', '-j1',
123 'python', '-c', 'import os;print os.environ["GCLIENT_DEP_PATH"]'])
124 for i in gclient_out.split('\n'):
125 if i.startswith('src/'):
126 i = i[4:]
127 prefixes.add(i)
128 except Exception as e:
129 err = str(e)
130 q.put((prefixes, err))
wychen037f6e9e2017-01-10 17:14:56131
132
wychen0735fd762017-06-03 07:53:26133def IsBuildClean(out_dir):
134 cmd = ['ninja', '-C', out_dir, '-n']
135 out = subprocess.check_output(cmd)
136 return 'no work to do.' in out
137
138
wychen037f6e9e2017-01-10 17:14:56139def ParseWhiteList(whitelist):
140 out = set()
141 for line in whitelist.split('\n'):
142 line = re.sub(r'#.*', '', line).strip()
143 if line:
144 out.add(line)
145 return out
146
147
wychene7a3d6482017-04-29 07:12:17148def FilterOutDepsedRepo(files, deps):
149 return {f for f in files if not any(f.startswith(d) for d in deps)}
150
151
152def GetNonExistingFiles(lst):
153 out = set()
154 for f in lst:
155 if not os.path.isfile(f):
156 out.add(f)
157 return out
158
159
wychen037f6e9e2017-01-10 17:14:56160def main():
wychen0735fd762017-06-03 07:53:26161
162 def DumpJson(data):
163 if args.json:
164 with open(args.json, 'w') as f:
165 json.dump(data, f)
166
167 def PrintError(msg):
168 DumpJson([])
169 parser.error(msg)
170
wychen03629112017-05-25 20:37:18171 parser = argparse.ArgumentParser(description='''
172 NOTE: Use ninja to build all targets in OUT_DIR before running
173 this script.''')
174 parser.add_argument('--out-dir', metavar='OUT_DIR', default='out/Release',
175 help='output directory of the build')
176 parser.add_argument('--json',
177 help='JSON output filename for missing headers')
178 parser.add_argument('--whitelist', help='file containing whitelist')
wychen0735fd762017-06-03 07:53:26179 parser.add_argument('--skip-dirty-check', action='store_true',
180 help='skip checking whether the build is dirty')
wychen037f6e9e2017-01-10 17:14:56181
182 args, _extras = parser.parse_known_args()
183
wychen03629112017-05-25 20:37:18184 if not os.path.isdir(args.out_dir):
185 parser.error('OUT_DIR "%s" does not exist.' % args.out_dir)
186
wychen0735fd762017-06-03 07:53:26187 if not args.skip_dirty_check and not IsBuildClean(args.out_dir):
188 dirty_msg = 'OUT_DIR looks dirty. You need to build all there.'
189 if args.json:
190 # Assume running on the bots. Silently skip this step.
191 # This is possible because "analyze" step can be wrong due to
192 # underspecified header files. See crbug.com/725877
193 print dirty_msg
194 DumpJson([])
195 return 0
196 else:
197 # Assume running interactively.
198 parser.error(dirty_msg)
199
wychenef74ec992017-04-27 06:28:25200 d_q = Queue()
201 d_p = Process(target=GetHeadersFromNinja, args=(args.out_dir, d_q,))
202 d_p.start()
203
204 gn_q = Queue()
205 gn_p = Process(target=GetHeadersFromGN, args=(args.out_dir, gn_q,))
206 gn_p.start()
207
208 deps_q = Queue()
209 deps_p = Process(target=GetDepsPrefixes, args=(deps_q,))
210 deps_p.start()
211
wychen09692cd2017-05-26 01:57:16212 d, d_err = d_q.get()
213 gn, gn_err = gn_q.get()
wychen037f6e9e2017-01-10 17:14:56214 missing = d - gn
wychene7a3d6482017-04-29 07:12:17215 nonexisting = GetNonExistingFiles(gn)
wychen037f6e9e2017-01-10 17:14:56216
wychen09692cd2017-05-26 01:57:16217 deps, deps_err = deps_q.get()
wychene7a3d6482017-04-29 07:12:17218 missing = FilterOutDepsedRepo(missing, deps)
219 nonexisting = FilterOutDepsedRepo(nonexisting, deps)
wychen037f6e9e2017-01-10 17:14:56220
wychenef74ec992017-04-27 06:28:25221 d_p.join()
222 gn_p.join()
223 deps_p.join()
224
wychen09692cd2017-05-26 01:57:16225 if d_err:
wychen0735fd762017-06-03 07:53:26226 PrintError(d_err)
wychen09692cd2017-05-26 01:57:16227 if gn_err:
wychen0735fd762017-06-03 07:53:26228 PrintError(gn_err)
wychen09692cd2017-05-26 01:57:16229 if deps_err:
wychen0735fd762017-06-03 07:53:26230 PrintError(deps_err)
wychen03629112017-05-25 20:37:18231 if len(GetNonExistingFiles(d)) > 0:
wychen0735fd762017-06-03 07:53:26232 print 'Non-existing files in ninja deps:', GetNonExistingFiles(d)
233 PrintError('Found non-existing files in ninja deps. You should ' +
234 'build all in OUT_DIR.')
wychen03629112017-05-25 20:37:18235 if len(d) == 0:
wychen0735fd762017-06-03 07:53:26236 PrintError('OUT_DIR looks empty. You should build all there.')
wychen03629112017-05-25 20:37:18237 if any((('/gen/' in i) for i in nonexisting)):
wychen0735fd762017-06-03 07:53:26238 PrintError('OUT_DIR looks wrong. You should build all there.')
wychen03629112017-05-25 20:37:18239
wychen037f6e9e2017-01-10 17:14:56240 if args.whitelist:
241 whitelist = ParseWhiteList(open(args.whitelist).read())
242 missing -= whitelist
wychen0735fd762017-06-03 07:53:26243 nonexisting -= whitelist
wychen037f6e9e2017-01-10 17:14:56244
245 missing = sorted(missing)
wychene7a3d6482017-04-29 07:12:17246 nonexisting = sorted(nonexisting)
wychen037f6e9e2017-01-10 17:14:56247
wychen0735fd762017-06-03 07:53:26248 DumpJson(sorted(missing + nonexisting))
wychen037f6e9e2017-01-10 17:14:56249
wychene7a3d6482017-04-29 07:12:17250 if len(missing) == 0 and len(nonexisting) == 0:
wychen037f6e9e2017-01-10 17:14:56251 return 0
252
wychene7a3d6482017-04-29 07:12:17253 if len(missing) > 0:
254 print '\nThe following files should be included in gn files:'
255 for i in missing:
256 print i
257
258 if len(nonexisting) > 0:
259 print '\nThe following non-existing files should be removed from gn files:'
260 for i in nonexisting:
261 print i
262
wychen037f6e9e2017-01-10 17:14:56263 return 1
264
265
266if __name__ == '__main__':
267 sys.exit(main())