PageRenderTime 86ms CodeModel.GetById 28ms RepoModel.GetById 3ms app.codeStats 0ms

/build/android/preprocess_google_play_services.py

https://gitlab.com/jonnialva90/iridium-browser
Python | 299 lines | 285 code | 8 blank | 6 comment | 5 complexity | d2216ac11c6da983691ad43bfe782530 MD5 | raw file
  1. #!/usr/bin/env python
  2. #
  3. # Copyright 2015 The Chromium Authors. All rights reserved.
  4. # Use of this source code is governed by a BSD-style license that can be
  5. # found in the LICENSE file.
  6. '''Prepares the Google Play services split client libraries before usage by
  7. Chrome's build system.
  8. We need to preprocess Google Play services before using it in Chrome
  9. builds for 2 main reasons:
  10. - Getting rid of unused resources: unsupported languages, unused
  11. drawables, etc.
  12. - Merging the differents jars so that it can be proguarded more
  13. easily. This is necessary since debug and test apks get very close
  14. to the dex limit.
  15. The script is supposed to be used with the maven repository that can be
  16. obtained by downloading the "extra-google-m2repository" from the Android SDK
  17. Manager. It also supports importing from already extracted AAR files using the
  18. --is-extracted-repo flag. The expected directory structure in that case would
  19. look like:
  20. REPOSITORY_DIR
  21. +-- CLIENT_1
  22. | +-- <content of the first AAR file>
  23. +-- CLIENT_2
  24. +-- etc.
  25. The json config (see the -c argument) file should provide the following fields:
  26. - lib_version: String. Used when building from the maven repository. It should
  27. be the package's version (e.g. "7.3.0"). Unused with extracted repositories.
  28. - clients: String array. List of clients to pick. For example, when building
  29. from the maven repository, it's the artifactId (e.g. "play-services-base") of
  30. each client. With an extracted repository, it's the name of the
  31. subdirectories.
  32. - locale_whitelist: String array. Locales that should be allowed in the final
  33. resources. They are specified the same way they are appended to the `values`
  34. directory in android resources (e.g. "us-GB", "it", "fil").
  35. The output is a directory with the following structure:
  36. OUT_DIR
  37. +-- google-play-services.jar
  38. +-- res
  39. | +-- CLIENT_1
  40. | | +-- color
  41. | | +-- values
  42. | | +-- etc.
  43. | +-- CLIENT_2
  44. | +-- ...
  45. +-- stub
  46. +-- res/[.git-keep-directory]
  47. +-- src/android/UnusedStub.java
  48. Requires the `jar` utility in the path.
  49. '''
  50. import argparse
  51. import glob
  52. import itertools
  53. import json
  54. import os
  55. import re
  56. import shutil
  57. import stat
  58. import sys
  59. from datetime import datetime
  60. from devil.utils import cmd_helper
  61. from pylib import constants
  62. sys.path.append(
  63. os.path.join(constants.DIR_SOURCE_ROOT, 'build', 'android', 'gyp'))
  64. from util import build_utils # pylint: disable=import-error
  65. M2_PKG_PATH = os.path.join('com', 'google', 'android', 'gms')
  66. OUTPUT_FORMAT_VERSION = 1
  67. VERSION_FILE_NAME = 'version_info.json'
  68. VERSION_NUMBER_PATTERN = re.compile(
  69. r'<integer name="google_play_services_version">(\d+)<\/integer>')
  70. def main():
  71. parser = argparse.ArgumentParser(description=("Prepares the Google Play "
  72. "services split client libraries before usage by Chrome's build system. "
  73. "See the script's documentation for more a detailed help."))
  74. parser.add_argument('-r',
  75. '--repository',
  76. help='The Google Play services repository location',
  77. required=True,
  78. metavar='FILE')
  79. parser.add_argument('-o',
  80. '--out-dir',
  81. help='The output directory',
  82. required=True,
  83. metavar='FILE')
  84. parser.add_argument('-c',
  85. '--config-file',
  86. help='Config file path',
  87. required=True,
  88. metavar='FILE')
  89. parser.add_argument('-x',
  90. '--is-extracted-repo',
  91. action='store_true',
  92. default=False,
  93. help='The provided repository is not made of AAR files.')
  94. args = parser.parse_args()
  95. ProcessGooglePlayServices(args.repository,
  96. args.out_dir,
  97. args.config_file,
  98. args.is_extracted_repo)
  99. def ProcessGooglePlayServices(repo, out_dir, config_path, is_extracted_repo):
  100. with open(config_path, 'r') as json_file:
  101. config = json.load(json_file)
  102. with build_utils.TempDir() as tmp_root:
  103. tmp_paths = _SetupTempDir(tmp_root)
  104. if is_extracted_repo:
  105. _ImportFromExtractedRepo(config, tmp_paths, repo)
  106. else:
  107. _ImportFromAars(config, tmp_paths, repo)
  108. _GenerateCombinedJar(tmp_paths)
  109. _ProcessResources(config, tmp_paths)
  110. if is_extracted_repo:
  111. printable_repo = repo
  112. else:
  113. printable_repo = 'm2repository - ' + config['lib_version']
  114. _BuildOutput(config, tmp_paths, out_dir, printable_repo)
  115. def _SetupTempDir(tmp_root):
  116. tmp_paths = {
  117. 'root': tmp_root,
  118. 'imported_clients': os.path.join(tmp_root, 'imported_clients'),
  119. 'extracted_jars': os.path.join(tmp_root, 'jar'),
  120. 'combined_jar': os.path.join(tmp_root, 'google-play-services.jar'),
  121. }
  122. os.mkdir(tmp_paths['imported_clients'])
  123. os.mkdir(tmp_paths['extracted_jars'])
  124. return tmp_paths
  125. def _SetupOutputDir(out_dir):
  126. out_paths = {
  127. 'root': out_dir,
  128. 'res': os.path.join(out_dir, 'res'),
  129. 'jar': os.path.join(out_dir, 'google-play-services.jar'),
  130. 'stub': os.path.join(out_dir, 'stub'),
  131. }
  132. shutil.rmtree(out_paths['jar'], ignore_errors=True)
  133. shutil.rmtree(out_paths['res'], ignore_errors=True)
  134. shutil.rmtree(out_paths['stub'], ignore_errors=True)
  135. return out_paths
  136. def _MakeWritable(dir_path):
  137. for root, dirs, files in os.walk(dir_path):
  138. for path in itertools.chain(dirs, files):
  139. st = os.stat(os.path.join(root, path))
  140. os.chmod(os.path.join(root, path), st.st_mode | stat.S_IWUSR)
  141. def _ImportFromAars(config, tmp_paths, repo):
  142. for client in config['clients']:
  143. aar_name = '%s-%s.aar' % (client, config['lib_version'])
  144. aar_path = os.path.join(repo, M2_PKG_PATH, client,
  145. config['lib_version'], aar_name)
  146. aar_out_path = os.path.join(tmp_paths['imported_clients'], client)
  147. build_utils.ExtractAll(aar_path, aar_out_path)
  148. client_jar_path = os.path.join(aar_out_path, 'classes.jar')
  149. build_utils.ExtractAll(client_jar_path, tmp_paths['extracted_jars'],
  150. no_clobber=False)
  151. def _ImportFromExtractedRepo(config, tmp_paths, repo):
  152. # Import the clients
  153. try:
  154. for client in config['clients']:
  155. client_out_dir = os.path.join(tmp_paths['imported_clients'], client)
  156. shutil.copytree(os.path.join(repo, client), client_out_dir)
  157. client_jar_path = os.path.join(client_out_dir, 'classes.jar')
  158. build_utils.ExtractAll(client_jar_path, tmp_paths['extracted_jars'],
  159. no_clobber=False)
  160. finally:
  161. _MakeWritable(tmp_paths['imported_clients'])
  162. def _GenerateCombinedJar(tmp_paths):
  163. out_file_name = tmp_paths['combined_jar']
  164. working_dir = tmp_paths['extracted_jars']
  165. cmd_helper.Call(['jar', '-cf', out_file_name, '-C', working_dir, '.'])
  166. def _ProcessResources(config, tmp_paths):
  167. LOCALIZED_VALUES_BASE_NAME = 'values-'
  168. locale_whitelist = set(config['locale_whitelist'])
  169. glob_pattern = os.path.join(tmp_paths['imported_clients'], '*', 'res', '*')
  170. for res_dir in glob.glob(glob_pattern):
  171. dir_name = os.path.basename(res_dir)
  172. if dir_name.startswith('drawable'):
  173. shutil.rmtree(res_dir)
  174. continue
  175. if dir_name.startswith(LOCALIZED_VALUES_BASE_NAME):
  176. dir_locale = dir_name[len(LOCALIZED_VALUES_BASE_NAME):]
  177. if dir_locale not in locale_whitelist:
  178. shutil.rmtree(res_dir)
  179. def _GetVersionNumber(config, tmp_paths):
  180. version_file_path = os.path.join(tmp_paths['imported_clients'],
  181. config['base_client'],
  182. 'res',
  183. 'values',
  184. 'version.xml')
  185. with open(version_file_path, 'r') as version_file:
  186. version_file_content = version_file.read()
  187. match = VERSION_NUMBER_PATTERN.search(version_file_content)
  188. if not match:
  189. raise AttributeError('A value for google_play_services_version was not '
  190. 'found in ' + version_file_path)
  191. return match.group(1)
  192. def _BuildOutput(config, tmp_paths, out_dir, printable_repo):
  193. generation_date = datetime.utcnow()
  194. play_services_full_version = _GetVersionNumber(config, tmp_paths)
  195. # Create a version text file to allow quickly checking the version
  196. gen_info = {
  197. '@Description@': 'Preprocessed Google Play services clients for chrome',
  198. 'Generator script': os.path.basename(__file__),
  199. 'Repository source': printable_repo,
  200. 'Library version': play_services_full_version,
  201. 'Directory format version': OUTPUT_FORMAT_VERSION,
  202. 'Generation Date (UTC)': str(generation_date)
  203. }
  204. tmp_version_file_path = os.path.join(tmp_paths['root'], VERSION_FILE_NAME)
  205. with open(tmp_version_file_path, 'w') as version_file:
  206. json.dump(gen_info, version_file, indent=2, sort_keys=True)
  207. out_paths = _SetupOutputDir(out_dir)
  208. # Copy the resources to the output dir
  209. for client in config['clients']:
  210. res_in_tmp_dir = os.path.join(tmp_paths['imported_clients'], client, 'res')
  211. if os.path.isdir(res_in_tmp_dir) and os.listdir(res_in_tmp_dir):
  212. res_in_final_dir = os.path.join(out_paths['res'], client)
  213. shutil.copytree(res_in_tmp_dir, res_in_final_dir)
  214. # Copy the jar
  215. shutil.copyfile(tmp_paths['combined_jar'], out_paths['jar'])
  216. # Write the java dummy stub. Needed for gyp to create the resource jar
  217. stub_location = os.path.join(out_paths['stub'], 'src', 'android')
  218. os.makedirs(stub_location)
  219. with open(os.path.join(stub_location, 'UnusedStub.java'), 'w') as stub:
  220. stub.write('package android;'
  221. 'public final class UnusedStub {'
  222. ' private UnusedStub() {}'
  223. '}')
  224. # Create the main res directory. It is needed by gyp
  225. stub_res_location = os.path.join(out_paths['stub'], 'res')
  226. os.makedirs(stub_res_location)
  227. with open(os.path.join(stub_res_location, '.res-stamp'), 'w') as stamp:
  228. content_str = 'google_play_services_version: %s\nutc_date: %s\n'
  229. stamp.write(content_str % (play_services_full_version, generation_date))
  230. shutil.copyfile(tmp_version_file_path,
  231. os.path.join(out_paths['root'], VERSION_FILE_NAME))
  232. if __name__ == '__main__':
  233. sys.exit(main())