blob: 8cb7e39c9c9c40b22936e9a7b29c341e532a9b40 [file] [log] [blame]
Sami Kyostila865d1d32017-12-12 18:37:04 +00001#!/usr/bin/env python
2# Copyright (C) 2017 The Android Open Source Project
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15
16# This tool translates a collection of BUILD.gn files into a mostly equivalent
17# Android.bp file for the Android Soong build system. The input to the tool is a
18# JSON description of the GN build definition generated with the following
19# command:
20#
21# gn desc out --format=json --all-toolchains "//*" > desc.json
22#
23# The tool is then given a list of GN labels for which to generate Android.bp
24# build rules. The dependencies for the GN labels are squashed to the generated
25# Android.bp target, except for actions which get their own genrule. Some
26# libraries are also mapped to their Android equivalents -- see |builtin_deps|.
27
28import argparse
Primiano Tucciedf099c2018-01-08 18:27:56 +000029import errno
Sami Kyostila865d1d32017-12-12 18:37:04 +000030import json
31import os
32import re
Sami Kyostilab27619f2017-12-13 19:22:16 +000033import shutil
34import subprocess
Sami Kyostila865d1d32017-12-12 18:37:04 +000035import sys
36
Sami Kyostilab27619f2017-12-13 19:22:16 +000037# Default targets to translate to the blueprint file.
Primiano Tucci4e49c022017-12-21 18:22:44 +010038default_targets = [
Primiano Tucciedf099c2018-01-08 18:27:56 +000039 '//:libtraced_shared',
Lalit Maganti79f2d7b2018-01-23 18:27:33 +000040 '//:perfetto_integrationtests',
41 '//:perfetto_unittests',
Primiano Tucci3b729102018-01-08 18:16:36 +000042 '//:perfetto',
Primiano Tucci4e49c022017-12-21 18:22:44 +010043 '//:traced',
Primiano Tucci6067e732018-01-08 16:19:40 +000044 '//:traced_probes',
Primiano Tucci4e49c022017-12-21 18:22:44 +010045]
Sami Kyostilab27619f2017-12-13 19:22:16 +000046
Primiano Tucci6067e732018-01-08 16:19:40 +000047# Defines a custom init_rc argument to be applied to the corresponding output
48# blueprint target.
Primiano Tucci5a304532018-01-09 14:15:43 +000049target_initrc = {
50 '//:traced': 'perfetto.rc',
51}
Primiano Tucci6067e732018-01-08 16:19:40 +000052
Sami Kyostilab27619f2017-12-13 19:22:16 +000053# Arguments for the GN output directory.
Primiano Tucciedf099c2018-01-08 18:27:56 +000054gn_args = 'target_os="android" target_cpu="arm" is_debug=false build_with_android=true'
Sami Kyostilab27619f2017-12-13 19:22:16 +000055
Sami Kyostila865d1d32017-12-12 18:37:04 +000056# All module names are prefixed with this string to avoid collisions.
57module_prefix = 'perfetto_'
58
59# Shared libraries which are directly translated to Android system equivalents.
60library_whitelist = [
61 'android',
Sami Kyostilab5b71692018-01-12 12:16:44 +000062 'binder',
Sami Kyostila865d1d32017-12-12 18:37:04 +000063 'log',
Sami Kyostilab5b71692018-01-12 12:16:44 +000064 'services',
Primiano Tucciedf099c2018-01-08 18:27:56 +000065 'utils',
Sami Kyostila865d1d32017-12-12 18:37:04 +000066]
67
68# Name of the module which settings such as compiler flags for all other
69# modules.
70defaults_module = module_prefix + 'defaults'
71
72# Location of the project in the Android source tree.
73tree_path = 'external/perfetto'
74
Primiano Tucciedf099c2018-01-08 18:27:56 +000075# Compiler flags which are passed through to the blueprint.
76cflag_whitelist = r'^-DPERFETTO.*$'
77
Florian Mayer3d5e7e62018-01-19 15:22:46 +000078# Compiler defines which are passed through to the blueprint.
79define_whitelist = r'^GOOGLE_PROTO.*$'
80
Sami Kyostila865d1d32017-12-12 18:37:04 +000081
82def enable_gmock(module):
83 module.static_libs.append('libgmock')
84
85
Hector Dearman3e712a02017-12-19 16:39:59 +000086def enable_gtest_prod(module):
87 module.static_libs.append('libgtest_prod')
88
89
Sami Kyostila865d1d32017-12-12 18:37:04 +000090def enable_gtest(module):
91 assert module.type == 'cc_test'
92
93
94def enable_protobuf_full(module):
95 module.shared_libs.append('libprotobuf-cpp-full')
96
97
98def enable_protobuf_lite(module):
99 module.shared_libs.append('libprotobuf-cpp-lite')
100
101
102def enable_protoc_lib(module):
103 module.shared_libs.append('libprotoc')
104
105
106def enable_libunwind(module):
Sami Kyostilafc074d42017-12-15 10:33:42 +0000107 # libunwind is disabled on Darwin so we cannot depend on it.
108 pass
Sami Kyostila865d1d32017-12-12 18:37:04 +0000109
110
111# Android equivalents for third-party libraries that the upstream project
112# depends on.
113builtin_deps = {
114 '//buildtools:gmock': enable_gmock,
115 '//buildtools:gtest': enable_gtest,
Hector Dearman3e712a02017-12-19 16:39:59 +0000116 '//gn:gtest_prod_config': enable_gtest_prod,
Sami Kyostila865d1d32017-12-12 18:37:04 +0000117 '//buildtools:gtest_main': enable_gtest,
118 '//buildtools:libunwind': enable_libunwind,
119 '//buildtools:protobuf_full': enable_protobuf_full,
120 '//buildtools:protobuf_lite': enable_protobuf_lite,
121 '//buildtools:protoc_lib': enable_protoc_lib,
122}
123
124# ----------------------------------------------------------------------------
125# End of configuration.
126# ----------------------------------------------------------------------------
127
128
129class Error(Exception):
130 pass
131
132
133class ThrowingArgumentParser(argparse.ArgumentParser):
134 def __init__(self, context):
135 super(ThrowingArgumentParser, self).__init__()
136 self.context = context
137
138 def error(self, message):
139 raise Error('%s: %s' % (self.context, message))
140
141
142class Module(object):
143 """A single module (e.g., cc_binary, cc_test) in a blueprint."""
144
145 def __init__(self, mod_type, name):
146 self.type = mod_type
147 self.name = name
148 self.srcs = []
149 self.comment = None
150 self.shared_libs = []
151 self.static_libs = []
152 self.tools = []
153 self.cmd = None
Primiano Tucci6067e732018-01-08 16:19:40 +0000154 self.init_rc = []
Sami Kyostila865d1d32017-12-12 18:37:04 +0000155 self.out = []
156 self.export_include_dirs = []
157 self.generated_headers = []
Lalit Magantic5bcd792018-01-12 18:38:11 +0000158 self.export_generated_headers = []
Sami Kyostila865d1d32017-12-12 18:37:04 +0000159 self.defaults = []
Florian Mayer3d5e7e62018-01-19 15:22:46 +0000160 self.cflags = set()
Sami Kyostila865d1d32017-12-12 18:37:04 +0000161 self.local_include_dirs = []
162
163 def to_string(self, output):
164 if self.comment:
165 output.append('// %s' % self.comment)
166 output.append('%s {' % self.type)
167 self._output_field(output, 'name')
168 self._output_field(output, 'srcs')
169 self._output_field(output, 'shared_libs')
170 self._output_field(output, 'static_libs')
171 self._output_field(output, 'tools')
172 self._output_field(output, 'cmd', sort=False)
Primiano Tucci6067e732018-01-08 16:19:40 +0000173 self._output_field(output, 'init_rc')
Sami Kyostila865d1d32017-12-12 18:37:04 +0000174 self._output_field(output, 'out')
175 self._output_field(output, 'export_include_dirs')
176 self._output_field(output, 'generated_headers')
Lalit Magantic5bcd792018-01-12 18:38:11 +0000177 self._output_field(output, 'export_generated_headers')
Sami Kyostila865d1d32017-12-12 18:37:04 +0000178 self._output_field(output, 'defaults')
179 self._output_field(output, 'cflags')
180 self._output_field(output, 'local_include_dirs')
181 output.append('}')
182 output.append('')
183
184 def _output_field(self, output, name, sort=True):
185 value = getattr(self, name)
186 if not value:
187 return
Florian Mayer3d5e7e62018-01-19 15:22:46 +0000188 if isinstance(value, set):
189 value = sorted(value)
Sami Kyostila865d1d32017-12-12 18:37:04 +0000190 if isinstance(value, list):
191 output.append(' %s: [' % name)
192 for item in sorted(value) if sort else value:
193 output.append(' "%s",' % item)
194 output.append(' ],')
195 else:
196 output.append(' %s: "%s",' % (name, value))
197
198
199class Blueprint(object):
200 """In-memory representation of an Android.bp file."""
201
202 def __init__(self):
203 self.modules = {}
204
205 def add_module(self, module):
206 """Adds a new module to the blueprint, replacing any existing module
207 with the same name.
208
209 Args:
210 module: Module instance.
211 """
212 self.modules[module.name] = module
213
214 def to_string(self, output):
Sami Kyostilaebba0fe2017-12-19 14:01:52 +0000215 for m in sorted(self.modules.itervalues(), key=lambda m: m.name):
Sami Kyostila865d1d32017-12-12 18:37:04 +0000216 m.to_string(output)
217
218
219def label_to_path(label):
220 """Turn a GN output label (e.g., //some_dir/file.cc) into a path."""
221 assert label.startswith('//')
222 return label[2:]
223
224
225def label_to_module_name(label):
226 """Turn a GN label (e.g., //:perfetto_tests) into a module name."""
Primiano Tucci4e49c022017-12-21 18:22:44 +0100227 module = re.sub(r'^//:?', '', label)
228 module = re.sub(r'[^a-zA-Z0-9_]', '_', module)
229 if not module.startswith(module_prefix) and label not in default_targets:
Sami Kyostila865d1d32017-12-12 18:37:04 +0000230 return module_prefix + module
231 return module
232
233
234def label_without_toolchain(label):
235 """Strips the toolchain from a GN label.
236
237 Return a GN label (e.g //buildtools:protobuf(//gn/standalone/toolchain:
238 gcc_like_host) without the parenthesised toolchain part.
239 """
240 return label.split('(')[0]
241
242
243def is_supported_source_file(name):
244 """Returns True if |name| can appear in a 'srcs' list."""
245 return os.path.splitext(name)[1] in ['.c', '.cc', '.proto']
246
247
248def is_generated_by_action(desc, label):
249 """Checks if a label is generated by an action.
250
251 Returns True if a GN output label |label| is an output for any action,
252 i.e., the file is generated dynamically.
253 """
254 for target in desc.itervalues():
255 if target['type'] == 'action' and label in target['outputs']:
256 return True
257 return False
258
259
260def apply_module_dependency(blueprint, desc, module, dep_name):
261 """Recursively collect dependencies for a given module.
262
263 Walk the transitive dependencies for a GN target and apply them to a given
264 module. This effectively flattens the dependency tree so that |module|
265 directly contains all the sources, libraries, etc. in the corresponding GN
266 dependency tree.
267
268 Args:
269 blueprint: Blueprint instance which is being generated.
270 desc: JSON GN description.
271 module: Module to which dependencies should be added.
272 dep_name: GN target of the dependency.
273 """
Sami Kyostila865d1d32017-12-12 18:37:04 +0000274 # If the dependency refers to a library which we can replace with an Android
275 # equivalent, stop recursing and patch the dependency in.
276 if label_without_toolchain(dep_name) in builtin_deps:
277 builtin_deps[label_without_toolchain(dep_name)](module)
278 return
279
280 # Similarly some shared libraries are directly mapped to Android
281 # equivalents.
282 target = desc[dep_name]
283 for lib in target.get('libs', []):
284 android_lib = 'lib' + lib
285 if lib in library_whitelist and not android_lib in module.shared_libs:
286 module.shared_libs.append(android_lib)
287
288 type = target['type']
289 if type == 'action':
290 create_modules_from_target(blueprint, desc, dep_name)
291 # Depend both on the generated sources and headers -- see
292 # make_genrules_for_action.
293 module.srcs.append(':' + label_to_module_name(dep_name))
294 module.generated_headers.append(
295 label_to_module_name(dep_name) + '_headers')
Sami Kyostilaebba0fe2017-12-19 14:01:52 +0000296 elif type == 'static_library' and label_to_module_name(
297 dep_name) != module.name:
298 create_modules_from_target(blueprint, desc, dep_name)
299 module.static_libs.append(label_to_module_name(dep_name))
Primiano Tucci6067e732018-01-08 16:19:40 +0000300 elif type == 'shared_library' and label_to_module_name(
301 dep_name) != module.name:
302 module.shared_libs.append(label_to_module_name(dep_name))
Sami Kyostilaebba0fe2017-12-19 14:01:52 +0000303 elif type in ['group', 'source_set', 'executable', 'static_library'
304 ] and 'sources' in target:
Sami Kyostila865d1d32017-12-12 18:37:04 +0000305 # Ignore source files that are generated by actions since they will be
306 # implicitly added by the genrule dependencies.
307 module.srcs.extend(
308 label_to_path(src) for src in target['sources']
309 if is_supported_source_file(src)
310 and not is_generated_by_action(desc, src))
Florian Mayer3d5e7e62018-01-19 15:22:46 +0000311 module.cflags |= _get_cflags(target)
Sami Kyostila865d1d32017-12-12 18:37:04 +0000312
313
314def make_genrules_for_action(blueprint, desc, target_name):
315 """Generate genrules for a GN action.
316
317 GN actions are used to dynamically generate files during the build. The
318 Soong equivalent is a genrule. This function turns a specific kind of
319 genrule which turns .proto files into source and header files into a pair
Sami Kyostila71625d72017-12-18 10:29:49 +0000320 equivalent genrules.
Sami Kyostila865d1d32017-12-12 18:37:04 +0000321
322 Args:
323 blueprint: Blueprint instance which is being generated.
324 desc: JSON GN description.
325 target_name: GN target for genrule generation.
326
327 Returns:
328 A (source_genrule, header_genrule) module tuple.
329 """
330 target = desc[target_name]
331
332 # We only support genrules which call protoc (with or without a plugin) to
333 # turn .proto files into header and source files.
334 args = target['args']
335 if not args[0].endswith('/protoc'):
336 raise Error('Unsupported action in target %s: %s' % (target_name,
337 target['args']))
Primiano Tucci20b760c2018-01-19 12:36:12 +0000338 parser = ThrowingArgumentParser('Action in target %s (%s)' %
339 (target_name, ' '.join(target['args'])))
340 parser.add_argument('--proto_path')
341 parser.add_argument('--cpp_out')
342 parser.add_argument('--plugin')
343 parser.add_argument('--plugin_out')
344 parser.add_argument('protos', nargs=argparse.REMAINDER)
345 args = parser.parse_args(args[1:])
346
347 # Depending on whether we are using the default protoc C++ generator or the
348 # protozero plugin, the output dir is passed as:
349 # --cpp_out=gen/xxx or
350 # --plugin_out=:gen/xxx or
351 # --plugin_out=wrapper_namespace=pbzero:gen/xxx
352 gen_dir = args.cpp_out if args.cpp_out else args.plugin_out.split(':')[1]
353 assert gen_dir.startswith('gen/')
354 gen_dir = gen_dir[4:]
355 cpp_out_dir = ('$(genDir)/%s/%s' % (tree_path, gen_dir)).rstrip('/')
356
357 # TODO(skyostil): Is there a way to avoid hardcoding the tree path here?
358 # TODO(skyostil): Find a way to avoid creating the directory.
359 cmd = [
360 'mkdir -p %s &&' % cpp_out_dir,
361 '$(location aprotoc)',
362 '--cpp_out=%s' % cpp_out_dir
363 ]
Sami Kyostila865d1d32017-12-12 18:37:04 +0000364
365 # We create two genrules for each action: one for the protobuf headers and
366 # another for the sources. This is because the module that depends on the
367 # generated files needs to declare two different types of dependencies --
368 # source files in 'srcs' and headers in 'generated_headers' -- and it's not
369 # valid to generate .h files from a source dependency and vice versa.
Sami Kyostila71625d72017-12-18 10:29:49 +0000370 source_module = Module('genrule', label_to_module_name(target_name))
Sami Kyostila865d1d32017-12-12 18:37:04 +0000371 source_module.srcs.extend(label_to_path(src) for src in target['sources'])
372 source_module.tools = ['aprotoc']
373
Sami Kyostila71625d72017-12-18 10:29:49 +0000374 header_module = Module('genrule',
Sami Kyostila865d1d32017-12-12 18:37:04 +0000375 label_to_module_name(target_name) + '_headers')
376 header_module.srcs = source_module.srcs[:]
377 header_module.tools = source_module.tools[:]
Primiano Tucci20b760c2018-01-19 12:36:12 +0000378 header_module.export_include_dirs = [gen_dir or '.']
Sami Kyostila865d1d32017-12-12 18:37:04 +0000379
Primiano Tucci20b760c2018-01-19 12:36:12 +0000380 # In GN builds the proto path is always relative to the output directory
381 # (out/tmp.xxx).
382 assert args.proto_path.startswith('../../')
383 cmd += [ '--proto_path=%s/%s' % (tree_path, args.proto_path[6:])]
384
Sami Kyostila865d1d32017-12-12 18:37:04 +0000385 namespaces = ['pb']
Sami Kyostila865d1d32017-12-12 18:37:04 +0000386 if args.plugin:
387 _, plugin = os.path.split(args.plugin)
388 # TODO(skyostil): Can we detect this some other way?
389 if plugin == 'ipc_plugin':
390 namespaces.append('ipc')
391 elif plugin == 'protoc_plugin':
392 namespaces = ['pbzero']
393 for dep in target['deps']:
394 if desc[dep]['type'] != 'executable':
395 continue
396 _, executable = os.path.split(desc[dep]['outputs'][0])
397 if executable == plugin:
398 cmd += [
399 '--plugin=protoc-gen-plugin=$(location %s)' %
400 label_to_module_name(dep)
401 ]
402 source_module.tools.append(label_to_module_name(dep))
403 # Also make sure the module for the tool is generated.
404 create_modules_from_target(blueprint, desc, dep)
405 break
406 else:
407 raise Error('Unrecognized protoc plugin in target %s: %s' %
408 (target_name, args[i]))
409 if args.plugin_out:
410 plugin_args = args.plugin_out.split(':')[0]
Primiano Tucci20b760c2018-01-19 12:36:12 +0000411 cmd += ['--plugin_out=%s:%s' % (plugin_args, cpp_out_dir)]
Sami Kyostila865d1d32017-12-12 18:37:04 +0000412
413 cmd += ['$(in)']
414 source_module.cmd = ' '.join(cmd)
415 header_module.cmd = source_module.cmd
416 header_module.tools = source_module.tools[:]
417
418 for ns in namespaces:
419 source_module.out += [
420 '%s/%s' % (tree_path, src.replace('.proto', '.%s.cc' % ns))
421 for src in source_module.srcs
422 ]
423 header_module.out += [
424 '%s/%s' % (tree_path, src.replace('.proto', '.%s.h' % ns))
425 for src in header_module.srcs
426 ]
427 return source_module, header_module
428
429
Florian Mayer3d5e7e62018-01-19 15:22:46 +0000430def _get_cflags(target):
431 cflags = set(flag for flag in target.get('cflags', [])
432 if re.match(cflag_whitelist, flag))
433 cflags |= set("-D%s" % define for define in target.get('defines', [])
434 if re.match(define_whitelist, define))
435 return cflags
436
437
Sami Kyostila865d1d32017-12-12 18:37:04 +0000438def create_modules_from_target(blueprint, desc, target_name):
439 """Generate module(s) for a given GN target.
440
441 Given a GN target name, generate one or more corresponding modules into a
442 blueprint.
443
444 Args:
445 blueprint: Blueprint instance which is being generated.
446 desc: JSON GN description.
447 target_name: GN target for module generation.
448 """
449 target = desc[target_name]
450 if target['type'] == 'executable':
451 if 'host' in target['toolchain']:
452 module_type = 'cc_binary_host'
453 elif target.get('testonly'):
454 module_type = 'cc_test'
455 else:
456 module_type = 'cc_binary'
457 modules = [Module(module_type, label_to_module_name(target_name))]
458 elif target['type'] == 'action':
459 modules = make_genrules_for_action(blueprint, desc, target_name)
Sami Kyostilaebba0fe2017-12-19 14:01:52 +0000460 elif target['type'] == 'static_library':
Lalit Magantic5bcd792018-01-12 18:38:11 +0000461 module = Module('cc_library_static', label_to_module_name(target_name))
462 module.export_include_dirs = ['include']
463 modules = [module]
Primiano Tucci6067e732018-01-08 16:19:40 +0000464 elif target['type'] == 'shared_library':
465 modules = [
466 Module('cc_library_shared', label_to_module_name(target_name))
467 ]
Sami Kyostila865d1d32017-12-12 18:37:04 +0000468 else:
469 raise Error('Unknown target type: %s' % target['type'])
470
471 for module in modules:
472 module.comment = 'GN target: %s' % target_name
Primiano Tucci6067e732018-01-08 16:19:40 +0000473 if target_name in target_initrc:
474 module.init_rc = [target_initrc[target_name]]
475
Sami Kyostilaebba0fe2017-12-19 14:01:52 +0000476 # Don't try to inject library/source dependencies into genrules because
477 # they are not compiled in the traditional sense.
Sami Kyostila71625d72017-12-18 10:29:49 +0000478 if module.type != 'genrule':
Sami Kyostila865d1d32017-12-12 18:37:04 +0000479 module.defaults = [defaults_module]
Sami Kyostilaebba0fe2017-12-19 14:01:52 +0000480 apply_module_dependency(blueprint, desc, module, target_name)
481 for dep in resolve_dependencies(desc, target_name):
482 apply_module_dependency(blueprint, desc, module, dep)
Sami Kyostila865d1d32017-12-12 18:37:04 +0000483
Lalit Magantic5bcd792018-01-12 18:38:11 +0000484 # If the module is a static library, export all the generated headers.
485 if module.type == 'cc_library_static':
486 module.export_generated_headers = module.generated_headers
487
Sami Kyostila865d1d32017-12-12 18:37:04 +0000488 blueprint.add_module(module)
489
490
491def resolve_dependencies(desc, target_name):
492 """Return the transitive set of dependent-on targets for a GN target.
493
494 Args:
495 blueprint: Blueprint instance which is being generated.
496 desc: JSON GN description.
497
498 Returns:
499 A set of transitive dependencies in the form of GN targets.
500 """
501
502 if label_without_toolchain(target_name) in builtin_deps:
503 return set()
504 target = desc[target_name]
505 resolved_deps = set()
506 for dep in target.get('deps', []):
507 resolved_deps.add(dep)
508 # Ignore the transitive dependencies of actions because they are
509 # explicitly converted to genrules.
510 if desc[dep]['type'] == 'action':
511 continue
Primiano Tucci6067e732018-01-08 16:19:40 +0000512 # Dependencies on shared libraries shouldn't propagate any transitive
513 # dependencies but only depend on the shared library target
514 if desc[dep]['type'] == 'shared_library':
515 continue
Sami Kyostila865d1d32017-12-12 18:37:04 +0000516 resolved_deps.update(resolve_dependencies(desc, dep))
517 return resolved_deps
518
519
520def create_blueprint_for_targets(desc, targets):
521 """Generate a blueprint for a list of GN targets."""
522 blueprint = Blueprint()
523
524 # Default settings used by all modules.
525 defaults = Module('cc_defaults', defaults_module)
526 defaults.local_include_dirs = ['include']
527 defaults.cflags = [
528 '-Wno-error=return-type',
529 '-Wno-sign-compare',
530 '-Wno-sign-promo',
531 '-Wno-unused-parameter',
Florian Mayercc424fd2018-01-15 11:19:01 +0000532 '-fvisibility=hidden',
Florian Mayerc2a38ea2018-01-19 11:48:43 +0000533 '-Oz',
Sami Kyostila865d1d32017-12-12 18:37:04 +0000534 ]
535
536 blueprint.add_module(defaults)
537 for target in targets:
538 create_modules_from_target(blueprint, desc, target)
539 return blueprint
540
541
Sami Kyostilab27619f2017-12-13 19:22:16 +0000542def repo_root():
543 """Returns an absolute path to the repository root."""
544
545 return os.path.join(
546 os.path.realpath(os.path.dirname(__file__)), os.path.pardir)
547
548
549def create_build_description():
550 """Creates the JSON build description by running GN."""
551
552 out = os.path.join(repo_root(), 'out', 'tmp.gen_android_bp')
553 try:
554 try:
555 os.makedirs(out)
556 except OSError as e:
557 if e.errno != errno.EEXIST:
558 raise
559 subprocess.check_output(
560 ['gn', 'gen', out, '--args=%s' % gn_args], cwd=repo_root())
561 desc = subprocess.check_output(
562 ['gn', 'desc', out, '--format=json', '--all-toolchains', '//*'],
563 cwd=repo_root())
564 return json.loads(desc)
565 finally:
566 shutil.rmtree(out)
567
568
Sami Kyostila865d1d32017-12-12 18:37:04 +0000569def main():
570 parser = argparse.ArgumentParser(
571 description='Generate Android.bp from a GN description.')
572 parser.add_argument(
Sami Kyostilab27619f2017-12-13 19:22:16 +0000573 '--desc',
Sami Kyostila865d1d32017-12-12 18:37:04 +0000574 help=
575 'GN description (e.g., gn desc out --format=json --all-toolchains "//*"'
576 )
577 parser.add_argument(
Lalit Magantic5bcd792018-01-12 18:38:11 +0000578 '--extras',
579 help='Extra targets to include at the end of the Blueprint file',
580 default=os.path.join(repo_root(), 'Android.bp.extras'),
581 )
582 parser.add_argument(
Sami Kyostilab27619f2017-12-13 19:22:16 +0000583 '--output',
584 help='Blueprint file to create',
585 default=os.path.join(repo_root(), 'Android.bp'),
586 )
587 parser.add_argument(
Sami Kyostila865d1d32017-12-12 18:37:04 +0000588 'targets',
589 nargs=argparse.REMAINDER,
590 help='Targets to include in the blueprint (e.g., "//:perfetto_tests")')
591 args = parser.parse_args()
592
Sami Kyostilab27619f2017-12-13 19:22:16 +0000593 if args.desc:
594 with open(args.desc) as f:
595 desc = json.load(f)
596 else:
597 desc = create_build_description()
Sami Kyostila865d1d32017-12-12 18:37:04 +0000598
Sami Kyostilab27619f2017-12-13 19:22:16 +0000599 blueprint = create_blueprint_for_targets(desc, args.targets
600 or default_targets)
Sami Kyostila865d1d32017-12-12 18:37:04 +0000601 output = [
602 """// Copyright (C) 2017 The Android Open Source Project
603//
604// Licensed under the Apache License, Version 2.0 (the "License");
605// you may not use this file except in compliance with the License.
606// You may obtain a copy of the License at
607//
608// http://www.apache.org/licenses/LICENSE-2.0
609//
610// Unless required by applicable law or agreed to in writing, software
611// distributed under the License is distributed on an "AS IS" BASIS,
612// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
613// See the License for the specific language governing permissions and
614// limitations under the License.
615//
616// This file is automatically generated by %s. Do not edit.
617""" % (__file__)
618 ]
619 blueprint.to_string(output)
Lalit Magantic5bcd792018-01-12 18:38:11 +0000620 with open(args.extras, 'r') as r:
621 for line in r:
622 output.append(line.rstrip("\n\r"))
Sami Kyostilab27619f2017-12-13 19:22:16 +0000623 with open(args.output, 'w') as f:
624 f.write('\n'.join(output))
Sami Kyostila865d1d32017-12-12 18:37:04 +0000625
626
627if __name__ == '__main__':
628 sys.exit(main())