blob: 9fc8c8d760b00b0c757cdcd0827b290f5411cc67 [file] [log] [blame]
Alan Viverettef5cb0e62017-11-17 15:15:23 -05001#!/usr/bin/python3
Alan Viverette95f6d362017-04-06 09:40:50 -04002
Alan Viverettecd3de262017-08-14 09:51:30 -04003# This script is used to update platform SDK prebuilts, Support Library, and a variety of other
4# prebuilt libraries used by Android's Makefile builds. For details on how to use this script,
5# visit go/update-prebuilts.
Alan Viverette95f6d362017-04-06 09:40:50 -04006import os, sys, getopt, zipfile, re
Alan Viveretted4527e62017-05-11 15:03:25 -04007import argparse
Jiyong Park1d1c9632018-05-29 17:45:27 +09008import glob
Alan Viveretted4527e62017-05-11 15:03:25 -04009import subprocess
shepshaparde4127cf2019-09-03 16:08:44 -070010from shutil import copyfile, rmtree, which, move
Alan Viveretted4527e62017-05-11 15:03:25 -040011from distutils.version import LooseVersion
Alan Viverettef5cb0e62017-11-17 15:15:23 -050012from functools import reduce
Saeid Farivar Asanjan54cd34e2021-10-01 16:47:54 +000013import six
14import urllib.request, urllib.parse, urllib.error
Alan Viverette95f6d362017-04-06 09:40:50 -040015
Alan Viverette45837092017-05-12 14:50:53 -040016current_path = 'current'
Andy Wickhamc3c99af2020-10-26 20:47:58 +000017framework_sdk_target = 'sdk_phone_armv7-win_sdk'
Jeff Gastonbbd6bfc2018-03-27 17:35:49 -040018androidx_dir = os.path.join(current_path, 'androidx')
Saeid Farivar Asanjan54cd34e2021-10-01 16:47:54 +000019gmaven_dir = os.path.join(current_path, 'gmaven')
Alan Viverette3e57a4a2017-08-11 15:49:47 -040020extras_dir = os.path.join(current_path, 'extras')
Alan Viverettec1c32b62017-12-20 09:40:36 -050021buildtools_dir = 'tools'
Jeff Gaston553a4372018-03-29 18:34:22 -040022jetifier_dir = os.path.join(buildtools_dir, 'jetifier', 'jetifier-standalone')
Alan Viverette95f6d362017-04-06 09:40:50 -040023
Jeff Gastona68a8d42018-03-23 14:00:13 -040024temp_dir = os.path.join(os.getcwd(), "support_tmp")
25os.chdir(os.path.dirname(os.path.dirname(os.path.realpath(sys.argv[0]))))
26git_dir = os.getcwd()
27
Alan Viverettecd3de262017-08-14 09:51:30 -040028# See go/fetch_artifact for details on this script.
Alan Viveretted4527e62017-05-11 15:03:25 -040029FETCH_ARTIFACT = '/google/data/ro/projects/android/fetch_artifact'
Jeff Sharkeyabe16df2021-05-25 10:09:03 -060030FETCH_ARTIFACT_BEYOND_CORP = '/usr/bin/fetch_artifact'
Alan Viveretted4527e62017-05-11 15:03:25 -040031
Saeid Farivar Asanjan54cd34e2021-10-01 16:47:54 +000032# See (https://developer.android.com/studio/build/dependencies#gmaven-access)
33GMAVEN_BASE_URL = 'https://maven.google.com'
34
Alan Viverette0723aff2021-08-31 17:07:47 +000035# Leave map blank to automatically populate name and path:
36# - Name format is MAVEN.replaceAll(':','_')
37# - Path format is MAVEN.replaceAll(':','/').replaceAll('.','/')
Alan Viverette95f6d362017-04-06 09:40:50 -040038maven_to_make = {
Jeff Gastonbbd6bfc2018-03-27 17:35:49 -040039 # AndroidX
Alan Viverettef3c12722021-08-30 19:50:33 +000040 'androidx.benchmark:benchmark-macro': { },
41 'androidx.benchmark:benchmark-macro-junit4': { },
42 'androidx.benchmark:benchmark-common': { },
43 'androidx.benchmark:benchmark-junit4': { },
44 'androidx.tracing:tracing': { },
45 'androidx.tracing:tracing-ktx': { },
46 'androidx.slice:slice-builders': { },
47 'androidx.slice:slice-core': { },
48 'androidx.slice:slice-view': { },
49 'androidx.remotecallback:remotecallback': { },
Alan Viverette0723aff2021-08-31 17:07:47 +000050 'androidx.remotecallback:remotecallback-processor': {'host':True},
51 'androidx.versionedparcelable:versionedparcelable': { },
Alan Viverettef3c12722021-08-30 19:50:33 +000052 'androidx.vectordrawable:vectordrawable-animated': { },
53 'androidx.activity:activity': { },
54 'androidx.activity:activity-ktx': { },
Alan Viverette0723aff2021-08-31 17:07:47 +000055 'androidx.annotation:annotation': {'host_and_device':True},
Alan Viverettef3c12722021-08-30 19:50:33 +000056 'androidx.annotation:annotation-experimental': { },
57 'androidx.asynclayoutinflater:asynclayoutinflater': { },
58 'androidx.collection:collection': { },
59 'androidx.collection:collection-ktx': { },
60 'androidx.concurrent:concurrent-futures': { },
61 'androidx.concurrent:concurrent-listenablefuture-callback': { },
62 'androidx.concurrent:concurrent-listenablefuture': { },
63 'androidx.core:core': { },
64 'androidx.core:core-animation': { },
65 'androidx.core:core-ktx': { },
66 'androidx.contentpaging:contentpaging': { },
67 'androidx.coordinatorlayout:coordinatorlayout': { },
68 'androidx.legacy:legacy-support-core-ui': { },
69 'androidx.legacy:legacy-support-core-utils': { },
70 'androidx.cursoradapter:cursoradapter': { },
71 'androidx.browser:browser': { },
72 'androidx.customview:customview': { },
73 'androidx.documentfile:documentfile': { },
74 'androidx.drawerlayout:drawerlayout': { },
75 'androidx.dynamicanimation:dynamicanimation': { },
76 'androidx.emoji:emoji': { },
77 'androidx.emoji:emoji-appcompat': { },
78 'androidx.emoji:emoji-bundled': { },
79 'androidx.emoji2:emoji2': { },
80 'androidx.emoji2:emoji2-views-helper': { },
81 'androidx.exifinterface:exifinterface': { },
82 'androidx.fragment:fragment': { },
83 'androidx.fragment:fragment-ktx': { },
84 'androidx.heifwriter:heifwriter': { },
85 'androidx.interpolator:interpolator': { },
86 'androidx.loader:loader': { },
87 'androidx.localbroadcastmanager:localbroadcastmanager': { },
88 'androidx.media:media': { },
89 'androidx.media2:media2-player': { },
90 'androidx.media2:media2-session': { },
91 'androidx.media2:media2-common': { },
92 'androidx.media2:media2-exoplayer': { },
93 'androidx.media2:media2-widget': { },
94 'androidx.navigation:navigation-common': { },
95 'androidx.navigation:navigation-common-ktx': { },
96 'androidx.navigation:navigation-fragment': { },
97 'androidx.navigation:navigation-fragment-ktx': { },
98 'androidx.navigation:navigation-runtime': { },
99 'androidx.navigation:navigation-runtime-ktx': { },
100 'androidx.navigation:navigation-ui': { },
101 'androidx.navigation:navigation-ui-ktx': { },
102 'androidx.percentlayout:percentlayout': { },
103 'androidx.print:print': { },
104 'androidx.recommendation:recommendation': { },
105 'androidx.recyclerview:recyclerview-selection': { },
106 'androidx.savedstate:savedstate': { },
107 'androidx.savedstate:savedstate-ktx': { },
108 'androidx.slidingpanelayout:slidingpanelayout': { },
109 'androidx.swiperefreshlayout:swiperefreshlayout': { },
110 'androidx.textclassifier:textclassifier': { },
111 'androidx.transition:transition': { },
112 'androidx.tvprovider:tvprovider': { },
113 'androidx.legacy:legacy-support-v13': { },
114 'androidx.legacy:legacy-preference-v14': { },
115 'androidx.leanback:leanback': { },
116 'androidx.leanback:leanback-preference': { },
117 'androidx.legacy:legacy-support-v4': { },
118 'androidx.appcompat:appcompat': { },
119 'androidx.appcompat:appcompat-resources': { },
120 'androidx.cardview:cardview': { },
121 'androidx.gridlayout:gridlayout': { },
122 'androidx.mediarouter:mediarouter': { },
123 'androidx.palette:palette': { },
124 'androidx.preference:preference': { },
125 'androidx.recyclerview:recyclerview': { },
126 'androidx.vectordrawable:vectordrawable': { },
127 'androidx.viewpager:viewpager': { },
128 'androidx.viewpager2:viewpager2': { },
129 'androidx.wear:wear': { },
130 'androidx.wear:wear-ongoing': { },
131 'androidx.webkit:webkit': { },
132 'androidx.biometric:biometric': { },
133 'androidx.autofill:autofill': { },
134 'androidx.appsearch:appsearch': { },
Alan Viverette0723aff2021-08-31 17:07:47 +0000135 'androidx.appsearch:appsearch-local-storage': {'name':'androidx.appsearch_appsearch_local_storage'},
136 'androidx.appsearch:appsearch-platform-storage': { },
137 'androidx.appsearch:appsearch-compiler': {'name':'androidx.appsearch_appsearch-compiler', 'host':True},
Alan Viverettef3c12722021-08-30 19:50:33 +0000138 'androidx.car.app:app': { },
139 'androidx.car.app:app-automotive': { },
140 'androidx.car.app:app-testing': { },
141 'androidx.startup:startup-runtime': { },
Alan Viverettecdfc9892021-08-31 19:35:58 +0000142 'androidx.window:window': {'optional-uses-libs':{'androidx.window.extensions', 'androidx.window.sidecar'}},
Alan Viverettef3c12722021-08-30 19:50:33 +0000143 'androidx.resourceinspection:resourceinspection-annotation': { },
144 'androidx.profileinstaller:profileinstaller': { },
Aurimas Liutikas6e87bbf2021-07-30 10:04:05 -0700145
Alan Viverettef44e2f92021-08-31 17:26:26 +0000146 # AndroidX for Compose
Colin Cross58866d42021-09-17 14:40:35 -0700147 'androidx.compose.compiler:compiler-hosted': { 'host':True },
Alan Viverettef44e2f92021-08-31 17:26:26 +0000148 'androidx.compose.runtime:runtime': { },
149 'androidx.compose.runtime:runtime-saveable': { },
150 'androidx.compose.foundation:foundation': { },
151 'androidx.compose.foundation:foundation-layout': { },
152 'androidx.compose.foundation:foundation-text': { },
153 'androidx.compose.ui:ui': { },
154 'androidx.compose.ui:ui-geometry': { },
155 'androidx.compose.ui:ui-graphics': { },
156 'androidx.compose.ui:ui-text': { },
157 'androidx.compose.ui:ui-unit': { },
158 'androidx.compose.ui:ui-util': { },
159 'androidx.compose.animation:animation-core': { },
160 'androidx.compose.animation:animation': { },
161 'androidx.compose.material:material-icons-core': { },
162 'androidx.compose.material:material-ripple': { },
163 'androidx.compose.material:material': { },
164 'androidx.activity:activity-compose': { },
165
Jeff Gastonbbd6bfc2018-03-27 17:35:49 -0400166 # AndroidX for Multidex
Alan Viverette0723aff2021-08-31 17:07:47 +0000167 'androidx.multidex:multidex': { },
168 'androidx.multidex:multidex-instrumentation': { },
Jeff Gastonbbd6bfc2018-03-27 17:35:49 -0400169
170 # AndroidX for Constraint Layout
Alan Viverette0723aff2021-08-31 17:07:47 +0000171 'androidx.constraintlayout:constraintlayout': {'name':'androidx-constraintlayout_constraintlayout'},
172 'androidx.constraintlayout:constraintlayout-solver': {'name':'androidx-constraintlayout_constraintlayout-solver'},
Jeff Gastonbbd6bfc2018-03-27 17:35:49 -0400173
174 # AndroidX for Architecture Components
Alan Viverettef3c12722021-08-30 19:50:33 +0000175 'androidx.arch.core:core-common': { },
176 'androidx.arch.core:core-runtime': { },
177 'androidx.lifecycle:lifecycle-common': { },
178 'androidx.lifecycle:lifecycle-common-java8': { },
179 'androidx.lifecycle:lifecycle-extensions': { },
180 'androidx.lifecycle:lifecycle-livedata': { },
181 'androidx.lifecycle:lifecycle-livedata-ktx': { },
182 'androidx.lifecycle:lifecycle-livedata-core': { },
183 'androidx.lifecycle:lifecycle-livedata-core-ktx': { },
184 'androidx.lifecycle:lifecycle-process': { },
185 'androidx.lifecycle:lifecycle-runtime': { },
186 'androidx.lifecycle:lifecycle-runtime-ktx': { },
187 'androidx.lifecycle:lifecycle-service': { },
188 'androidx.lifecycle:lifecycle-viewmodel': { },
189 'androidx.lifecycle:lifecycle-viewmodel-ktx': { },
190 'androidx.lifecycle:lifecycle-viewmodel-savedstate': { },
191 'androidx.paging:paging-common': { },
192 'androidx.paging:paging-common-ktx': { },
193 'androidx.paging:paging-runtime': { },
194 'androidx.sqlite:sqlite': { },
195 'androidx.sqlite:sqlite-framework': { },
Alan Viverette0723aff2021-08-31 17:07:47 +0000196 'androidx.room:room-common': {'host_and_device':True},
Alan Viverettecdfc9892021-08-31 19:35:58 +0000197 'androidx.room:room-compiler': {'host':True, 'extra-static-libs':{'guava-21.0'}},
Alan Viverette0723aff2021-08-31 17:07:47 +0000198 'androidx.room:room-migration': {'host_and_device':True},
Alan Viverettef3c12722021-08-30 19:50:33 +0000199 'androidx.room:room-runtime': { },
200 'androidx.room:room-testing': { },
Alan Viverette0723aff2021-08-31 17:07:47 +0000201 'androidx.room:room-compiler-processing': {'host':True},
Alan Viverettef3c12722021-08-30 19:50:33 +0000202 'androidx.work:work-runtime': { },
203 'androidx.work:work-runtime-ktx': { },
204 'androidx.work:work-testing': { },
Allenab72f012018-01-29 18:10:23 -0800205
Jeff Gaston6e7e7502018-04-04 00:22:45 -0400206 # Third-party dependencies
Jeff Gastona0bce602018-08-24 14:05:03 -0400207 'com.google.android:flexbox': {'name':'flexbox', 'path':'flexbox'},
Jeff Gaston6e7e7502018-04-04 00:22:45 -0400208
Jeff Gastonfa7c7e82018-04-06 13:35:48 -0400209 # Androidx Material Design Components
Alan Viverettef3c12722021-08-30 19:50:33 +0000210 'com.google.android.material:material': { },
Alan Viverette95f6d362017-04-06 09:40:50 -0400211}
212
Alan Viverettecdfc9892021-08-31 19:35:58 +0000213# Mapping of POM dependencies to Soong build targets
214deps_rewrite = {
215 'auto-common':'auto_common',
216 'auto-value-annotations':'auto_value_annotations',
217 'com.google.auto.value:auto-value':'auto_value_plugin',
218 'monitor':'androidx.test.monitor',
219 'rules':'androidx.test.rules',
220 'runner':'androidx.test.runner',
221 'androidx.test:core':'androidx.test.core',
222 'com.squareup:javapoet':'javapoet',
223 'com.google.guava:listenablefuture':'guava-listenablefuture-prebuilt-jar',
224 'sqlite-jdbc':'xerial-sqlite-jdbc',
225 'gson':'gson-prebuilt-jar',
226 'com.intellij:annotations':'jetbrains-annotations',
227 'javax.annotation:javax.annotation-api':'javax-annotation-api-prebuilt-host-jar',
228 'org.robolectric:robolectric':'Robolectric_all-target',
229 'org.jetbrains.kotlin:kotlin-stdlib-common':'kotlin-stdlib',
230 'org.jetbrains.kotlinx:kotlinx-coroutines-core':'kotlinx_coroutines',
231 'org.jetbrains.kotlinx:kotlinx-coroutines-android':'kotlinx_coroutines_android',
232 'org.jetbrains.kotlinx:kotlinx-metadata-jvm':'kotlinx_metadata_jvm',
233}
234
Saeid Farivar Asanjan54cd34e2021-10-01 16:47:54 +0000235# List of artifacts that will be updated from GMaven
236# Use pattern: `group:library:version:extension`
237# e.g.:
238# androidx.appcompat:appcompat:1.2.0:aar
239# Use `latest` to always fetch the latest version.
240# e.g.:
241# androidx.appcompat:appcompat:latest:aar
242# Also make sure you add `group:library`:{} to maven_to_make as well.
243gmaven_artifacts = {}
Alan Viverettef3c12722021-08-30 19:50:33 +0000244
245def name_for_artifact(group_artifact):
246 return group_artifact.replace(':','_')
247
248
249def path_for_artifact(group_artifact):
250 return group_artifact.replace('.','/').replace(':','/')
251
252
253# Add automatic entries to maven_to_make.
254for key in maven_to_make:
255 if ('name' not in maven_to_make[key]):
256 maven_to_make[key]['name'] = name_for_artifact(key)
257 if ('path' not in maven_to_make[key]):
258 maven_to_make[key]['path'] = path_for_artifact(key)
259
Alan Viverette95f6d362017-04-06 09:40:50 -0400260# Always remove these files.
261blacklist_files = [
262 'annotations.zip',
263 'public.txt',
264 'R.txt',
Alan Viverette44ad4e42017-08-09 17:45:00 -0400265 'AndroidManifest.xml',
Alan Viverettef48d9b42017-08-17 14:45:46 -0400266 os.path.join('libs','noto-emoji-compat-java.jar')
Alan Viverette95f6d362017-04-06 09:40:50 -0400267]
268
Alan Viverette44ad4e42017-08-09 17:45:00 -0400269artifact_pattern = re.compile(r"^(.+?)-(\d+\.\d+\.\d+(?:-\w+\d+)?(?:-[\d.]+)*)\.(jar|aar)$")
Alan Viverette95f6d362017-04-06 09:40:50 -0400270
Alan Viverettec960cfb2017-12-04 13:09:22 -0500271
272class MavenLibraryInfo:
Jeff Gastonc302bb92018-03-23 13:53:48 -0400273 def __init__(self, key, group_id, artifact_id, version, dir, repo_dir, file):
Alan Viverettec960cfb2017-12-04 13:09:22 -0500274 self.key = key
275 self.group_id = group_id
276 self.artifact_id = artifact_id
277 self.version = version
Jeff Gastonc302bb92018-03-23 13:53:48 -0400278 self.dir = dir
Alan Viverettec960cfb2017-12-04 13:09:22 -0500279 self.repo_dir = repo_dir
280 self.file = file
281
282
Alan Viverettef5cb0e62017-11-17 15:15:23 -0500283def print_e(*args, **kwargs):
284 print(*args, file=sys.stderr, **kwargs)
285
Alan Viverette95f6d362017-04-06 09:40:50 -0400286
287def touch(fname, times=None):
288 with open(fname, 'a'):
289 os.utime(fname, times)
290
291
Alan Viverette45837092017-05-12 14:50:53 -0400292def path(*path_parts):
293 return reduce((lambda x, y: os.path.join(x, y)), path_parts)
294
295
Alan Viverettecd3de262017-08-14 09:51:30 -0400296def flatten(list):
297 return reduce((lambda x, y: "%s %s" % (x, y)), list)
298
299
Alan Viverette45837092017-05-12 14:50:53 -0400300def rm(path):
301 if os.path.isdir(path):
302 rmtree(path)
303 elif os.path.exists(path):
304 os.remove(path)
305
306
307def mv(src_path, dst_path):
Alan Viverette3e57a4a2017-08-11 15:49:47 -0400308 if os.path.exists(dst_path):
Alan Viverettecd3de262017-08-14 09:51:30 -0400309 rm(dst_path)
Alan Viverette3e57a4a2017-08-11 15:49:47 -0400310 if not os.path.exists(os.path.dirname(dst_path)):
311 os.makedirs(os.path.dirname(dst_path))
Jiyong Park1d1c9632018-05-29 17:45:27 +0900312 for f in (glob.glob(src_path)):
313 if '*' in dst_path:
314 dst = os.path.join(os.path.dirname(dst_path), os.path.basename(f))
315 else:
316 dst = dst_path
shepshaparde4127cf2019-09-03 16:08:44 -0700317 move(f, dst)
Alan Viverette45837092017-05-12 14:50:53 -0400318
319
Jeff Gastonc302bb92018-03-23 13:53:48 -0400320def detect_artifacts(maven_repo_dirs):
Alan Viveretted4527e62017-05-11 15:03:25 -0400321 maven_lib_info = {}
322
Dan Willemsen814152e2017-11-06 13:22:11 -0800323 # Find the latest revision for each artifact, remove others
Jeff Gastonc302bb92018-03-23 13:53:48 -0400324 for repo_dir in maven_repo_dirs:
Dan Willemsen814152e2017-11-06 13:22:11 -0800325 for root, dirs, files in os.walk(repo_dir):
326 for file in files:
Alan Viverettec960cfb2017-12-04 13:09:22 -0500327 if file[-4:] == ".pom":
328 # Read the POM (hack hack hack).
329 group_id = ''
330 artifact_id = ''
331 version = ''
332 file = os.path.join(root, file)
333 with open(file) as pom_file:
334 for line in pom_file:
335 if line[:11] == ' <groupId>':
336 group_id = line[11:-11]
337 elif line[:14] == ' <artifactId>':
338 artifact_id = line[14:-14]
339 elif line[:11] == ' <version>':
340 version = line[11:-11]
341 if group_id == '' or artifact_id == '' or version == '':
342 print_e('Failed to find Maven artifact data in ' + file)
343 continue
Alan Viverette95f6d362017-04-06 09:40:50 -0400344
Alan Viverettec960cfb2017-12-04 13:09:22 -0500345 # Locate the artifact.
346 artifact_file = file[:-4]
347 if os.path.exists(artifact_file + '.jar'):
348 artifact_file = artifact_file + '.jar'
349 elif os.path.exists(artifact_file + '.aar'):
350 artifact_file = artifact_file + '.aar'
351 else:
352 print_e('Failed to find artifact for ' + artifact_file)
353 continue
354
355 # Make relative to root.
356 artifact_file = artifact_file[len(root) + 1:]
357
358 # Find the mapping.
359 group_artifact = group_id + ':' + artifact_id
Jeff Gaston3e622ba2018-03-26 23:24:46 -0400360 if group_artifact in maven_to_make:
Alan Viverettec960cfb2017-12-04 13:09:22 -0500361 key = group_artifact
Jeff Gaston3e622ba2018-03-26 23:24:46 -0400362 elif artifact_id in maven_to_make:
363 key = artifact_id
Alan Viverettec960cfb2017-12-04 13:09:22 -0500364 else:
Alan Viverettecdfc9892021-08-31 19:35:58 +0000365 # No mapping entry, skip this library.
Alan Viverettec960cfb2017-12-04 13:09:22 -0500366 continue
367
368 # Store the latest version.
369 version = LooseVersion(version)
370 if key not in maven_lib_info \
371 or version > maven_lib_info[key].version:
372 maven_lib_info[key] = MavenLibraryInfo(key, group_id, artifact_id, version,
373 root, repo_dir, artifact_file)
Alan Viverette95f6d362017-04-06 09:40:50 -0400374
Alan Viverette3e57a4a2017-08-11 15:49:47 -0400375 return maven_lib_info
376
377
Colin Cross59b59db2018-04-24 13:58:05 -0700378def transform_maven_repos(maven_repo_dirs, transformed_dir, extract_res=True, include_static_deps=True):
Alan Viverette3e57a4a2017-08-11 15:49:47 -0400379 cwd = os.getcwd()
380
381 # Use a temporary working directory.
Jeff Gastonc302bb92018-03-23 13:53:48 -0400382 maven_lib_info = detect_artifacts(maven_repo_dirs)
Jeff Gastona68a8d42018-03-23 14:00:13 -0400383 working_dir = temp_dir
Alan Viverette3e57a4a2017-08-11 15:49:47 -0400384
Alan Viverettec960cfb2017-12-04 13:09:22 -0500385 if not maven_lib_info:
386 print_e('Failed to detect artifacts')
387 return False
388
Jeff Gastonc302bb92018-03-23 13:53:48 -0400389 # extract some files (for example, AndroidManifest.xml) from any relevant artifacts
Alan Viveretted4527e62017-05-11 15:03:25 -0400390 for info in maven_lib_info.values():
Alan Viveretted8ce7222017-12-11 17:24:43 -0500391 transform_maven_lib(working_dir, info, extract_res)
Dan Willemsen814152e2017-11-06 13:22:11 -0800392
Colin Cross74683bc2018-04-11 17:36:18 -0700393 # generate a single Android.bp that specifies to use all of the above artifacts
394 makefile = os.path.join(working_dir, 'Android.bp')
Alan Viverette4ec9a172018-02-20 16:19:31 -0500395 with open(makefile, 'w') as f:
Anton Hanssonbd2021c2021-04-06 19:21:34 +0000396 args = ["pom2bp"]
Aurimas Liutikas6e87bbf2021-07-30 10:04:05 -0700397 args.extend(["-sdk-version", "31"])
Anton Hanssonbd2021c2021-04-06 19:21:34 +0000398 args.extend(["-default-min-sdk-version", "24"])
Jeff Gaston1cc06092018-03-28 15:51:02 -0400399 if include_static_deps:
400 args.append("-static-deps")
Jeff Gaston54868ee2018-04-25 19:43:35 -0400401 rewriteNames = sorted([name for name in maven_to_make if ":" in name] + [name for name in maven_to_make if ":" not in name])
Jeff Gastona0bce602018-08-24 14:05:03 -0400402 args.extend(["-rewrite=^" + name + "$=" + maven_to_make[name]['name'] for name in rewriteNames])
Alan Viverettecdfc9892021-08-31 19:35:58 +0000403 args.extend(["-rewrite=^" + key + "$=" + value for key, value in deps_rewrite.items()])
404 args.extend(["-extra-static-libs=" + maven_to_make[name]['name'] + "=" + ",".join(sorted(maven_to_make[name]['extra-static-libs'])) for name in maven_to_make if 'extra-static-libs' in maven_to_make[name]])
405 args.extend(["-optional-uses-libs=" + maven_to_make[name]['name'] + "=" + ",".join(sorted(maven_to_make[name]['optional-uses-libs'])) for name in maven_to_make if 'optional-uses-libs' in maven_to_make[name]])
Jeff Gaston07a3cf72018-08-24 14:16:34 -0400406 args.extend(["-host=" + name for name in maven_to_make if maven_to_make[name].get('host')])
Tony Mak0f658752019-07-19 11:11:05 +0100407 args.extend(["-host-and-device=" + name for name in maven_to_make if maven_to_make[name].get('host_and_device')])
Jeff Gaston7ec1d8f2018-03-27 00:25:12 -0400408 args.extend(["."])
Dan Willemsen814152e2017-11-06 13:22:11 -0800409 subprocess.check_call(args, stdout=f, cwd=working_dir)
Alan Viverette95f6d362017-04-06 09:40:50 -0400410
411 # Replace the old directory.
Jeff Gastonc302bb92018-03-23 13:53:48 -0400412 output_dir = os.path.join(cwd, transformed_dir)
Alan Viverette3e57a4a2017-08-11 15:49:47 -0400413 mv(working_dir, output_dir)
Alan Viverettec960cfb2017-12-04 13:09:22 -0500414 return True
Alan Viverette95f6d362017-04-06 09:40:50 -0400415
Jeff Gastonc302bb92018-03-23 13:53:48 -0400416# moves <artifact_info> (of type MavenLibraryInfo) into the appropriate part of <working_dir> , and possibly unpacks any necessary included files
Alan Viveretted8ce7222017-12-11 17:24:43 -0500417def transform_maven_lib(working_dir, artifact_info, extract_res):
Dan Willemsen814152e2017-11-06 13:22:11 -0800418 # Move library into working dir
Jeff Gaston9edf86c2018-04-18 13:45:23 -0400419 new_dir = os.path.normpath(os.path.join(working_dir, os.path.relpath(artifact_info.dir, artifact_info.repo_dir)))
Jeff Gastonc302bb92018-03-23 13:53:48 -0400420 mv(artifact_info.dir, new_dir)
Dan Willemsen814152e2017-11-06 13:22:11 -0800421
Alan Viverettec960cfb2017-12-04 13:09:22 -0500422 matcher = artifact_pattern.match(artifact_info.file)
423 maven_lib_name = artifact_info.key
Alan Viveretted4527e62017-05-11 15:03:25 -0400424 maven_lib_vers = matcher.group(2)
Alan Viverettec960cfb2017-12-04 13:09:22 -0500425 maven_lib_type = artifact_info.file[-3:]
Alan Viveretted4527e62017-05-11 15:03:25 -0400426
Alan Viverettef3c12722021-08-30 19:50:33 +0000427 group_artifact = artifact_info.key
428 make_lib_name = maven_to_make[group_artifact]['name']
429 make_dir_name = maven_to_make[group_artifact]['path']
Alan Viveretted4527e62017-05-11 15:03:25 -0400430
Alan Viverette129555e2018-01-30 09:57:57 -0500431 artifact_file = os.path.join(new_dir, artifact_info.file)
432
Colin Cross59b59db2018-04-24 13:58:05 -0700433 if maven_lib_type == "aar":
434 if extract_res:
435 target_dir = os.path.join(working_dir, make_dir_name)
436 if not os.path.exists(target_dir):
437 os.makedirs(target_dir)
Dan Willemsen814152e2017-11-06 13:22:11 -0800438
Alan Viverettec960cfb2017-12-04 13:09:22 -0500439 process_aar(artifact_file, target_dir)
Alan Viveretted4527e62017-05-11 15:03:25 -0400440
Colin Cross59b59db2018-04-24 13:58:05 -0700441 with zipfile.ZipFile(artifact_file) as zip:
442 manifests_dir = os.path.join(working_dir, "manifests")
443 zip.extract("AndroidManifest.xml", os.path.join(manifests_dir, make_lib_name))
Dan Willemsend677b602017-11-08 22:13:17 -0800444
Alan Viverettef5cb0e62017-11-17 15:15:23 -0500445 print(maven_lib_vers, ":", maven_lib_name, "->", make_lib_name)
Alan Viveretted4527e62017-05-11 15:03:25 -0400446
Alan Viverette95f6d362017-04-06 09:40:50 -0400447
Alan Viverettec960cfb2017-12-04 13:09:22 -0500448def process_aar(artifact_file, target_dir):
Alan Viverette95f6d362017-04-06 09:40:50 -0400449 # Extract AAR file to target_dir.
450 with zipfile.ZipFile(artifact_file) as zip:
451 zip.extractall(target_dir)
452
Dan Willemsen814152e2017-11-06 13:22:11 -0800453 # Remove classes.jar
Alan Viverette95f6d362017-04-06 09:40:50 -0400454 classes_jar = os.path.join(target_dir, "classes.jar")
455 if os.path.exists(classes_jar):
Dan Willemsen814152e2017-11-06 13:22:11 -0800456 os.remove(classes_jar)
Alan Viverette95f6d362017-04-06 09:40:50 -0400457
458 # Remove or preserve empty dirs.
459 for root, dirs, files in os.walk(target_dir):
460 for dir in dirs:
461 dir_path = os.path.join(root, dir)
462 if not os.listdir(dir_path):
463 os.rmdir(dir_path)
464
465 # Remove top-level cruft.
466 for file in blacklist_files:
467 file_path = os.path.join(target_dir, file)
468 if os.path.exists(file_path):
469 os.remove(file_path)
470
Alan Viverettef17c9402017-07-19 12:57:40 -0400471
Saeid Farivar Asanjan54cd34e2021-10-01 16:47:54 +0000472class GMavenArtifact(object):
473 # A map from group:library to the latest available version
474 key_versions_map = {}
475 def __init__(self, artifact_glob):
476 try:
477 (group, library, version, ext) = artifact_glob.split(':')
478 except ValueError:
479 raise ValueError(f'Error in {artifact_glob} expected: group:library:version:ext')
480
481 if not group or not library or not version or not ext:
482 raise ValueError(f'Error in {artifact_glob} expected: group:library:version:ext')
483
484 self.group = group
485 self.group_path = group.replace('.', '/')
486 self.library = library
487 self.key = f'{group}:{library}'
488 self.version = version
489 self.ext = ext
490
491 def get_pom_file_url(self):
492 return f'{GMAVEN_BASE_URL}/{self.group_path}/{self.library}/{self.version}/{self.library}-{self.version}.pom'
493
494 def get_artifact_url(self):
495 return f'{GMAVEN_BASE_URL}/{self.group_path}/{self.library}/{self.version}/{self.library}-{self.version}.{self.ext}'
496
497 def get_latest_version(self):
498 latest_version = GMavenArtifact.key_versions_map[self.key] \
499 if self.key in GMavenArtifact.key_versions_map else None
500
501 if not latest_version:
502 print(f'Fetching latest version for {self.key}')
503 group_index_url = f'{GMAVEN_BASE_URL}/{self.group_path}/group-index.xml'
504 import xml.etree.ElementTree as ET
505 tree = ET.parse(urllib.request.urlopen(group_index_url))
506 root = tree.getroot()
507 libraries = root.findall('./*[@versions]')
508 for library in libraries:
509 key = f'{root.tag}:{library.tag}'
510 GMavenArtifact.key_versions_map[key] = library.get('versions').split(',')[-1]
511 latest_version = GMavenArtifact.key_versions_map[self.key]
512 return latest_version
513
514
515def fetch_gmaven_artifact(artifact):
516 """Fetch a GMaven artifact.
517
518 Downloads a GMaven artifact
519 (https://developer.android.com/studio/build/dependencies#gmaven-access)
520
521 Args:
522 artifact_glob: an instance of GMavenArtifact.
523 """
524 download_to = os.path.join('gmaven', artifact.group, artifact.library, artifact.version)
525
526 _DownloadFileToDisk(artifact.get_pom_file_url(), os.path.join(download_to, f'{artifact.library}-{artifact.version}.pom'))
527 _DownloadFileToDisk(artifact.get_artifact_url(), os.path.join(download_to, f'{artifact.library}-{artifact.version}.{artifact.ext}'))
528
529 return download_to
530
531
532def _DownloadFileToDisk(url, filepath):
533 """Download the file at URL to the location dictated by the path.
534
535 Args:
536 url: Remote URL to download file from.
537 filepath: Filesystem path to write the file to.
538 """
539 print(f'Downloading URL: {url}')
540 file_data = urllib.request.urlopen(url)
541
542 try:
543 os.makedirs(os.path.dirname(filepath))
544 except os.error:
545 # This is a common situation - os.makedirs fails if dir already exists.
546 pass
547 try:
548 with open(filepath, 'wb') as f:
549 f.write(six.ensure_binary(file_data.read()))
550 except:
551 os.remove(os.path.dirname(filepath))
552 raise
553
554
Alan Viverettecd3de262017-08-14 09:51:30 -0400555def fetch_artifact(target, build_id, artifact_path):
Jeff Sharkeyabe16df2021-05-25 10:09:03 -0600556 global args
Jiyong Park1d1c9632018-05-29 17:45:27 +0900557 download_to = os.path.join('.', os.path.dirname(artifact_path))
558 print('Fetching %s from %s ...' % (artifact_path, target))
559 if not os.path.exists(download_to):
560 os.makedirs(download_to)
Jeff Sharkeyabe16df2021-05-25 10:09:03 -0600561 if args.beyond_corp:
562 fetch_cmd = [FETCH_ARTIFACT_BEYOND_CORP, '--use_oauth2',
563 '--bid', str(build_id), '--target', target, artifact_path, download_to]
564 else:
565 fetch_cmd = [FETCH_ARTIFACT,
566 '--bid', str(build_id), '--target', target, artifact_path, download_to]
Jeff Gaston97a9b762018-10-02 15:15:12 -0400567 print("Running: " + ' '.join(fetch_cmd))
Alan Viverette45837092017-05-12 14:50:53 -0400568 try:
Alan Viverettecd3de262017-08-14 09:51:30 -0400569 subprocess.check_output(fetch_cmd, stderr=subprocess.STDOUT)
Alan Viverette45837092017-05-12 14:50:53 -0400570 except subprocess.CalledProcessError:
Jeff Gaston13e38412018-02-06 14:45:36 -0500571 print_e('FAIL: Unable to retrieve %s artifact for build ID %s' % (artifact_path, build_id))
Alan Viverettec1c32b62017-12-20 09:40:36 -0500572 print_e('Please make sure you are authenticated for build server access!')
Alan Viverette45837092017-05-12 14:50:53 -0400573 return None
574 return artifact_path
575
576
Anton Hansson1d01a032018-04-09 10:29:37 +0100577def fetch_artifacts(target, build_id, artifact_dict):
578 for artifact, target_path in artifact_dict.items():
579 artifact_path = fetch_artifact(target, build_id.url_id, artifact)
580 if not artifact_path:
581 return False
582 mv(artifact_path, target_path)
583 return True
584
585
Alan Viverette129555e2018-01-30 09:57:57 -0500586def extract_artifact(artifact_path):
Alan Viverette45837092017-05-12 14:50:53 -0400587 # Unzip the repo archive into a separate directory.
Alan Viverette3e57a4a2017-08-11 15:49:47 -0400588 repo_dir = os.path.basename(artifact_path)[:-4]
Alan Viverette45837092017-05-12 14:50:53 -0400589 with zipfile.ZipFile(artifact_path) as zipFile:
Alan Viverette3e57a4a2017-08-11 15:49:47 -0400590 zipFile.extractall(repo_dir)
Alan Viverette3e57a4a2017-08-11 15:49:47 -0400591 return repo_dir
592
593
Alan Viverette7e897e22018-03-09 15:24:10 -0500594def fetch_and_extract(target, build_id, file, artifact_path=None):
595 if not artifact_path:
596 artifact_path = fetch_artifact(target, build_id, file)
Alan Viverette129555e2018-01-30 09:57:57 -0500597 if not artifact_path:
598 return None
599 return extract_artifact(artifact_path)
600
601
Saeid Farivar Asanjan54cd34e2021-10-01 16:47:54 +0000602def update_gmaven(gmaven_artifacts):
603 artifacts = [GMavenArtifact(artifact) for artifact in gmaven_artifacts]
604 for artifact in artifacts:
605 if artifact.version == 'latest':
606 artifact.version = artifact.get_latest_version()
607
608 artifact_dirs = [fetch_gmaven_artifact(artifact) for artifact in artifacts]
609 if not transform_maven_repos(['gmaven'], gmaven_dir, extract_res=False):
610 return []
611 return [artifact.key for artifact in artifacts]
612
613
Jeff Gaston08a2ee42018-05-07 18:08:41 -0400614def update_androidx(target, build_id, local_file):
Jeff Gastonbbd6bfc2018-03-27 17:35:49 -0400615 if build_id:
Anthony Chenacbb4872018-07-02 11:22:48 -0700616 repo_file = 'top-of-tree-m2repository-all-%s.zip' % build_id.fs_id
Jeff Gastonbbd6bfc2018-03-27 17:35:49 -0400617 repo_dir = fetch_and_extract(target, build_id.url_id, repo_file, None)
618 else:
619 repo_dir = fetch_and_extract(target, None, None, local_file)
620 if not repo_dir:
621 print_e('Failed to extract AndroidX repository')
622 return False
623
Tony Mak0f658752019-07-19 11:11:05 +0100624 # Keep JavaPlugins.bp file untounched.
625 java_plugins_bp_path = os.path.join(androidx_dir, 'JavaPlugins.bp')
626 tmp_java_plugins_bp_path = os.path.join('/tmp', 'JavaPlugins.bp')
627 mv(java_plugins_bp_path, tmp_java_plugins_bp_path)
Jeff Gastonbbd6bfc2018-03-27 17:35:49 -0400628
Tony Mak0f658752019-07-19 11:11:05 +0100629 # Transform the repo archive into a Makefile-compatible format.
630 if not transform_maven_repos([repo_dir], androidx_dir, extract_res=False):
631 return False
632
633 # Import JavaPlugins.bp in Android.bp.
634 makefile = os.path.join(androidx_dir, 'Android.bp')
635 with open(makefile, "a+") as f:
636 f.write('\nbuild = ["JavaPlugins.bp"]\n')
637 mv(tmp_java_plugins_bp_path, java_plugins_bp_path)
638
639 return True
Jeff Gastonbbd6bfc2018-03-27 17:35:49 -0400640
Alan Viverette6dc45752020-04-16 14:56:20 +0000641
Jeff Gaston782c3e32018-02-06 14:36:17 -0500642def update_jetifier(target, build_id):
643 repo_file = 'jetifier-standalone.zip'
644 repo_dir = fetch_and_extract(target, build_id.url_id, repo_file)
645 if not repo_dir:
646 print_e('Failed to extract Jetifier')
647 return False
648
649 rm(jetifier_dir)
Jeff Gaston553a4372018-03-29 18:34:22 -0400650 mv(os.path.join(repo_dir, 'jetifier-standalone'), jetifier_dir)
651 os.chmod(os.path.join(jetifier_dir, 'bin', 'jetifier-standalone'), 0o755)
Jeff Gaston782c3e32018-02-06 14:36:17 -0500652 return True
653
Alan Viverette7e897e22018-03-09 15:24:10 -0500654
Alan Viverette6dc45752020-04-16 14:56:20 +0000655def update_constraint(local_file):
Jeff Gaston9edf86c2018-04-18 13:45:23 -0400656 repo_dir = extract_artifact(local_file)
657 if not repo_dir:
Alan Viverette6dc45752020-04-16 14:56:20 +0000658 print_e('Failed to extract Constraint Layout')
Jeff Gaston9edf86c2018-04-18 13:45:23 -0400659 return False
660 return transform_maven_repos([repo_dir], os.path.join(extras_dir, 'constraint-layout-x'), extract_res=False)
661
Alan Viverette45837092017-05-12 14:50:53 -0400662
Jeff Gaston6e7e7502018-04-04 00:22:45 -0400663def update_material(file):
664 design_dir = extract_artifact(file)
665 if not design_dir:
Alan Viverette6dc45752020-04-16 14:56:20 +0000666 print_e('Failed to extract Material Design Components')
Jeff Gaston6e7e7502018-04-04 00:22:45 -0400667 return False
668
669 # Don't bother extracting resources -- this should only be used with AAPT2.
670 return transform_maven_repos([design_dir],
671 os.path.join(extras_dir, 'material-design-x'), extract_res=False)
672
673
Anton Hansson1d01a032018-04-09 10:29:37 +0100674def update_framework(build_id, sdk_dir):
Anton Hansson83f92172020-03-26 11:12:03 +0000675 api_scope_list = ['public', 'system', 'test', 'module-lib', 'system-server']
Sundong Ahn66091f22018-08-29 18:54:28 +0900676 if sdk_dir == 'current':
677 api_scope_list.append('core')
678
679 for api_scope in api_scope_list:
Jiyong Park1d1c9632018-05-29 17:45:27 +0900680 target_dir = path(sdk_dir, api_scope)
Sundong Ahn66091f22018-08-29 18:54:28 +0900681 if api_scope == 'core':
682 artifact_to_path = {'core.current.stubs.jar': path(target_dir, 'android.jar')}
683 else:
684 artifact_to_path = {'apistubs/android/' + api_scope + '/*.jar': path(target_dir, '*')}
Anton Hansson1d01a032018-04-09 10:29:37 +0100685
686 if not fetch_artifacts(framework_sdk_target, build_id, artifact_to_path):
687 return False
688
Jiyong Park1d1c9632018-05-29 17:45:27 +0900689 if api_scope == 'public':
Anton Hansson1d01a032018-04-09 10:29:37 +0100690 # Fetch a few artifacts from the public sdk.
Sundong Ahn66091f22018-08-29 18:54:28 +0900691 artifact = 'sdk-repo-linux-platforms-%s.zip' % build_id.fs_id
Anton Hansson1d01a032018-04-09 10:29:37 +0100692 artifact_path = fetch_artifact(framework_sdk_target, build_id.url_id, artifact)
Anton Hansson9709fd42018-04-03 16:52:13 +0100693 if not artifact_path:
694 return False
Anton Hansson1d01a032018-04-09 10:29:37 +0100695
696 with zipfile.ZipFile(artifact_path) as zipFile:
Colin Crossd338d702020-07-10 19:17:54 -0700697 extra_files = [
698 'android.jar',
699 'framework.aidl',
700 'uiautomator.jar',
701 'core-for-system-modules.jar',
702 'data/annotations.zip',
703 'data/api-versions.xml']
704 for filename in extra_files:
Anton Hanssona26e4812020-03-25 12:54:39 +0000705 matches = list(filter(lambda path: filename in path, zipFile.namelist()))
706 if len(matches) != 1:
707 print_e('Expected 1 file named \'%s\' in zip %s, found %d' %
708 (filename, zipFile.filename, len(matches)))
709 return False
710 zip_path = matches[0]
711 src_path = zipFile.extract(zip_path)
712 dst_path = path(target_dir, filename)
713 mv(src_path, dst_path)
Anton Hansson9709fd42018-04-03 16:52:13 +0100714
Anton Hansson73be1512021-06-24 10:56:05 +0100715 # Filtered API DB is currently only available for "public"
716 fetch_artifacts(framework_sdk_target, build_id, {'api-versions-public-filtered.xml': path(target_dir, 'data/api-versions-filtered.xml')})
717
Alan Viverettecd3de262017-08-14 09:51:30 -0400718 return True
Alan Viverette45837092017-05-12 14:50:53 -0400719
Sundong Ahncc34cc32018-07-11 15:18:47 +0900720def update_makefile(build_id):
721 template = '"%s",\n\
722 "current"'
723 makefile = os.path.join(git_dir, 'Android.bp')
724
725 with open(makefile, 'r+') as f:
726 contents = f.read().replace('"current"', template % build_id)
727 f.seek(0)
728 f.write(contents)
729
730 return True
Alan Viverette45837092017-05-12 14:50:53 -0400731
Anton Hansson1d01a032018-04-09 10:29:37 +0100732def finalize_sdk(build_id, sdk_version):
733 target_finalize_dir = '%d' % sdk_version
Anton Hansson9709fd42018-04-03 16:52:13 +0100734
Anton Hanssonaa554c02020-04-30 14:06:20 +0100735 for api_scope in ['public', 'system', 'test', 'module-lib', 'system-server']:
Sundong Ahn66091f22018-08-29 18:54:28 +0900736 artifact_to_path = {'apistubs/android/' + api_scope + '/api/*.txt':
737 path(target_finalize_dir, api_scope, 'api', '*')}
738
739 if not fetch_artifacts(framework_sdk_target, build_id, artifact_to_path):
740 return False
741
742 return update_framework(build_id, target_finalize_dir) \
Sundong Ahncc34cc32018-07-11 15:18:47 +0900743 and update_makefile(target_finalize_dir)
Anton Hansson9709fd42018-04-03 16:52:13 +0100744
Anton Hansson9709fd42018-04-03 16:52:13 +0100745
Anton Hansson1d01a032018-04-09 10:29:37 +0100746def update_framework_current(build_id):
747 return update_framework(build_id, current_path)
Anton Hansson9709fd42018-04-03 16:52:13 +0100748
749
Alan Viverettec1c32b62017-12-20 09:40:36 -0500750def update_buildtools(target, arch, build_id):
Jeff Gaston13e38412018-02-06 14:45:36 -0500751 artifact_path = fetch_and_extract(target, build_id.url_id,
752 "sdk-repo-%s-build-tools-%s.zip" % (arch, build_id.fs_id))
Alan Viverettec1c32b62017-12-20 09:40:36 -0500753 if not artifact_path:
754 return False
755
756 top_level_dir = os.listdir(artifact_path)[0]
757 src_path = os.path.join(artifact_path, top_level_dir)
758 dst_path = path(buildtools_dir, arch)
Colin Cross20648d32021-02-12 13:30:51 -0800759
760 # There are a few libraries that have been manually added to the
761 # build tools, copy them from the destination back to the source
762 # before the destination is overwritten.
763 files_to_save = (
764 'lib64/libconscrypt_openjdk_jni.dylib',
765 'lib64/libconscrypt_openjdk_jni.so',
766 'bin/lib64/libwinpthread-1.dll',
767 )
768 for file in files_to_save:
769 src_file = os.path.join(dst_path, file)
770 dst_file = os.path.join(src_path, file)
771 if os.path.exists(dst_path):
772 mv(src_file, dst_file)
773
Alan Viverettec1c32b62017-12-20 09:40:36 -0500774 mv(src_path, dst_path)
775
776 # Move all top-level files to /bin and make them executable
777 bin_path = path(dst_path, 'bin')
778 top_level_files = filter(lambda e: os.path.isfile(path(dst_path, e)), os.listdir(dst_path))
779 for file in top_level_files:
780 src_file = path(dst_path, file)
781 dst_file = path(bin_path, file)
782 mv(src_file, dst_file)
783 os.chmod(dst_file, 0o755)
784
Colin Cross6673ceb2021-02-12 13:14:14 -0800785 # Make the files under lld-bin executable
786 lld_bin_files = os.listdir(os.path.join(dst_path, 'lld-bin'))
787 for file in lld_bin_files:
788 os.chmod(os.path.join(dst_path, 'lld-bin', file), 0o755)
789
Alan Viverettec1c32b62017-12-20 09:40:36 -0500790 # Remove renderscript
791 rm(path(dst_path, 'renderscript'))
792
793 return True
794
795
Alan Viverettecd3de262017-08-14 09:51:30 -0400796def append(text, more_text):
797 if text:
798 return "%s, %s" % (text, more_text)
799 return more_text
Alan Viverette45837092017-05-12 14:50:53 -0400800
Alan Viverette95f6d362017-04-06 09:40:50 -0400801
Jeff Gaston13e38412018-02-06 14:45:36 -0500802class buildId(object):
803 def __init__(self, url_id, fs_id):
804 # id when used in build server urls
805 self.url_id = url_id
806 # id when used in build commands
807 self.fs_id = fs_id
808
Jeff Gastonb9b09052018-02-05 14:16:05 -0500809def getBuildId(args):
Jeff Gaston13e38412018-02-06 14:45:36 -0500810 # must be in the format 12345 or P12345
Jeff Gastonb9b09052018-02-05 14:16:05 -0500811 source = args.source
Jeff Gaston13e38412018-02-06 14:45:36 -0500812 number_text = source[:]
813 presubmit = False
814 if number_text.startswith("P"):
815 presubmit = True
816 number_text = number_text[1:]
817 if not number_text.isnumeric():
Alan Viverette7e897e22018-03-09 15:24:10 -0500818 return None
Jeff Gaston13e38412018-02-06 14:45:36 -0500819 url_id = source
820 fs_id = url_id
821 if presubmit:
822 fs_id = "0"
823 args.file = False
824 return buildId(url_id, fs_id)
Jeff Gastonb9b09052018-02-05 14:16:05 -0500825
Colin Cross573e1212018-02-12 14:59:52 -0800826def getFile(args):
827 source = args.source
828 if not source.isnumeric():
829 return args.source
Alan Viverette7e897e22018-03-09 15:24:10 -0500830 return None
Colin Cross573e1212018-02-12 14:59:52 -0800831
Alan Viverette4ec9a172018-02-20 16:19:31 -0500832
833def script_relative(rel_path):
Jeff Gastona68a8d42018-03-23 14:00:13 -0400834 return os.path.join(script_dir, rel_path)
Alan Viverette4ec9a172018-02-20 16:19:31 -0500835
836
Jeff Gastoncc296a82018-03-23 14:33:24 -0400837def uncommittedChangesExist():
838 try:
839 # Make sure we don't overwrite any pending changes.
840 diffCommand = "cd " + git_dir + " && git diff --quiet"
841 subprocess.check_call(diffCommand, shell=True)
842 subprocess.check_call(diffCommand + " --cached", shell=True)
843 return False
844 except subprocess.CalledProcessError:
845 return True
846
847
Jeff Gastona7fba9b2018-03-26 23:48:51 -0400848rm(temp_dir)
Alan Viveretted4527e62017-05-11 15:03:25 -0400849parser = argparse.ArgumentParser(
Alan Viverette45837092017-05-12 14:50:53 -0400850 description=('Update current prebuilts'))
Alan Viveretted4527e62017-05-11 15:03:25 -0400851parser.add_argument(
Saeid Farivar Asanjan54cd34e2021-10-01 16:47:54 +0000852 'source', nargs='?',
Alan Viverette129555e2018-01-30 09:57:57 -0500853 help='Build server build ID or local Maven ZIP file')
854parser.add_argument(
Jeff Gaston6e7e7502018-04-04 00:22:45 -0400855 '-m', '--material', action="store_true",
Alan Viverette6dc45752020-04-16 14:56:20 +0000856 help='If specified, updates only Material Design Components')
Jeff Gaston6e7e7502018-04-04 00:22:45 -0400857parser.add_argument(
Alan Viverette3e57a4a2017-08-11 15:49:47 -0400858 '-c', '--constraint', action="store_true",
859 help='If specified, updates only Constraint Layout')
860parser.add_argument(
Jeff Gaston782c3e32018-02-06 14:36:17 -0500861 '-j', '--jetifier', action="store_true",
862 help='If specified, updates only Jetifier')
863parser.add_argument(
Alan Viverette5bfe05b2017-06-06 14:21:29 -0400864 '-p', '--platform', action="store_true",
865 help='If specified, updates only the Android Platform')
Alan Viverettec1c32b62017-12-20 09:40:36 -0500866parser.add_argument(
Anton Hansson9709fd42018-04-03 16:52:13 +0100867 '-f', '--finalize_sdk', type=int,
868 help='If specified, imports the source build as the specified finalized SDK version')
869parser.add_argument(
Alan Viverettec1c32b62017-12-20 09:40:36 -0500870 '-b', '--buildtools', action="store_true",
871 help='If specified, updates only the Build Tools')
Jeff Gastoncc296a82018-03-23 14:33:24 -0400872parser.add_argument(
Alan Viverette6dc45752020-04-16 14:56:20 +0000873 '-x', '--androidx', action="store_true",
874 help='If specified, updates only the Jetpack (androidx) libraries excluding those covered by other arguments')
Jeff Gaston41fd5e62018-04-25 17:02:02 -0400875parser.add_argument(
Saeid Farivar Asanjan54cd34e2021-10-01 16:47:54 +0000876 '-g', '--gmaven', action="store_true",
877 help='If specified, updates only the artifact from GMaven libraries excluding those covered by other arguments')
878parser.add_argument(
Jeff Gastoncc296a82018-03-23 14:33:24 -0400879 '--commit-first', action="store_true",
880 help='If specified, then if uncommited changes exist, commit before continuing')
Jeff Sharkeyabe16df2021-05-25 10:09:03 -0600881parser.add_argument(
882 '--beyond-corp', action="store_true",
883 help='If specified, then fetch artifacts with tooling that works on BeyondCorp devices')
Alan Viveretted4527e62017-05-11 15:03:25 -0400884args = parser.parse_args()
Jeff Gaston56fe2762018-02-06 14:54:37 -0500885args.file = True
Saeid Farivar Asanjan54cd34e2021-10-01 16:47:54 +0000886if not args.source and (args.platform or args.buildtools \
887 or args.jetifier or args.androidx or args.material \
888 or args.finalize_sdk or args.constraint):
Alan Viverette129555e2018-01-30 09:57:57 -0500889 parser.error("You must specify a build ID or local Maven ZIP file")
Alan Viveretted4527e62017-05-11 15:03:25 -0400890 sys.exit(1)
Saeid Farivar Asanjan54cd34e2021-10-01 16:47:54 +0000891if not (args.gmaven or args.platform or args.buildtools \
Alan Viverette6dc45752020-04-16 14:56:20 +0000892 or args.jetifier or args.androidx or args.material \
893 or args.finalize_sdk or args.constraint):
Alan Viverettec1c32b62017-12-20 09:40:36 -0500894 parser.error("You must specify at least one target to update")
Alan Viverettecd3de262017-08-14 09:51:30 -0400895 sys.exit(1)
Saeid Farivar Asanjan54cd34e2021-10-01 16:47:54 +0000896if (args.constraint or args.material or args.androidx or args.gmaven) \
Colin Cross74683bc2018-04-11 17:36:18 -0700897 and which('pom2bp') is None:
Louis Pullen-Freilich61bb70e2019-04-09 16:15:32 +0100898 parser.error("Cannot find pom2bp in path; please run lunch to set up build environment. You may also need to run 'm pom2bp' if it hasn't been built already.")
Alan Viverettef5cb0e62017-11-17 15:15:23 -0500899 sys.exit(1)
Alan Viveretted4527e62017-05-11 15:03:25 -0400900
Jeff Gastoncc296a82018-03-23 14:33:24 -0400901if uncommittedChangesExist():
902 if args.commit_first:
903 subprocess.check_call("cd " + git_dir + " && git add -u", shell=True)
904 subprocess.check_call("cd " + git_dir + " && git commit -m 'save working state'", shell=True)
905
906if uncommittedChangesExist():
Anton Hansson10861a02018-04-06 13:57:08 +0100907 print_e('FAIL: There are uncommitted changes here. Please commit or stash before continuing, because %s will run "git reset --hard" if execution fails' % os.path.basename(__file__))
Alan Viveretted4527e62017-05-11 15:03:25 -0400908 sys.exit(1)
909
910try:
Alan Viverettecd3de262017-08-14 09:51:30 -0400911 components = None
912 if args.constraint:
Jeff Gaston9edf86c2018-04-18 13:45:23 -0400913 if update_constraint_x(getFile(args)):
914 components = append(components, 'Constraint Layout X')
915 else:
916 print_e('Failed to update Constraint Layout X, aborting...')
Alan Viverettecd3de262017-08-14 09:51:30 -0400917 sys.exit(1)
Saeid Farivar Asanjan54cd34e2021-10-01 16:47:54 +0000918 if args.gmaven:
919 updated_artifacts = update_gmaven(gmaven_artifacts)
920 if updated_artifacts:
921 components = append(components, '\n'.join(updated_artifacts))
922 else:
923 print_e('Failed to update GMaven, aborting...')
924 sys.exit(1)
Jeff Gastonbbd6bfc2018-03-27 17:35:49 -0400925 if args.androidx:
Jeff Gaston17ccf8f2018-08-29 11:33:19 -0400926 if update_androidx('androidx', \
Jeff Gastonbbd6bfc2018-03-27 17:35:49 -0400927 getBuildId(args), getFile(args)):
928 components = append(components, 'AndroidX')
929 else:
930 print_e('Failed to update AndroidX, aborting...')
931 sys.exit(1)
Jeff Gaston782c3e32018-02-06 14:36:17 -0500932 if args.jetifier:
Jeff Gaston17ccf8f2018-08-29 11:33:19 -0400933 if update_jetifier('androidx', getBuildId(args)):
Jeff Gaston782c3e32018-02-06 14:36:17 -0500934 components = append(components, 'Jetifier')
935 else:
936 print_e('Failed to update Jetifier, aborting...')
937 sys.exit(1)
Anton Hanssonbe15e8c2018-04-26 17:35:45 +0100938 if args.platform or args.finalize_sdk:
Anton Hansson87654c42018-04-26 15:19:42 +0100939 if update_framework_current(getBuildId(args)):
Alan Viverettecd3de262017-08-14 09:51:30 -0400940 components = append(components, 'platform SDK')
941 else:
Alan Viverettef5cb0e62017-11-17 15:15:23 -0500942 print_e('Failed to update platform SDK, aborting...')
Alan Viverettecd3de262017-08-14 09:51:30 -0400943 sys.exit(1)
Anton Hansson9709fd42018-04-03 16:52:13 +0100944 if args.finalize_sdk:
Anton Hanssonbe15e8c2018-04-26 17:35:45 +0100945 n = args.finalize_sdk
946 if finalize_sdk(getBuildId(args), n):
947 # We commit the finalized dir separately from the current sdk update.
948 msg = "Import final sdk version %d from build %s" % (n, getBuildId(args).url_id)
949 subprocess.check_call(['git', 'add', '%d' % n])
Sundong Ahncc34cc32018-07-11 15:18:47 +0900950 subprocess.check_call(['git', 'add', 'Android.bp'])
Anton Hanssonbe15e8c2018-04-26 17:35:45 +0100951 subprocess.check_call(['git', 'commit', '-m', msg])
Anton Hansson9709fd42018-04-03 16:52:13 +0100952 else:
Anton Hanssonbe15e8c2018-04-26 17:35:45 +0100953 print_e('Failed to finalize SDK %d, aborting...' % n)
Anton Hansson9709fd42018-04-03 16:52:13 +0100954 sys.exit(1)
Jeff Gaston6e7e7502018-04-04 00:22:45 -0400955 if args.material:
956 if update_material(getFile(args)):
957 components = append(components, 'intermediate-AndroidX Design Library')
958 else:
959 print_e('Failed to update intermediate-AndroidX Design Library, aborting...')
Alan Viverette129555e2018-01-30 09:57:57 -0500960 sys.exit(1)
Alan Viverettec1c32b62017-12-20 09:40:36 -0500961 if args.buildtools:
Jeff Gastonb9b09052018-02-05 14:16:05 -0500962 if update_buildtools('sdk_phone_armv7-sdk_mac', 'darwin', getBuildId(args)) \
963 and update_buildtools('sdk_phone_x86_64-sdk', 'linux', getBuildId(args)) \
964 and update_buildtools('sdk_phone_armv7-win_sdk', 'windows', getBuildId(args)):
Alan Viverettec1c32b62017-12-20 09:40:36 -0500965 components = append(components, 'build tools')
966 else:
967 print_e('Failed to update build tools, aborting...')
968 sys.exit(1)
Jeff Gastonb70daa92018-03-29 20:10:22 -0400969
Jeff Gastonf12f3ce2018-03-23 16:41:24 -0400970
Alan Viveretted4527e62017-05-11 15:03:25 -0400971
Colin Cross941d9802018-05-03 21:37:57 -0700972 subprocess.check_call(['git', 'add', current_path, buildtools_dir])
Saeid Farivar Asanjan54cd34e2021-10-01 16:47:54 +0000973 if not args.source and args.gmaven:
974 src_msg = "GMaven"
975 elif not args.source.isnumeric():
Alan Viverette129555e2018-01-30 09:57:57 -0500976 src_msg = "local Maven ZIP"
977 else:
Jeff Gaston13e38412018-02-06 14:45:36 -0500978 src_msg = "build %s" % (getBuildId(args).url_id)
Alan Viverette129555e2018-01-30 09:57:57 -0500979 msg = "Import %s from %s\n\n%s" % (components, src_msg, flatten(sys.argv))
Alan Viveretted4527e62017-05-11 15:03:25 -0400980 subprocess.check_call(['git', 'commit', '-m', msg])
Anton Hanssonbe15e8c2018-04-26 17:35:45 +0100981 if args.finalize_sdk:
982 print('NOTE: Created two commits:')
983 subprocess.check_call(['git', 'log', '-2', '--oneline'])
Alan Viverettef5cb0e62017-11-17 15:15:23 -0500984 print('Remember to test this change before uploading it to Gerrit!')
Alan Viveretted4527e62017-05-11 15:03:25 -0400985
986finally:
987 # Revert all stray files, including the downloaded zip.
988 try:
989 with open(os.devnull, 'w') as bitbucket:
990 subprocess.check_call(['git', 'add', '-Af', '.'], stdout=bitbucket)
991 subprocess.check_call(
Jeff Gaston9edf86c2018-04-18 13:45:23 -0400992 ['git', 'commit', '-m', 'COMMIT TO REVERT - RESET ME!!!', '--allow-empty'], stdout=bitbucket)
Alan Viveretted4527e62017-05-11 15:03:25 -0400993 subprocess.check_call(['git', 'reset', '--hard', 'HEAD~1'], stdout=bitbucket)
994 except subprocess.CalledProcessError:
Alan Viverettef5cb0e62017-11-17 15:15:23 -0500995 print_e('ERROR: Failed cleaning up, manual cleanup required!!!')