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

Side by Side Diff: tools/gyp_flag_compare.py

Issue 2246203004: Add a copy of gyp_flag_compare from Chromium to WebRTC's webrtc/tools. (Closed) Base URL: https://chromium.googlesource.com/external/webrtc.git@master
Patch Set: Port from Chromium's script. Created 4 years, 4 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 | no next file » | 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/env python
2
3 # Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
4 #
5 # Use of this source code is governed by a BSD-style license
6 # that can be found in the LICENSE file in the root of the source
7 # tree. An additional intellectual property rights grant can be found
8 # in the file PATENTS. All contributing project authors may
9 # be found in the AUTHORS file in the root of the source tree.
10
11 """Given the output of -t commands from a ninja build for a gyp and GN generated
12 build, report on differences between the command lines.
13
14 This script is best used interactively. Here's a recommended setup:
kjellander_webrtc 2016/08/19 13:09:09 This part is no longer true, right? I think V8's v
15 $ PYTHONPATH=tools/gn/bin python
16 >>> import sys
17 >>> import pprint
18 >>> sys.displayhook = pprint.pprint
19 >>> import gyp_flag_compare as fc
20 >>> fc.ConfigureBuild(['gyp_define=1', 'define=2'], ['gn_arg=1', 'arg=2'])
21 >>> chrome = fc.Comparison('chrome')
22
23 The above starts interactive Python, sets up the output to be pretty-printed
24 (useful for making lists, dicts, and sets readable), configures the build with
25 GN arguments and GYP defines, and then generates a comparison for that build
26 configuration for the "chrome" target.
27
28 After that, the |chrome| object can be used to investigate differences in the
29 build.
30
31 To configure an official build, use this configuration. Disabling NaCl produces
32 a more meaningful comparison, as certain files need to get compiled twice
33 for the IRT build, which uses different flags:
34 >>> fc.ConfigureBuild(
35 ['disable_nacl=1', 'buildtype=Official', 'branding=Chrome'],
36 ['enable_nacl=false', 'is_official_build=true',
37 'is_chrome_branded=true'])
38 """
39
40
41 import os
42 import shlex
43 import subprocess
44 import sys
45
46 # Must be in src/.
47 BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
48 os.chdir(BASE_DIR)
49
50 _GN_OUT_DIR = 'out/gn'
51 _GYP_OUT_DIR = 'out/Release'
52
53
54 def FilterChromium(filename):
55 """Replaces 'chromium/src/' by '' in the filename."""
56 return filename.replace('chromium/src/', '')
57
58
59 def Counts(dict_of_list):
60 """Given a dictionary whose value are lists, returns a dictionary whose values
61 are the length of the list. This can be used to summarize a dictionary.
62 """
63 return {k: len(v) for k, v in dict_of_list.iteritems()}
64
65
66 def CountsByDirname(dict_of_list):
67 """Given a list of files, returns a dict of dirname to counts in that dir."""
68 r = {}
69 for path in dict_of_list:
70 dirname = os.path.dirname(path)
71 r.setdefault(dirname, 0)
72 r[dirname] += 1
73 return r
74
75
76 class Comparison(object):
77 """A comparison of the currently-configured build for a target."""
78
79 def __init__(self, gyp_target, gn_target=None):
80 """Creates a comparison of a GN and GYP target. If the target names differ
81 between the two build systems, then two names may be passed.
82 """
83 if gn_target is None:
84 gn_target = gyp_target
85 self._gyp_target = gyp_target
86 self._gn_target = gn_target
87
88 self._skipped = []
89
90 self._total_diffs = 0
91
92 self._missing_gyp_flags = {}
93 self._missing_gn_flags = {}
94
95 self._missing_gyp_files = {}
96 self._missing_gn_files = {}
97
98 self._CompareFiles()
99
100 @property
101 def gyp_files(self):
102 """Returns the set of files that are in the GYP target."""
103 return set(self._gyp_flags.keys())
104
105 @property
106 def gn_files(self):
107 """Returns the set of files that are in the GN target."""
108 return set(self._gn_flags.keys())
109
110 @property
111 def skipped(self):
112 """Returns the list of compiler commands that were not processed during the
113 comparison.
114 """
115 return self._skipped
116
117 @property
118 def total_differences(self):
119 """Returns the total number of differences detected."""
120 return self._total_diffs
121
122 @property
123 def missing_in_gyp(self):
124 """Differences that are only in GYP build but not in GN, indexed by the
125 difference."""
126 return self._missing_gyp_flags
127
128 @property
129 def missing_in_gn(self):
130 """Differences that are only in the GN build but not in GYP, indexed by
131 the difference."""
132 return self._missing_gn_flags
133
134 @property
135 def missing_in_gyp_by_file(self):
136 """Differences that are only in the GYP build but not in GN, indexed by
137 file.
138 """
139 return self._missing_gyp_files
140
141 @property
142 def missing_in_gn_by_file(self):
143 """Differences that are only in the GYP build but not in GN, indexed by
144 file.
145 """
146 return self._missing_gn_files
147
148 def _CompareFiles(self):
149 """Performs the actual target comparison."""
150 if sys.platform == 'win32':
151 # On Windows flags are stored in .rsp files which are created by building.
152 print >> sys.stderr, 'Building in %s...' % _GN_OUT_DIR
153 Run('ninja -C %s -d keeprsp %s' % (_GN_OUT_DIR, self._gn_target))
154 print >> sys.stderr, 'Building in %s...' % _GYP_OUT_DIR
155 Run('ninja -C %s -d keeprsp %s' % (_GYP_OUT_DIR, self._gn_target))
156
157 gn = Run('ninja -C %s -t commands %s' % (_GN_OUT_DIR, self._gn_target))
158 gyp = Run('ninja -C %s -t commands %s' % (_GYP_OUT_DIR, self._gyp_target))
159
160 self._gn_flags = self._GetFlags(gn.splitlines(),
161 os.path.join(os.getcwd(), _GN_OUT_DIR))
162 self._gyp_flags = self._GetFlags(gyp.splitlines(),
163 os.path.join(os.getcwd(), _GYP_OUT_DIR))
164
165 self._gn_flags = dict((FilterChromium(filename), value)
166 for filename, value in self._gn_flags.iteritems())
167 self._gyp_flags = dict((FilterChromium(filename), value)
168 for filename, value in self._gyp_flags.iteritems())
169
170 all_files = sorted(self.gn_files & self.gyp_files)
171 for filename in all_files:
172 gyp_flags = self._gyp_flags[filename]
173 gn_flags = self._gn_flags[filename]
174 self._CompareLists(filename, gyp_flags, gn_flags, 'dash_f')
175 self._CompareLists(filename, gyp_flags, gn_flags, 'defines')
176 self._CompareLists(filename, gyp_flags, gn_flags, 'include_dirs')
177 self._CompareLists(filename, gyp_flags, gn_flags, 'warnings',
178 # More conservative warnings in GN we consider to be OK.
179 dont_care_gyp=[
180 '/wd4091', # 'keyword' : ignored on left of 'type' when no variable
181 # is declared.
182 '/wd4456', # Declaration hides previous local declaration.
183 '/wd4457', # Declaration hides function parameter.
184 '/wd4458', # Declaration hides class member.
185 '/wd4459', # Declaration hides global declaration.
186 '/wd4702', # Unreachable code.
187 '/wd4800', # Forcing value to bool 'true' or 'false'.
188 '/wd4838', # Conversion from 'type' to 'type' requires a narrowing
189 # conversion.
190 ] if sys.platform == 'win32' else None,
191 dont_care_gn=[
192 '-Wendif-labels',
193 '-Wextra',
194 '-Wsign-compare',
195 ] if not sys.platform == 'win32' else None)
196 self._CompareLists(filename, gyp_flags, gn_flags, 'other')
197
198 def _CompareLists(self, filename, gyp, gn, name,
199 dont_care_gyp=None, dont_care_gn=None):
200 """Return a report of any differences between gyp and gn lists, ignoring
201 anything in |dont_care_{gyp|gn}| respectively."""
202 if gyp[name] == gn[name]:
203 return
204 if not dont_care_gyp:
205 dont_care_gyp = []
206 if not dont_care_gn:
207 dont_care_gn = []
208 gyp_set = set(gyp[name])
209 gn_set = set(gn[name])
210 missing_in_gyp = gyp_set - gn_set
211 missing_in_gn = gn_set - gyp_set
212 missing_in_gyp -= set(dont_care_gyp)
213 missing_in_gn -= set(dont_care_gn)
214
215 for m in missing_in_gyp:
216 self._missing_gyp_flags.setdefault(name, {}) \
217 .setdefault(m, []).append(filename)
218 self._total_diffs += 1
219 self._missing_gyp_files.setdefault(filename, {}) \
220 .setdefault(name, set()).update(missing_in_gyp)
221
222 for m in missing_in_gn:
223 self._missing_gn_flags.setdefault(name, {}) \
224 .setdefault(m, []).append(filename)
225 self._total_diffs += 1
226 self._missing_gn_files.setdefault(filename, {}) \
227 .setdefault(name, set()).update(missing_in_gn)
228
229 def _GetFlags(self, lines, build_dir):
230 """Turn a list of command lines into a semi-structured dict."""
231 is_win = sys.platform == 'win32'
232 flags_by_output = {}
233 for line in lines:
234 command_line = shlex.split(line.strip(), posix=not is_win)[1:]
235
236 output_name = _FindAndRemoveArgWithValue(command_line, '-o')
237 dep_name = _FindAndRemoveArgWithValue(command_line, '-MF')
238
239 command_line = _MergeSpacedArgs(command_line, '-Xclang')
240
241 cc_file = [x for x in command_line if x.endswith('.cc') or
242 x.endswith('.c') or
243 x.endswith('.cpp') or
244 x.endswith('.mm') or
245 x.endswith('.m')]
246 if len(cc_file) != 1:
247 self._skipped.append(command_line)
248 continue
249 assert len(cc_file) == 1
250
251 if is_win:
252 rsp_file = [x for x in command_line if x.endswith('.rsp')]
253 assert len(rsp_file) <= 1
254 if rsp_file:
255 rsp_file = os.path.join(build_dir, rsp_file[0][1:])
256 with open(rsp_file, "r") as open_rsp_file:
257 command_line = shlex.split(open_rsp_file, posix=False)
258
259 defines = [x for x in command_line if x.startswith('-D')]
260 include_dirs = [x for x in command_line if x.startswith('-I')]
261 dash_f = [x for x in command_line if x.startswith('-f')]
262 warnings = \
263 [x for x in command_line if x.startswith('/wd' if is_win else '-W')]
264 others = [x for x in command_line if x not in defines and \
265 x not in include_dirs and \
266 x not in dash_f and \
267 x not in warnings and \
268 x not in cc_file]
269
270 for index, value in enumerate(include_dirs):
271 if value == '-Igen':
272 continue
273 path = value[2:]
274 if not os.path.isabs(path):
275 path = os.path.join(build_dir, path)
276 include_dirs[index] = '-I' + os.path.normpath(path)
277
278 # GYP supports paths above the source root like <(DEPTH)/../foo while such
279 # paths are unsupported by gn. But gn allows to use system-absolute paths
280 # instead (paths that start with single '/'). Normalize all paths.
281 cc_file = [os.path.normpath(os.path.join(build_dir, cc_file[0]))]
282
283 # Filter for libFindBadConstructs.so having a relative path in one and
284 # absolute path in the other.
285 others_filtered = []
286 for x in others:
287 if x.startswith('-Xclang ') and \
288 (x.endswith('libFindBadConstructs.so') or \
289 x.endswith('libFindBadConstructs.dylib')):
290 others_filtered.append(
291 '-Xclang ' +
292 os.path.join(os.getcwd(), os.path.normpath(
293 os.path.join('out/gn_flags', x.split(' ', 1)[1]))))
294 elif x.startswith('-B'):
295 others_filtered.append(
296 '-B' +
297 os.path.join(os.getcwd(), os.path.normpath(
298 os.path.join('out/gn_flags', x[2:]))))
299 else:
300 others_filtered.append(x)
301 others = others_filtered
302
303 flags_by_output[cc_file[0]] = {
304 'output': output_name,
305 'depname': dep_name,
306 'defines': sorted(defines),
307 'include_dirs': sorted(include_dirs), # TODO(scottmg): This is wrong.
308 'dash_f': sorted(dash_f),
309 'warnings': sorted(warnings),
310 'other': sorted(others),
311 }
312 return flags_by_output
313
314
315 def _FindAndRemoveArgWithValue(command_line, argname):
316 """Given a command line as a list, remove and return the value of an option
317 that takes a value as a separate entry.
318
319 Modifies |command_line| in place.
320 """
321 if argname not in command_line:
322 return ''
323 location = command_line.index(argname)
324 value = command_line[location + 1]
325 command_line[location:location + 2] = []
326 return value
327
328
329 def _MergeSpacedArgs(command_line, argname):
330 """Combine all arguments |argname| with their values, separated by a space."""
331 i = 0
332 result = []
333 while i < len(command_line):
334 arg = command_line[i]
335 if arg == argname:
336 result.append(arg + ' ' + command_line[i + 1])
337 i += 1
338 else:
339 result.append(arg)
340 i += 1
341 return result
342
343
344 def Run(command_line):
345 """Run |command_line| as a subprocess and return stdout. Raises on error."""
346 print >> sys.stderr, command_line
347 return subprocess.check_output(command_line, shell=True)
348
349
350 def main():
351 if len(sys.argv) != 2 and len(sys.argv) != 3:
352 print 'usage: %s gyp_target gn_target' % __file__
353 print ' or: %s target' % __file__
354 return 1
355
356 gyp_target = sys.argv[1]
357 if len(sys.argv) == 2:
358 gn_target = gyp_target
359 else:
360 gn_target = sys.argv[2]
361 comparison = Comparison(gyp_target, gn_target)
362
363 gyp_files = comparison.gyp_files
364 gn_files = comparison.gn_files
365 different_source_list = comparison.gyp_files != comparison.gn_files
366 if different_source_list:
367 print 'Different set of sources files:'
368 print ' In gyp, not in GN:\n %s' % '\n '.join(
369 sorted(gyp_files - gn_files))
370 print ' In GN, not in gyp:\n %s' % '\n '.join(
371 sorted(gn_files - gyp_files))
372 print '\nNote that flags will only be compared for files in both sets.\n'
373
374 differing_files = set(comparison.missing_in_gn_by_file.keys()) & \
375 set(comparison.missing_in_gyp_by_file.keys())
376 files_with_given_differences = {}
377 for filename in differing_files:
378 output = ''
379 missing_in_gyp = comparison.missing_in_gyp_by_file.get(filename, {})
380 missing_in_gn = comparison.missing_in_gn_by_file.get(filename, {})
381 difference_types = sorted(set(missing_in_gyp.keys() + missing_in_gn.keys()))
382 for difference_type in difference_types:
383 output += ' %s differ:\n' % difference_type
384 if difference_type in missing_in_gyp:
385 output += ' In gyp, but not in GN:\n %s' % '\n '.join(
386 sorted(missing_in_gyp[difference_type])) + '\n'
387 if difference_type in missing_in_gn:
388 output += ' In GN, but not in gyp:\n %s' % '\n '.join(
389 sorted(missing_in_gn[difference_type])) + '\n'
390 if output:
391 files_with_given_differences.setdefault(output, []).append(filename)
392
393 for diff, files in files_with_given_differences.iteritems():
394 print '\n'.join(sorted(files))
395 print diff
396
397 print 'Total differences:', comparison.total_differences
398 # TODO(scottmg): Return failure on difference once we're closer to identical.
399 return 0
400
401
402 if __name__ == '__main__':
403 sys.exit(main())
OLDNEW
« no previous file with comments | « no previous file | no next file » | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698