generate_gradle.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914
  1. #!/usr/bin/env vpython3
  2. # Copyright 2016 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. """Generates an Android Studio project from a GN target."""
  6. import argparse
  7. import codecs
  8. import collections
  9. import glob
  10. import json
  11. import logging
  12. import os
  13. import re
  14. import shutil
  15. import subprocess
  16. import sys
  17. _BUILD_ANDROID = os.path.join(os.path.dirname(__file__), os.pardir)
  18. sys.path.append(_BUILD_ANDROID)
  19. import devil_chromium
  20. from devil.utils import run_tests_helper
  21. from pylib import constants
  22. from pylib.constants import host_paths
  23. sys.path.append(os.path.join(_BUILD_ANDROID, 'gyp'))
  24. import jinja_template
  25. from util import build_utils
  26. from util import resource_utils
  27. sys.path.append(os.path.dirname(_BUILD_ANDROID))
  28. import gn_helpers
  29. _DEPOT_TOOLS_PATH = os.path.join(host_paths.DIR_SOURCE_ROOT, 'third_party',
  30. 'depot_tools')
  31. _DEFAULT_ANDROID_MANIFEST_PATH = os.path.join(
  32. host_paths.DIR_SOURCE_ROOT, 'build', 'android', 'gradle',
  33. 'AndroidManifest.xml')
  34. _FILE_DIR = os.path.dirname(__file__)
  35. _GENERATED_JAVA_SUBDIR = 'generated_java'
  36. _JNI_LIBS_SUBDIR = 'symlinked-libs'
  37. _ARMEABI_SUBDIR = 'armeabi'
  38. _GRADLE_BUILD_FILE = 'build.gradle'
  39. _CMAKE_FILE = 'CMakeLists.txt'
  40. # This needs to come first alphabetically among all modules.
  41. _MODULE_ALL = '_all'
  42. _SRC_INTERNAL = os.path.join(
  43. os.path.dirname(host_paths.DIR_SOURCE_ROOT), 'src-internal')
  44. _INSTRUMENTATION_TARGET_SUFFIX = '_test_apk__test_apk__apk'
  45. _DEFAULT_TARGETS = [
  46. '//android_webview/test/embedded_test_server:aw_net_test_support_apk',
  47. '//android_webview/test:webview_instrumentation_apk',
  48. '//android_webview/test:webview_instrumentation_test_apk',
  49. '//base:base_junit_tests',
  50. '//chrome/android:chrome_junit_tests',
  51. '//chrome/android:chrome_public_apk',
  52. '//chrome/android:chrome_public_test_apk',
  53. '//chrome/android:chrome_public_unit_test_apk',
  54. '//content/public/android:content_junit_tests',
  55. '//content/shell/android:content_shell_apk',
  56. # Below must be included even with --all since they are libraries.
  57. '//base/android/jni_generator:jni_processor',
  58. '//tools/android/errorprone_plugin:errorprone_plugin_java',
  59. ]
  60. def _TemplatePath(name):
  61. return os.path.join(_FILE_DIR, '{}.jinja'.format(name))
  62. def _RebasePath(path_or_list, new_cwd=None, old_cwd=None):
  63. """Makes the given path(s) relative to new_cwd, or absolute if not specified.
  64. If new_cwd is not specified, absolute paths are returned.
  65. If old_cwd is not specified, constants.GetOutDirectory() is assumed.
  66. """
  67. if path_or_list is None:
  68. return []
  69. if not isinstance(path_or_list, str):
  70. return [_RebasePath(p, new_cwd, old_cwd) for p in path_or_list]
  71. if old_cwd is None:
  72. old_cwd = constants.GetOutDirectory()
  73. old_cwd = os.path.abspath(old_cwd)
  74. if new_cwd:
  75. new_cwd = os.path.abspath(new_cwd)
  76. return os.path.relpath(os.path.join(old_cwd, path_or_list), new_cwd)
  77. return os.path.abspath(os.path.join(old_cwd, path_or_list))
  78. def _IsSubpathOf(child, parent):
  79. """Returns whether |child| is a subpath of |parent|."""
  80. return not os.path.relpath(child, parent).startswith(os.pardir)
  81. def _WriteFile(path, data):
  82. """Writes |data| to |path|, constucting parent directories if necessary."""
  83. logging.info('Writing %s', path)
  84. dirname = os.path.dirname(path)
  85. if not os.path.exists(dirname):
  86. os.makedirs(dirname)
  87. with codecs.open(path, 'w', 'utf-8') as output_file:
  88. output_file.write(data)
  89. def _RunGnGen(output_dir, args=None):
  90. cmd = [os.path.join(_DEPOT_TOOLS_PATH, 'gn'), 'gen', output_dir]
  91. if args:
  92. cmd.extend(args)
  93. logging.info('Running: %r', cmd)
  94. subprocess.check_call(cmd)
  95. def _RunNinja(output_dir, args):
  96. # Don't use version within _DEPOT_TOOLS_PATH, since most devs don't use
  97. # that one when building.
  98. cmd = ['autoninja', '-C', output_dir]
  99. cmd.extend(args)
  100. logging.info('Running: %r', cmd)
  101. subprocess.check_call(cmd)
  102. def _QueryForAllGnTargets(output_dir):
  103. cmd = [
  104. os.path.join(_BUILD_ANDROID, 'list_java_targets.py'), '--gn-labels',
  105. '--nested', '--build', '--output-directory', output_dir
  106. ]
  107. logging.info('Running: %r', cmd)
  108. return subprocess.check_output(cmd, encoding='UTF-8').splitlines()
  109. class _ProjectEntry:
  110. """Helper class for project entries."""
  111. _cached_entries = {}
  112. def __init__(self, gn_target):
  113. # Use _ProjectEntry.FromGnTarget instead for caching.
  114. self._gn_target = gn_target
  115. self._build_config = None
  116. self._java_files = None
  117. self._all_entries = None
  118. self.android_test_entries = []
  119. @classmethod
  120. def FromGnTarget(cls, gn_target):
  121. assert gn_target.startswith('//'), gn_target
  122. if ':' not in gn_target:
  123. gn_target = '%s:%s' % (gn_target, os.path.basename(gn_target))
  124. if gn_target not in cls._cached_entries:
  125. cls._cached_entries[gn_target] = cls(gn_target)
  126. return cls._cached_entries[gn_target]
  127. @classmethod
  128. def FromBuildConfigPath(cls, path):
  129. prefix = 'gen/'
  130. suffix = '.build_config.json'
  131. assert path.startswith(prefix) and path.endswith(suffix), path
  132. subdir = path[len(prefix):-len(suffix)]
  133. gn_target = '//%s:%s' % (os.path.split(subdir))
  134. return cls.FromGnTarget(gn_target)
  135. def __hash__(self):
  136. return hash(self._gn_target)
  137. def __eq__(self, other):
  138. return self._gn_target == other.GnTarget()
  139. def GnTarget(self):
  140. return self._gn_target
  141. def NinjaTarget(self):
  142. return self._gn_target[2:]
  143. def GradleSubdir(self):
  144. """Returns the output subdirectory."""
  145. ninja_target = self.NinjaTarget()
  146. # Support targets at the root level. e.g. //:foo
  147. if ninja_target[0] == ':':
  148. ninja_target = ninja_target[1:]
  149. return ninja_target.replace(':', os.path.sep)
  150. def GeneratedJavaSubdir(self):
  151. return _RebasePath(
  152. os.path.join('gen', self.GradleSubdir(), _GENERATED_JAVA_SUBDIR))
  153. def ProjectName(self):
  154. """Returns the Gradle project name."""
  155. return self.GradleSubdir().replace(os.path.sep, '.')
  156. def BuildConfig(self):
  157. """Reads and returns the project's .build_config.json JSON."""
  158. if not self._build_config:
  159. path = os.path.join('gen', self.GradleSubdir() + '.build_config.json')
  160. with open(_RebasePath(path)) as jsonfile:
  161. self._build_config = json.load(jsonfile)
  162. return self._build_config
  163. def DepsInfo(self):
  164. return self.BuildConfig()['deps_info']
  165. def Gradle(self):
  166. return self.BuildConfig()['gradle']
  167. def Javac(self):
  168. return self.BuildConfig()['javac']
  169. def GetType(self):
  170. """Returns the target type from its .build_config."""
  171. return self.DepsInfo()['type']
  172. def IsValid(self):
  173. return self.GetType() in (
  174. 'android_apk',
  175. 'android_app_bundle_module',
  176. 'java_library',
  177. "java_annotation_processor",
  178. 'java_binary',
  179. 'robolectric_binary',
  180. )
  181. def ResSources(self):
  182. return self.DepsInfo().get('lint_resource_sources', [])
  183. def JavaFiles(self):
  184. if self._java_files is None:
  185. java_sources_file = self.DepsInfo().get('java_sources_file')
  186. java_files = []
  187. if java_sources_file:
  188. java_sources_file = _RebasePath(java_sources_file)
  189. java_files = build_utils.ReadSourcesList(java_sources_file)
  190. self._java_files = java_files
  191. return self._java_files
  192. def PrebuiltJars(self):
  193. return self.Gradle().get('dependent_prebuilt_jars', [])
  194. def AllEntries(self):
  195. """Returns a list of all entries that the current entry depends on.
  196. This includes the entry itself to make iterating simpler."""
  197. if self._all_entries is None:
  198. logging.debug('Generating entries for %s', self.GnTarget())
  199. deps = [_ProjectEntry.FromBuildConfigPath(p)
  200. for p in self.Gradle()['dependent_android_projects']]
  201. deps.extend(_ProjectEntry.FromBuildConfigPath(p)
  202. for p in self.Gradle()['dependent_java_projects'])
  203. all_entries = set()
  204. for dep in deps:
  205. all_entries.update(dep.AllEntries())
  206. all_entries.add(self)
  207. self._all_entries = list(all_entries)
  208. return self._all_entries
  209. class _ProjectContextGenerator:
  210. """Helper class to generate gradle build files"""
  211. def __init__(self, project_dir, build_vars, use_gradle_process_resources,
  212. jinja_processor, split_projects, channel):
  213. self.project_dir = project_dir
  214. self.build_vars = build_vars
  215. self.use_gradle_process_resources = use_gradle_process_resources
  216. self.jinja_processor = jinja_processor
  217. self.split_projects = split_projects
  218. self.channel = channel
  219. self.processed_java_dirs = set()
  220. self.processed_prebuilts = set()
  221. self.processed_res_dirs = set()
  222. def _GenJniLibs(self, root_entry):
  223. libraries = []
  224. for entry in self._GetEntries(root_entry):
  225. libraries += entry.BuildConfig().get('native', {}).get('libraries', [])
  226. if libraries:
  227. return _CreateJniLibsDir(constants.GetOutDirectory(),
  228. self.EntryOutputDir(root_entry), libraries)
  229. return []
  230. def _GenJavaDirs(self, root_entry):
  231. java_files = []
  232. for entry in self._GetEntries(root_entry):
  233. java_files += entry.JavaFiles()
  234. java_dirs, excludes = _ComputeJavaSourceDirsAndExcludes(
  235. constants.GetOutDirectory(), java_files)
  236. return java_dirs, excludes
  237. def _GenCustomManifest(self, entry):
  238. """Returns the path to the generated AndroidManifest.xml.
  239. Gradle uses package id from manifest when generating R.class. So, we need
  240. to generate a custom manifest if we let gradle process resources. We cannot
  241. simply set android.defaultConfig.applicationId because it is not supported
  242. for library targets."""
  243. resource_packages = entry.Javac().get('resource_packages')
  244. if not resource_packages:
  245. logging.debug(
  246. 'Target %s includes resources from unknown package. '
  247. 'Unable to process with gradle.', entry.GnTarget())
  248. return _DEFAULT_ANDROID_MANIFEST_PATH
  249. if len(resource_packages) > 1:
  250. logging.debug(
  251. 'Target %s includes resources from multiple packages. '
  252. 'Unable to process with gradle.', entry.GnTarget())
  253. return _DEFAULT_ANDROID_MANIFEST_PATH
  254. variables = {'package': resource_packages[0]}
  255. data = self.jinja_processor.Render(_TemplatePath('manifest'), variables)
  256. output_file = os.path.join(
  257. self.EntryOutputDir(entry), 'AndroidManifest.xml')
  258. _WriteFile(output_file, data)
  259. return output_file
  260. def _Relativize(self, entry, paths):
  261. return _RebasePath(paths, self.EntryOutputDir(entry))
  262. def _GetEntries(self, entry):
  263. if self.split_projects:
  264. return [entry]
  265. return entry.AllEntries()
  266. def EntryOutputDir(self, entry):
  267. return os.path.join(self.project_dir, entry.GradleSubdir())
  268. def GeneratedInputs(self, root_entry):
  269. generated_inputs = set()
  270. for entry in self._GetEntries(root_entry):
  271. generated_inputs.update(entry.PrebuiltJars())
  272. return generated_inputs
  273. def GenerateManifest(self, root_entry):
  274. android_manifest = root_entry.DepsInfo().get('android_manifest')
  275. if not android_manifest:
  276. android_manifest = self._GenCustomManifest(root_entry)
  277. return self._Relativize(root_entry, android_manifest)
  278. def Generate(self, root_entry):
  279. # TODO(agrieve): Add an option to use interface jars and see if that speeds
  280. # things up at all.
  281. variables = {}
  282. java_dirs, excludes = self._GenJavaDirs(root_entry)
  283. java_dirs.extend(
  284. e.GeneratedJavaSubdir() for e in self._GetEntries(root_entry))
  285. self.processed_java_dirs.update(java_dirs)
  286. java_dirs.sort()
  287. variables['java_dirs'] = self._Relativize(root_entry, java_dirs)
  288. variables['java_excludes'] = excludes
  289. variables['jni_libs'] = self._Relativize(
  290. root_entry, set(self._GenJniLibs(root_entry)))
  291. prebuilts = set(
  292. p for e in self._GetEntries(root_entry) for p in e.PrebuiltJars())
  293. self.processed_prebuilts.update(prebuilts)
  294. variables['prebuilts'] = self._Relativize(root_entry, prebuilts)
  295. res_sources_files = _RebasePath(
  296. set(p for e in self._GetEntries(root_entry) for p in e.ResSources()))
  297. res_sources = []
  298. for res_sources_file in res_sources_files:
  299. res_sources.extend(build_utils.ReadSourcesList(res_sources_file))
  300. res_dirs = resource_utils.DeduceResourceDirsFromFileList(res_sources)
  301. # Do not add generated resources for the all module since it creates many
  302. # duplicates, and currently resources are only used for editing.
  303. self.processed_res_dirs.update(res_dirs)
  304. variables['res_dirs'] = self._Relativize(root_entry, res_dirs)
  305. if self.split_projects:
  306. deps = [_ProjectEntry.FromBuildConfigPath(p)
  307. for p in root_entry.Gradle()['dependent_android_projects']]
  308. variables['android_project_deps'] = [d.ProjectName() for d in deps]
  309. deps = [_ProjectEntry.FromBuildConfigPath(p)
  310. for p in root_entry.Gradle()['dependent_java_projects']]
  311. variables['java_project_deps'] = [d.ProjectName() for d in deps]
  312. return variables
  313. def _ComputeJavaSourceDirs(java_files):
  314. """Returns a dictionary of source dirs with each given files in one."""
  315. found_roots = {}
  316. for path in java_files:
  317. path_root = path
  318. # Recognize these tokens as top-level.
  319. while True:
  320. path_root = os.path.dirname(path_root)
  321. basename = os.path.basename(path_root)
  322. assert basename, 'Failed to find source dir for ' + path
  323. if basename in ('java', 'src'):
  324. break
  325. if basename in ('javax', 'org', 'com'):
  326. path_root = os.path.dirname(path_root)
  327. break
  328. if path_root not in found_roots:
  329. found_roots[path_root] = []
  330. found_roots[path_root].append(path)
  331. return found_roots
  332. def _ComputeExcludeFilters(wanted_files, unwanted_files, parent_dir):
  333. """Returns exclude patters to exclude unwanted files but keep wanted files.
  334. - Shortens exclude list by globbing if possible.
  335. - Exclude patterns are relative paths from the parent directory.
  336. """
  337. excludes = []
  338. files_to_include = set(wanted_files)
  339. files_to_exclude = set(unwanted_files)
  340. while files_to_exclude:
  341. unwanted_file = files_to_exclude.pop()
  342. target_exclude = os.path.join(
  343. os.path.dirname(unwanted_file), '*.java')
  344. found_files = set(glob.glob(target_exclude))
  345. valid_files = found_files & files_to_include
  346. if valid_files:
  347. excludes.append(os.path.relpath(unwanted_file, parent_dir))
  348. else:
  349. excludes.append(os.path.relpath(target_exclude, parent_dir))
  350. files_to_exclude -= found_files
  351. return excludes
  352. def _ComputeJavaSourceDirsAndExcludes(output_dir, java_files):
  353. """Computes the list of java source directories and exclude patterns.
  354. 1. Computes the root java source directories from the list of files.
  355. 2. Compute exclude patterns that exclude all extra files only.
  356. 3. Returns the list of java source directories and exclude patterns.
  357. """
  358. java_dirs = []
  359. excludes = []
  360. if java_files:
  361. java_files = _RebasePath(java_files)
  362. computed_dirs = _ComputeJavaSourceDirs(java_files)
  363. java_dirs = list(computed_dirs.keys())
  364. all_found_java_files = set()
  365. for directory, files in computed_dirs.items():
  366. found_java_files = build_utils.FindInDirectory(directory, '*.java')
  367. all_found_java_files.update(found_java_files)
  368. unwanted_java_files = set(found_java_files) - set(files)
  369. if unwanted_java_files:
  370. logging.debug('Directory requires excludes: %s', directory)
  371. excludes.extend(
  372. _ComputeExcludeFilters(files, unwanted_java_files, directory))
  373. missing_java_files = set(java_files) - all_found_java_files
  374. # Warn only about non-generated files that are missing.
  375. missing_java_files = [p for p in missing_java_files
  376. if not p.startswith(output_dir)]
  377. if missing_java_files:
  378. logging.warning(
  379. 'Some java files were not found: %s', missing_java_files)
  380. return java_dirs, excludes
  381. def _CreateRelativeSymlink(target_path, link_path):
  382. link_dir = os.path.dirname(link_path)
  383. relpath = os.path.relpath(target_path, link_dir)
  384. logging.debug('Creating symlink %s -> %s', link_path, relpath)
  385. os.symlink(relpath, link_path)
  386. def _CreateJniLibsDir(output_dir, entry_output_dir, so_files):
  387. """Creates directory with symlinked .so files if necessary.
  388. Returns list of JNI libs directories."""
  389. if so_files:
  390. symlink_dir = os.path.join(entry_output_dir, _JNI_LIBS_SUBDIR)
  391. shutil.rmtree(symlink_dir, True)
  392. abi_dir = os.path.join(symlink_dir, _ARMEABI_SUBDIR)
  393. if not os.path.exists(abi_dir):
  394. os.makedirs(abi_dir)
  395. for so_file in so_files:
  396. target_path = os.path.join(output_dir, so_file)
  397. symlinked_path = os.path.join(abi_dir, so_file)
  398. _CreateRelativeSymlink(target_path, symlinked_path)
  399. return [symlink_dir]
  400. return []
  401. def _GenerateLocalProperties(sdk_dir):
  402. """Returns the data for local.properties as a string."""
  403. return '\n'.join([
  404. '# Generated by //build/android/gradle/generate_gradle.py',
  405. 'sdk.dir=%s' % sdk_dir,
  406. '',
  407. ])
  408. def _GenerateGradleWrapperProperties():
  409. """Returns the data for gradle-wrapper.properties as a string."""
  410. return '\n'.join([
  411. '# Generated by //build/android/gradle/generate_gradle.py',
  412. ('distributionUrl=https\\://services.gradle.org/distributions/'
  413. 'gradle-7.3.3-all.zip\n'),
  414. '',
  415. ])
  416. def _GenerateGradleProperties():
  417. """Returns the data for gradle.properties as a string."""
  418. return '\n'.join([
  419. '# Generated by //build/android/gradle/generate_gradle.py',
  420. '',
  421. '# Tells Gradle to show warnings during project sync.',
  422. 'org.gradle.warning.mode=all',
  423. '',
  424. ])
  425. def _GenerateBaseVars(generator, build_vars):
  426. variables = {}
  427. # Avoid pre-release SDKs since Studio might not know how to download them.
  428. variables['compile_sdk_version'] = ('android-%s' %
  429. build_vars['public_android_sdk_version'])
  430. target_sdk_version = build_vars['public_android_sdk_version']
  431. if str(target_sdk_version).isalpha():
  432. target_sdk_version = '"{}"'.format(target_sdk_version)
  433. variables['target_sdk_version'] = target_sdk_version
  434. variables['min_sdk_version'] = build_vars['default_min_sdk_version']
  435. variables['use_gradle_process_resources'] = (
  436. generator.use_gradle_process_resources)
  437. variables['channel'] = generator.channel
  438. return variables
  439. def _GenerateGradleFile(entry, generator, build_vars, jinja_processor):
  440. """Returns the data for a project's build.gradle."""
  441. deps_info = entry.DepsInfo()
  442. variables = _GenerateBaseVars(generator, build_vars)
  443. sourceSetName = 'main'
  444. if deps_info['type'] == 'android_apk':
  445. target_type = 'android_apk'
  446. elif deps_info['type'] in ('java_library', 'java_annotation_processor'):
  447. is_prebuilt = deps_info.get('is_prebuilt', False)
  448. gradle_treat_as_prebuilt = deps_info.get('gradle_treat_as_prebuilt', False)
  449. if is_prebuilt or gradle_treat_as_prebuilt:
  450. return None
  451. if deps_info['requires_android']:
  452. target_type = 'android_library'
  453. else:
  454. target_type = 'java_library'
  455. elif deps_info['type'] == 'java_binary':
  456. target_type = 'java_binary'
  457. variables['main_class'] = deps_info.get('main_class')
  458. elif deps_info['type'] == 'robolectric_binary':
  459. target_type = 'android_junit'
  460. sourceSetName = 'test'
  461. else:
  462. return None
  463. variables['target_name'] = os.path.splitext(deps_info['name'])[0]
  464. variables['template_type'] = target_type
  465. variables['main'] = {}
  466. variables[sourceSetName] = generator.Generate(entry)
  467. variables['main']['android_manifest'] = generator.GenerateManifest(entry)
  468. if entry.android_test_entries:
  469. variables['android_test'] = []
  470. for e in entry.android_test_entries:
  471. test_entry = generator.Generate(e)
  472. test_entry['android_manifest'] = generator.GenerateManifest(e)
  473. variables['android_test'].append(test_entry)
  474. for key, value in test_entry.items():
  475. if isinstance(value, list):
  476. test_entry[key] = sorted(set(value) - set(variables['main'][key]))
  477. return jinja_processor.Render(
  478. _TemplatePath(target_type.split('_')[0]), variables)
  479. # Example: //chrome/android:monochrome
  480. def _GetNative(relative_func, target_names):
  481. """Returns an object containing native c++ sources list and its included path
  482. Iterate through all target_names and their deps to get the list of included
  483. paths and sources."""
  484. out_dir = constants.GetOutDirectory()
  485. with open(os.path.join(out_dir, 'project.json'), 'r') as project_file:
  486. projects = json.load(project_file)
  487. project_targets = projects['targets']
  488. root_dir = projects['build_settings']['root_path']
  489. includes = set()
  490. processed_target = set()
  491. targets_stack = list(target_names)
  492. sources = []
  493. while targets_stack:
  494. target_name = targets_stack.pop()
  495. if target_name in processed_target:
  496. continue
  497. processed_target.add(target_name)
  498. target = project_targets[target_name]
  499. includes.update(target.get('include_dirs', []))
  500. targets_stack.extend(target.get('deps', []))
  501. # Ignore generated files
  502. sources.extend(f for f in target.get('sources', [])
  503. if f.endswith('.cc') and not f.startswith('//out'))
  504. def process_paths(paths):
  505. # Ignores leading //
  506. return relative_func(
  507. sorted(os.path.join(root_dir, path[2:]) for path in paths))
  508. return {
  509. 'sources': process_paths(sources),
  510. 'includes': process_paths(includes),
  511. }
  512. def _GenerateModuleAll(gradle_output_dir, generator, build_vars,
  513. jinja_processor, native_targets):
  514. """Returns the data for a pseudo build.gradle of all dirs.
  515. See //docs/android_studio.md for more details."""
  516. variables = _GenerateBaseVars(generator, build_vars)
  517. target_type = 'android_apk'
  518. variables['target_name'] = _MODULE_ALL
  519. variables['template_type'] = target_type
  520. java_dirs = sorted(generator.processed_java_dirs)
  521. prebuilts = sorted(generator.processed_prebuilts)
  522. res_dirs = sorted(generator.processed_res_dirs)
  523. def Relativize(paths):
  524. return _RebasePath(paths, os.path.join(gradle_output_dir, _MODULE_ALL))
  525. # As after clank modularization, the java and javatests code will live side by
  526. # side in the same module, we will list both of them in the main target here.
  527. main_java_dirs = [d for d in java_dirs if 'junit/' not in d]
  528. junit_test_java_dirs = [d for d in java_dirs if 'junit/' in d]
  529. variables['main'] = {
  530. 'android_manifest': Relativize(_DEFAULT_ANDROID_MANIFEST_PATH),
  531. 'java_dirs': Relativize(main_java_dirs),
  532. 'prebuilts': Relativize(prebuilts),
  533. 'java_excludes': ['**/*.java'],
  534. 'res_dirs': Relativize(res_dirs),
  535. }
  536. variables['android_test'] = [{
  537. 'java_dirs': Relativize(junit_test_java_dirs),
  538. 'java_excludes': ['**/*.java'],
  539. }]
  540. if native_targets:
  541. variables['native'] = _GetNative(
  542. relative_func=Relativize, target_names=native_targets)
  543. data = jinja_processor.Render(
  544. _TemplatePath(target_type.split('_')[0]), variables)
  545. _WriteFile(
  546. os.path.join(gradle_output_dir, _MODULE_ALL, _GRADLE_BUILD_FILE), data)
  547. if native_targets:
  548. cmake_data = jinja_processor.Render(_TemplatePath('cmake'), variables)
  549. _WriteFile(
  550. os.path.join(gradle_output_dir, _MODULE_ALL, _CMAKE_FILE), cmake_data)
  551. def _GenerateRootGradle(jinja_processor, channel):
  552. """Returns the data for the root project's build.gradle."""
  553. return jinja_processor.Render(_TemplatePath('root'), {'channel': channel})
  554. def _GenerateSettingsGradle(project_entries):
  555. """Returns the data for settings.gradle."""
  556. project_name = os.path.basename(os.path.dirname(host_paths.DIR_SOURCE_ROOT))
  557. lines = []
  558. lines.append('// Generated by //build/android/gradle/generate_gradle.py')
  559. lines.append('rootProject.name = "%s"' % project_name)
  560. lines.append('rootProject.projectDir = settingsDir')
  561. lines.append('')
  562. for name, subdir in project_entries:
  563. # Example target:
  564. # android_webview:android_webview_java__build_config_crbug_908819
  565. lines.append('include ":%s"' % name)
  566. lines.append('project(":%s").projectDir = new File(settingsDir, "%s")' %
  567. (name, subdir))
  568. return '\n'.join(lines)
  569. def _FindAllProjectEntries(main_entries):
  570. """Returns the list of all _ProjectEntry instances given the root project."""
  571. found = set()
  572. to_scan = list(main_entries)
  573. while to_scan:
  574. cur_entry = to_scan.pop()
  575. if cur_entry in found:
  576. continue
  577. found.add(cur_entry)
  578. sub_config_paths = cur_entry.DepsInfo()['deps_configs']
  579. to_scan.extend(
  580. _ProjectEntry.FromBuildConfigPath(p) for p in sub_config_paths)
  581. return list(found)
  582. def _CombineTestEntries(entries):
  583. """Combines test apks into the androidTest source set of their target.
  584. - Speeds up android studio
  585. - Adds proper dependency between test and apk_under_test
  586. - Doesn't work for junit yet due to resulting circular dependencies
  587. - e.g. base_junit_tests > base_junit_test_support > base_java
  588. """
  589. combined_entries = []
  590. android_test_entries = collections.defaultdict(list)
  591. for entry in entries:
  592. target_name = entry.GnTarget()
  593. if (target_name.endswith(_INSTRUMENTATION_TARGET_SUFFIX)
  594. and 'apk_under_test' in entry.Gradle()):
  595. apk_name = entry.Gradle()['apk_under_test']
  596. android_test_entries[apk_name].append(entry)
  597. else:
  598. combined_entries.append(entry)
  599. for entry in combined_entries:
  600. target_name = entry.DepsInfo()['name']
  601. if target_name in android_test_entries:
  602. entry.android_test_entries = android_test_entries[target_name]
  603. del android_test_entries[target_name]
  604. # Add unmatched test entries as individual targets.
  605. combined_entries.extend(e for l in android_test_entries.values() for e in l)
  606. return combined_entries
  607. def main():
  608. parser = argparse.ArgumentParser()
  609. parser.add_argument('--output-directory',
  610. help='Path to the root build directory.')
  611. parser.add_argument('-v',
  612. '--verbose',
  613. dest='verbose_count',
  614. default=0,
  615. action='count',
  616. help='Verbose level')
  617. parser.add_argument('--target',
  618. dest='targets',
  619. action='append',
  620. help='GN target to generate project for. Replaces set of '
  621. 'default targets. May be repeated.')
  622. parser.add_argument('--extra-target',
  623. dest='extra_targets',
  624. action='append',
  625. help='GN target to generate project for, in addition to '
  626. 'the default ones. May be repeated.')
  627. parser.add_argument('--project-dir',
  628. help='Root of the output project.',
  629. default=os.path.join('$CHROMIUM_OUTPUT_DIR', 'gradle'))
  630. parser.add_argument('--all',
  631. action='store_true',
  632. help='Include all .java files reachable from any '
  633. 'apk/test/binary target. On by default unless '
  634. '--split-projects is used (--split-projects can '
  635. 'slow down Studio given too many targets).')
  636. parser.add_argument('--use-gradle-process-resources',
  637. action='store_true',
  638. help='Have gradle generate R.java rather than ninja')
  639. parser.add_argument('--split-projects',
  640. action='store_true',
  641. help='Split projects by their gn deps rather than '
  642. 'combining all the dependencies of each target')
  643. parser.add_argument('--native-target',
  644. dest='native_targets',
  645. action='append',
  646. help='GN native targets to generate for. May be '
  647. 'repeated.')
  648. parser.add_argument(
  649. '--sdk-path',
  650. default=os.path.expanduser('~/Android/Sdk'),
  651. help='The path to use as the SDK root, overrides the '
  652. 'default at ~/Android/Sdk.')
  653. version_group = parser.add_mutually_exclusive_group()
  654. version_group.add_argument('--beta',
  655. action='store_true',
  656. help='Generate a project that is compatible with '
  657. 'Android Studio Beta.')
  658. version_group.add_argument('--canary',
  659. action='store_true',
  660. help='Generate a project that is compatible with '
  661. 'Android Studio Canary.')
  662. args = parser.parse_args()
  663. if args.output_directory:
  664. constants.SetOutputDirectory(args.output_directory)
  665. constants.CheckOutputDirectory()
  666. output_dir = constants.GetOutDirectory()
  667. devil_chromium.Initialize(output_directory=output_dir)
  668. run_tests_helper.SetLogLevel(args.verbose_count)
  669. if args.use_gradle_process_resources:
  670. assert args.split_projects, (
  671. 'Gradle resources does not work without --split-projects.')
  672. _gradle_output_dir = os.path.abspath(
  673. args.project_dir.replace('$CHROMIUM_OUTPUT_DIR', output_dir))
  674. logging.warning('Creating project at: %s', _gradle_output_dir)
  675. # Generate for "all targets" by default when not using --split-projects (too
  676. # slow), and when no --target has been explicitly set. "all targets" means all
  677. # java targets that are depended on by an apk or java_binary (leaf
  678. # java_library targets will not be included).
  679. args.all = args.all or (not args.split_projects and not args.targets)
  680. targets_from_args = set(args.targets or _DEFAULT_TARGETS)
  681. if args.extra_targets:
  682. targets_from_args.update(args.extra_targets)
  683. if args.all:
  684. if args.native_targets:
  685. _RunGnGen(output_dir, ['--ide=json'])
  686. elif not os.path.exists(os.path.join(output_dir, 'build.ninja')):
  687. _RunGnGen(output_dir)
  688. else:
  689. # Faster than running "gn gen" in the no-op case.
  690. _RunNinja(output_dir, ['build.ninja'])
  691. # Query ninja for all __build_config_crbug_908819 targets.
  692. targets = _QueryForAllGnTargets(output_dir)
  693. else:
  694. assert not args.native_targets, 'Native editing requires --all.'
  695. targets = [
  696. re.sub(r'_test_apk$', _INSTRUMENTATION_TARGET_SUFFIX, t)
  697. for t in targets_from_args
  698. ]
  699. # Necessary after "gn clean"
  700. if not os.path.exists(
  701. os.path.join(output_dir, gn_helpers.BUILD_VARS_FILENAME)):
  702. _RunGnGen(output_dir)
  703. build_vars = gn_helpers.ReadBuildVars(output_dir)
  704. jinja_processor = jinja_template.JinjaProcessor(_FILE_DIR)
  705. if args.beta:
  706. channel = 'beta'
  707. elif args.canary:
  708. channel = 'canary'
  709. else:
  710. channel = 'stable'
  711. generator = _ProjectContextGenerator(_gradle_output_dir, build_vars,
  712. args.use_gradle_process_resources, jinja_processor, args.split_projects,
  713. channel)
  714. main_entries = [_ProjectEntry.FromGnTarget(t) for t in targets]
  715. if args.all:
  716. # There are many unused libraries, so restrict to those that are actually
  717. # used by apks/bundles/binaries/tests or that are explicitly mentioned in
  718. # --targets.
  719. BASE_TYPES = ('android_apk', 'android_app_bundle_module', 'java_binary',
  720. 'robolectric_binary')
  721. main_entries = [
  722. e for e in main_entries
  723. if (e.GetType() in BASE_TYPES or e.GnTarget() in targets_from_args
  724. or e.GnTarget().endswith(_INSTRUMENTATION_TARGET_SUFFIX))
  725. ]
  726. if args.split_projects:
  727. main_entries = _FindAllProjectEntries(main_entries)
  728. logging.info('Generating for %d targets.', len(main_entries))
  729. entries = [e for e in _CombineTestEntries(main_entries) if e.IsValid()]
  730. logging.info('Creating %d projects for targets.', len(entries))
  731. logging.warning('Writing .gradle files...')
  732. project_entries = []
  733. # When only one entry will be generated we want it to have a valid
  734. # build.gradle file with its own AndroidManifest.
  735. for entry in entries:
  736. data = _GenerateGradleFile(entry, generator, build_vars, jinja_processor)
  737. if data and not args.all:
  738. project_entries.append((entry.ProjectName(), entry.GradleSubdir()))
  739. _WriteFile(
  740. os.path.join(generator.EntryOutputDir(entry), _GRADLE_BUILD_FILE),
  741. data)
  742. if args.all:
  743. project_entries.append((_MODULE_ALL, _MODULE_ALL))
  744. _GenerateModuleAll(_gradle_output_dir, generator, build_vars,
  745. jinja_processor, args.native_targets)
  746. _WriteFile(os.path.join(generator.project_dir, _GRADLE_BUILD_FILE),
  747. _GenerateRootGradle(jinja_processor, channel))
  748. _WriteFile(os.path.join(generator.project_dir, 'settings.gradle'),
  749. _GenerateSettingsGradle(project_entries))
  750. # Ensure the Android Studio sdk is correctly initialized.
  751. if not os.path.exists(args.sdk_path):
  752. # Help first-time users avoid Android Studio forcibly changing back to
  753. # the previous default due to not finding a valid sdk under this dir.
  754. shutil.copytree(_RebasePath(build_vars['android_sdk_root']), args.sdk_path)
  755. _WriteFile(
  756. os.path.join(generator.project_dir, 'local.properties'),
  757. _GenerateLocalProperties(args.sdk_path))
  758. _WriteFile(os.path.join(generator.project_dir, 'gradle.properties'),
  759. _GenerateGradleProperties())
  760. wrapper_properties = os.path.join(generator.project_dir, 'gradle', 'wrapper',
  761. 'gradle-wrapper.properties')
  762. if os.path.exists(wrapper_properties):
  763. os.unlink(wrapper_properties)
  764. _WriteFile(wrapper_properties, _GenerateGradleWrapperProperties())
  765. generated_inputs = set()
  766. for entry in entries:
  767. entries_to_gen = [entry]
  768. entries_to_gen.extend(entry.android_test_entries)
  769. for entry_to_gen in entries_to_gen:
  770. # Build all paths references by .gradle that exist within output_dir.
  771. generated_inputs.update(generator.GeneratedInputs(entry_to_gen))
  772. if generated_inputs:
  773. targets = _RebasePath(generated_inputs, output_dir)
  774. _RunNinja(output_dir, targets)
  775. logging.warning('Generated files will only appear once you\'ve built them.')
  776. logging.warning('Generated projects for Android Studio %s', channel)
  777. logging.warning('For more tips: https://chromium.googlesource.com/chromium'
  778. '/src.git/+/master/docs/android_studio.md')
  779. if __name__ == '__main__':
  780. main()