blob: 9b183ebbea049b8f686db02d16e238330b97732c [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
Anton Hansson4bcebac2022-04-07 17:23:18 +010013from pathlib import Path
Saeid Farivar Asanjan54cd34e2021-10-01 16:47:54 +000014import six
15import urllib.request, urllib.parse, urllib.error
Alan Viverette95f6d362017-04-06 09:40:50 -040016
Alan Viverette45837092017-05-12 14:50:53 -040017current_path = 'current'
Andy Wickhamc3c99af2020-10-26 20:47:58 +000018framework_sdk_target = 'sdk_phone_armv7-win_sdk'
Jeff Gastonbbd6bfc2018-03-27 17:35:49 -040019androidx_dir = os.path.join(current_path, 'androidx')
Saeid Farivar Asanjan54cd34e2021-10-01 16:47:54 +000020gmaven_dir = os.path.join(current_path, 'gmaven')
Alan Viverette3e57a4a2017-08-11 15:49:47 -040021extras_dir = os.path.join(current_path, 'extras')
Alan Viverettec1c32b62017-12-20 09:40:36 -050022buildtools_dir = 'tools'
Jeff Gaston553a4372018-03-29 18:34:22 -040023jetifier_dir = os.path.join(buildtools_dir, 'jetifier', 'jetifier-standalone')
Anton Hansson4bcebac2022-04-07 17:23:18 +010024repo_root_dir = Path(sys.argv[0]).resolve().parents[3]
25extension_sdk_finalization_cmd = '%s -b {bug} -f {extension_version} {build_id}' % (
26 "packages/modules/common/tools/finalize_sdk.py"
27)
Jeff Gastona68a8d42018-03-23 14:00:13 -040028temp_dir = os.path.join(os.getcwd(), "support_tmp")
29os.chdir(os.path.dirname(os.path.dirname(os.path.realpath(sys.argv[0]))))
30git_dir = os.getcwd()
31
Alan Viverettecd3de262017-08-14 09:51:30 -040032# See go/fetch_artifact for details on this script.
Alan Viveretted4527e62017-05-11 15:03:25 -040033FETCH_ARTIFACT = '/google/data/ro/projects/android/fetch_artifact'
Jeff Sharkeyabe16df2021-05-25 10:09:03 -060034FETCH_ARTIFACT_BEYOND_CORP = '/usr/bin/fetch_artifact'
Alan Viveretted4527e62017-05-11 15:03:25 -040035
Saeid Farivar Asanjan54cd34e2021-10-01 16:47:54 +000036# See (https://developer.android.com/studio/build/dependencies#gmaven-access)
37GMAVEN_BASE_URL = 'https://maven.google.com'
38
Alan Viverette0723aff2021-08-31 17:07:47 +000039# Leave map blank to automatically populate name and path:
40# - Name format is MAVEN.replaceAll(':','_')
41# - Path format is MAVEN.replaceAll(':','/').replaceAll('.','/')
Alan Viverette95f6d362017-04-06 09:40:50 -040042maven_to_make = {
Jeff Gastonbbd6bfc2018-03-27 17:35:49 -040043 # AndroidX
Alan Viverettef3c12722021-08-30 19:50:33 +000044 'androidx.benchmark:benchmark-macro': { },
45 'androidx.benchmark:benchmark-macro-junit4': { },
46 'androidx.benchmark:benchmark-common': { },
47 'androidx.benchmark:benchmark-junit4': { },
48 'androidx.tracing:tracing': { },
49 'androidx.tracing:tracing-ktx': { },
50 'androidx.slice:slice-builders': { },
51 'androidx.slice:slice-core': { },
52 'androidx.slice:slice-view': { },
53 'androidx.remotecallback:remotecallback': { },
Alan Viverette0723aff2021-08-31 17:07:47 +000054 'androidx.remotecallback:remotecallback-processor': {'host':True},
55 'androidx.versionedparcelable:versionedparcelable': { },
Alan Viverettef3c12722021-08-30 19:50:33 +000056 'androidx.vectordrawable:vectordrawable-animated': { },
57 'androidx.activity:activity': { },
58 'androidx.activity:activity-ktx': { },
Alan Viverette0723aff2021-08-31 17:07:47 +000059 'androidx.annotation:annotation': {'host_and_device':True},
Alan Viverettef3c12722021-08-30 19:50:33 +000060 'androidx.annotation:annotation-experimental': { },
61 'androidx.asynclayoutinflater:asynclayoutinflater': { },
62 'androidx.collection:collection': { },
63 'androidx.collection:collection-ktx': { },
64 'androidx.concurrent:concurrent-futures': { },
65 'androidx.concurrent:concurrent-listenablefuture-callback': { },
66 'androidx.concurrent:concurrent-listenablefuture': { },
67 'androidx.core:core': { },
68 'androidx.core:core-animation': { },
69 'androidx.core:core-ktx': { },
70 'androidx.contentpaging:contentpaging': { },
71 'androidx.coordinatorlayout:coordinatorlayout': { },
72 'androidx.legacy:legacy-support-core-ui': { },
73 'androidx.legacy:legacy-support-core-utils': { },
74 'androidx.cursoradapter:cursoradapter': { },
75 'androidx.browser:browser': { },
76 'androidx.customview:customview': { },
77 'androidx.documentfile:documentfile': { },
78 'androidx.drawerlayout:drawerlayout': { },
79 'androidx.dynamicanimation:dynamicanimation': { },
80 'androidx.emoji:emoji': { },
81 'androidx.emoji:emoji-appcompat': { },
82 'androidx.emoji:emoji-bundled': { },
83 'androidx.emoji2:emoji2': { },
84 'androidx.emoji2:emoji2-views-helper': { },
85 'androidx.exifinterface:exifinterface': { },
86 'androidx.fragment:fragment': { },
87 'androidx.fragment:fragment-ktx': { },
88 'androidx.heifwriter:heifwriter': { },
89 'androidx.interpolator:interpolator': { },
90 'androidx.loader:loader': { },
Alan Viverettef3c12722021-08-30 19:50:33 +000091 'androidx.media:media': { },
92 'androidx.media2:media2-player': { },
93 'androidx.media2:media2-session': { },
94 'androidx.media2:media2-common': { },
95 'androidx.media2:media2-exoplayer': { },
96 'androidx.media2:media2-widget': { },
97 'androidx.navigation:navigation-common': { },
98 'androidx.navigation:navigation-common-ktx': { },
99 'androidx.navigation:navigation-fragment': { },
100 'androidx.navigation:navigation-fragment-ktx': { },
101 'androidx.navigation:navigation-runtime': { },
102 'androidx.navigation:navigation-runtime-ktx': { },
103 'androidx.navigation:navigation-ui': { },
104 'androidx.navigation:navigation-ui-ktx': { },
105 'androidx.percentlayout:percentlayout': { },
106 'androidx.print:print': { },
107 'androidx.recommendation:recommendation': { },
108 'androidx.recyclerview:recyclerview-selection': { },
109 'androidx.savedstate:savedstate': { },
110 'androidx.savedstate:savedstate-ktx': { },
111 'androidx.slidingpanelayout:slidingpanelayout': { },
112 'androidx.swiperefreshlayout:swiperefreshlayout': { },
113 'androidx.textclassifier:textclassifier': { },
114 'androidx.transition:transition': { },
115 'androidx.tvprovider:tvprovider': { },
116 'androidx.legacy:legacy-support-v13': { },
117 'androidx.legacy:legacy-preference-v14': { },
118 'androidx.leanback:leanback': { },
119 'androidx.leanback:leanback-preference': { },
120 'androidx.legacy:legacy-support-v4': { },
121 'androidx.appcompat:appcompat': { },
122 'androidx.appcompat:appcompat-resources': { },
123 'androidx.cardview:cardview': { },
124 'androidx.gridlayout:gridlayout': { },
125 'androidx.mediarouter:mediarouter': { },
126 'androidx.palette:palette': { },
127 'androidx.preference:preference': { },
128 'androidx.recyclerview:recyclerview': { },
129 'androidx.vectordrawable:vectordrawable': { },
130 'androidx.viewpager:viewpager': { },
131 'androidx.viewpager2:viewpager2': { },
132 'androidx.wear:wear': { },
133 'androidx.wear:wear-ongoing': { },
134 'androidx.webkit:webkit': { },
135 'androidx.biometric:biometric': { },
136 'androidx.autofill:autofill': { },
137 'androidx.appsearch:appsearch': { },
Alan Viverette0723aff2021-08-31 17:07:47 +0000138 'androidx.appsearch:appsearch-local-storage': {'name':'androidx.appsearch_appsearch_local_storage'},
139 'androidx.appsearch:appsearch-platform-storage': { },
140 'androidx.appsearch:appsearch-compiler': {'name':'androidx.appsearch_appsearch-compiler', 'host':True},
Alan Viverettef3c12722021-08-30 19:50:33 +0000141 'androidx.car.app:app': { },
142 'androidx.car.app:app-automotive': { },
143 'androidx.car.app:app-testing': { },
144 'androidx.startup:startup-runtime': { },
Alan Viverettecdfc9892021-08-31 19:35:58 +0000145 'androidx.window:window': {'optional-uses-libs':{'androidx.window.extensions', 'androidx.window.sidecar'}},
Alan Viverettef3c12722021-08-30 19:50:33 +0000146 'androidx.resourceinspection:resourceinspection-annotation': { },
147 'androidx.profileinstaller:profileinstaller': { },
Aurimas Liutikas6e87bbf2021-07-30 10:04:05 -0700148
Alan Viverettef44e2f92021-08-31 17:26:26 +0000149 # AndroidX for Compose
Colin Cross58866d42021-09-17 14:40:35 -0700150 'androidx.compose.compiler:compiler-hosted': { 'host':True },
Alan Viverettef44e2f92021-08-31 17:26:26 +0000151 'androidx.compose.runtime:runtime': { },
152 'androidx.compose.runtime:runtime-saveable': { },
153 'androidx.compose.foundation:foundation': { },
154 'androidx.compose.foundation:foundation-layout': { },
155 'androidx.compose.foundation:foundation-text': { },
156 'androidx.compose.ui:ui': { },
157 'androidx.compose.ui:ui-geometry': { },
158 'androidx.compose.ui:ui-graphics': { },
159 'androidx.compose.ui:ui-text': { },
160 'androidx.compose.ui:ui-unit': { },
161 'androidx.compose.ui:ui-util': { },
162 'androidx.compose.animation:animation-core': { },
163 'androidx.compose.animation:animation': { },
164 'androidx.compose.material:material-icons-core': { },
165 'androidx.compose.material:material-ripple': { },
166 'androidx.compose.material:material': { },
167 'androidx.activity:activity-compose': { },
168
Jeff Gastonbbd6bfc2018-03-27 17:35:49 -0400169 # AndroidX for Multidex
Alan Viverette0723aff2021-08-31 17:07:47 +0000170 'androidx.multidex:multidex': { },
171 'androidx.multidex:multidex-instrumentation': { },
Jeff Gastonbbd6bfc2018-03-27 17:35:49 -0400172
173 # AndroidX for Constraint Layout
Alan Viverette0723aff2021-08-31 17:07:47 +0000174 'androidx.constraintlayout:constraintlayout': {'name':'androidx-constraintlayout_constraintlayout'},
175 'androidx.constraintlayout:constraintlayout-solver': {'name':'androidx-constraintlayout_constraintlayout-solver'},
Jeff Gastonbbd6bfc2018-03-27 17:35:49 -0400176
177 # AndroidX for Architecture Components
Alan Viverettef3c12722021-08-30 19:50:33 +0000178 'androidx.arch.core:core-common': { },
179 'androidx.arch.core:core-runtime': { },
180 'androidx.lifecycle:lifecycle-common': { },
181 'androidx.lifecycle:lifecycle-common-java8': { },
182 'androidx.lifecycle:lifecycle-extensions': { },
183 'androidx.lifecycle:lifecycle-livedata': { },
184 'androidx.lifecycle:lifecycle-livedata-ktx': { },
185 'androidx.lifecycle:lifecycle-livedata-core': { },
186 'androidx.lifecycle:lifecycle-livedata-core-ktx': { },
187 'androidx.lifecycle:lifecycle-process': { },
188 'androidx.lifecycle:lifecycle-runtime': { },
189 'androidx.lifecycle:lifecycle-runtime-ktx': { },
190 'androidx.lifecycle:lifecycle-service': { },
191 'androidx.lifecycle:lifecycle-viewmodel': { },
192 'androidx.lifecycle:lifecycle-viewmodel-ktx': { },
193 'androidx.lifecycle:lifecycle-viewmodel-savedstate': { },
194 'androidx.paging:paging-common': { },
195 'androidx.paging:paging-common-ktx': { },
196 'androidx.paging:paging-runtime': { },
197 'androidx.sqlite:sqlite': { },
198 'androidx.sqlite:sqlite-framework': { },
Alan Viverette0723aff2021-08-31 17:07:47 +0000199 'androidx.room:room-common': {'host_and_device':True},
Alan Viverettecdfc9892021-08-31 19:35:58 +0000200 'androidx.room:room-compiler': {'host':True, 'extra-static-libs':{'guava-21.0'}},
Alan Viverette0723aff2021-08-31 17:07:47 +0000201 'androidx.room:room-migration': {'host_and_device':True},
Alan Viverettef3c12722021-08-30 19:50:33 +0000202 'androidx.room:room-runtime': { },
203 'androidx.room:room-testing': { },
Alan Viverette0723aff2021-08-31 17:07:47 +0000204 'androidx.room:room-compiler-processing': {'host':True},
Alan Viverettef3c12722021-08-30 19:50:33 +0000205 'androidx.work:work-runtime': { },
206 'androidx.work:work-runtime-ktx': { },
207 'androidx.work:work-testing': { },
Allenab72f012018-01-29 18:10:23 -0800208
Jeff Gaston6e7e7502018-04-04 00:22:45 -0400209 # Third-party dependencies
Jeff Gastona0bce602018-08-24 14:05:03 -0400210 'com.google.android:flexbox': {'name':'flexbox', 'path':'flexbox'},
Jeff Gaston6e7e7502018-04-04 00:22:45 -0400211
Jeff Gastonfa7c7e82018-04-06 13:35:48 -0400212 # Androidx Material Design Components
Alan Viverettef3c12722021-08-30 19:50:33 +0000213 'com.google.android.material:material': { },
Alan Viverette95f6d362017-04-06 09:40:50 -0400214}
215
Alan Viverettecdfc9892021-08-31 19:35:58 +0000216# Mapping of POM dependencies to Soong build targets
217deps_rewrite = {
218 'auto-common':'auto_common',
219 'auto-value-annotations':'auto_value_annotations',
220 'com.google.auto.value:auto-value':'auto_value_plugin',
221 'monitor':'androidx.test.monitor',
222 'rules':'androidx.test.rules',
223 'runner':'androidx.test.runner',
224 'androidx.test:core':'androidx.test.core',
225 'com.squareup:javapoet':'javapoet',
226 'com.google.guava:listenablefuture':'guava-listenablefuture-prebuilt-jar',
227 'sqlite-jdbc':'xerial-sqlite-jdbc',
228 'gson':'gson-prebuilt-jar',
229 'com.intellij:annotations':'jetbrains-annotations',
230 'javax.annotation:javax.annotation-api':'javax-annotation-api-prebuilt-host-jar',
231 'org.robolectric:robolectric':'Robolectric_all-target',
232 'org.jetbrains.kotlin:kotlin-stdlib-common':'kotlin-stdlib',
233 'org.jetbrains.kotlinx:kotlinx-coroutines-core':'kotlinx_coroutines',
234 'org.jetbrains.kotlinx:kotlinx-coroutines-android':'kotlinx_coroutines_android',
235 'org.jetbrains.kotlinx:kotlinx-metadata-jvm':'kotlinx_metadata_jvm',
236}
237
Saeid Farivar Asanjan54cd34e2021-10-01 16:47:54 +0000238# List of artifacts that will be updated from GMaven
239# Use pattern: `group:library:version:extension`
240# e.g.:
241# androidx.appcompat:appcompat:1.2.0:aar
242# Use `latest` to always fetch the latest version.
243# e.g.:
244# androidx.appcompat:appcompat:latest:aar
245# Also make sure you add `group:library`:{} to maven_to_make as well.
246gmaven_artifacts = {}
Alan Viverettef3c12722021-08-30 19:50:33 +0000247
248def name_for_artifact(group_artifact):
249 return group_artifact.replace(':','_')
250
251
252def path_for_artifact(group_artifact):
253 return group_artifact.replace('.','/').replace(':','/')
254
255
256# Add automatic entries to maven_to_make.
257for key in maven_to_make:
258 if ('name' not in maven_to_make[key]):
259 maven_to_make[key]['name'] = name_for_artifact(key)
260 if ('path' not in maven_to_make[key]):
261 maven_to_make[key]['path'] = path_for_artifact(key)
262
Alan Viverette95f6d362017-04-06 09:40:50 -0400263# Always remove these files.
264blacklist_files = [
265 'annotations.zip',
266 'public.txt',
267 'R.txt',
Alan Viverette44ad4e42017-08-09 17:45:00 -0400268 'AndroidManifest.xml',
Alan Viverettef48d9b42017-08-17 14:45:46 -0400269 os.path.join('libs','noto-emoji-compat-java.jar')
Alan Viverette95f6d362017-04-06 09:40:50 -0400270]
271
Alan Viverette44ad4e42017-08-09 17:45:00 -0400272artifact_pattern = re.compile(r"^(.+?)-(\d+\.\d+\.\d+(?:-\w+\d+)?(?:-[\d.]+)*)\.(jar|aar)$")
Alan Viverette95f6d362017-04-06 09:40:50 -0400273
Alan Viverettec960cfb2017-12-04 13:09:22 -0500274
275class MavenLibraryInfo:
Jeff Gastonc302bb92018-03-23 13:53:48 -0400276 def __init__(self, key, group_id, artifact_id, version, dir, repo_dir, file):
Alan Viverettec960cfb2017-12-04 13:09:22 -0500277 self.key = key
278 self.group_id = group_id
279 self.artifact_id = artifact_id
280 self.version = version
Jeff Gastonc302bb92018-03-23 13:53:48 -0400281 self.dir = dir
Alan Viverettec960cfb2017-12-04 13:09:22 -0500282 self.repo_dir = repo_dir
283 self.file = file
284
285
Alan Viverettef5cb0e62017-11-17 15:15:23 -0500286def print_e(*args, **kwargs):
287 print(*args, file=sys.stderr, **kwargs)
288
Alan Viverette95f6d362017-04-06 09:40:50 -0400289
290def touch(fname, times=None):
291 with open(fname, 'a'):
292 os.utime(fname, times)
293
294
Alan Viverette45837092017-05-12 14:50:53 -0400295def path(*path_parts):
296 return reduce((lambda x, y: os.path.join(x, y)), path_parts)
297
298
Alan Viverettecd3de262017-08-14 09:51:30 -0400299def flatten(list):
300 return reduce((lambda x, y: "%s %s" % (x, y)), list)
301
302
Alan Viverette45837092017-05-12 14:50:53 -0400303def rm(path):
304 if os.path.isdir(path):
305 rmtree(path)
306 elif os.path.exists(path):
307 os.remove(path)
308
309
310def mv(src_path, dst_path):
Alan Viverette3e57a4a2017-08-11 15:49:47 -0400311 if os.path.exists(dst_path):
Alan Viverettecd3de262017-08-14 09:51:30 -0400312 rm(dst_path)
Alan Viverette3e57a4a2017-08-11 15:49:47 -0400313 if not os.path.exists(os.path.dirname(dst_path)):
314 os.makedirs(os.path.dirname(dst_path))
Jiyong Park1d1c9632018-05-29 17:45:27 +0900315 for f in (glob.glob(src_path)):
316 if '*' in dst_path:
317 dst = os.path.join(os.path.dirname(dst_path), os.path.basename(f))
318 else:
319 dst = dst_path
shepshaparde4127cf2019-09-03 16:08:44 -0700320 move(f, dst)
Alan Viverette45837092017-05-12 14:50:53 -0400321
322
Jeff Gastonc302bb92018-03-23 13:53:48 -0400323def detect_artifacts(maven_repo_dirs):
Alan Viveretted4527e62017-05-11 15:03:25 -0400324 maven_lib_info = {}
325
Dan Willemsen814152e2017-11-06 13:22:11 -0800326 # Find the latest revision for each artifact, remove others
Jeff Gastonc302bb92018-03-23 13:53:48 -0400327 for repo_dir in maven_repo_dirs:
Dan Willemsen814152e2017-11-06 13:22:11 -0800328 for root, dirs, files in os.walk(repo_dir):
329 for file in files:
Alan Viverettec960cfb2017-12-04 13:09:22 -0500330 if file[-4:] == ".pom":
331 # Read the POM (hack hack hack).
332 group_id = ''
333 artifact_id = ''
334 version = ''
335 file = os.path.join(root, file)
336 with open(file) as pom_file:
337 for line in pom_file:
338 if line[:11] == ' <groupId>':
339 group_id = line[11:-11]
340 elif line[:14] == ' <artifactId>':
341 artifact_id = line[14:-14]
342 elif line[:11] == ' <version>':
343 version = line[11:-11]
344 if group_id == '' or artifact_id == '' or version == '':
345 print_e('Failed to find Maven artifact data in ' + file)
346 continue
Alan Viverette95f6d362017-04-06 09:40:50 -0400347
Alan Viverettec960cfb2017-12-04 13:09:22 -0500348 # Locate the artifact.
349 artifact_file = file[:-4]
350 if os.path.exists(artifact_file + '.jar'):
351 artifact_file = artifact_file + '.jar'
352 elif os.path.exists(artifact_file + '.aar'):
353 artifact_file = artifact_file + '.aar'
354 else:
355 print_e('Failed to find artifact for ' + artifact_file)
356 continue
357
358 # Make relative to root.
359 artifact_file = artifact_file[len(root) + 1:]
360
361 # Find the mapping.
362 group_artifact = group_id + ':' + artifact_id
Jeff Gaston3e622ba2018-03-26 23:24:46 -0400363 if group_artifact in maven_to_make:
Alan Viverettec960cfb2017-12-04 13:09:22 -0500364 key = group_artifact
Jeff Gaston3e622ba2018-03-26 23:24:46 -0400365 elif artifact_id in maven_to_make:
366 key = artifact_id
Alan Viverettec960cfb2017-12-04 13:09:22 -0500367 else:
Alan Viverettecdfc9892021-08-31 19:35:58 +0000368 # No mapping entry, skip this library.
Alan Viverettec960cfb2017-12-04 13:09:22 -0500369 continue
370
371 # Store the latest version.
372 version = LooseVersion(version)
373 if key not in maven_lib_info \
374 or version > maven_lib_info[key].version:
375 maven_lib_info[key] = MavenLibraryInfo(key, group_id, artifact_id, version,
376 root, repo_dir, artifact_file)
Alan Viverette95f6d362017-04-06 09:40:50 -0400377
Alan Viverette3e57a4a2017-08-11 15:49:47 -0400378 return maven_lib_info
379
380
Colin Cross59b59db2018-04-24 13:58:05 -0700381def transform_maven_repos(maven_repo_dirs, transformed_dir, extract_res=True, include_static_deps=True):
Alan Viverette3e57a4a2017-08-11 15:49:47 -0400382 cwd = os.getcwd()
383
384 # Use a temporary working directory.
Jeff Gastonc302bb92018-03-23 13:53:48 -0400385 maven_lib_info = detect_artifacts(maven_repo_dirs)
Jeff Gastona68a8d42018-03-23 14:00:13 -0400386 working_dir = temp_dir
Alan Viverette3e57a4a2017-08-11 15:49:47 -0400387
Alan Viverettec960cfb2017-12-04 13:09:22 -0500388 if not maven_lib_info:
389 print_e('Failed to detect artifacts')
390 return False
391
Jeff Gastonc302bb92018-03-23 13:53:48 -0400392 # extract some files (for example, AndroidManifest.xml) from any relevant artifacts
Alan Viveretted4527e62017-05-11 15:03:25 -0400393 for info in maven_lib_info.values():
Alan Viveretted8ce7222017-12-11 17:24:43 -0500394 transform_maven_lib(working_dir, info, extract_res)
Dan Willemsen814152e2017-11-06 13:22:11 -0800395
Colin Cross74683bc2018-04-11 17:36:18 -0700396 # generate a single Android.bp that specifies to use all of the above artifacts
397 makefile = os.path.join(working_dir, 'Android.bp')
Alan Viverette4ec9a172018-02-20 16:19:31 -0500398 with open(makefile, 'w') as f:
Anton Hanssonbd2021c2021-04-06 19:21:34 +0000399 args = ["pom2bp"]
Aurimas Liutikas6e87bbf2021-07-30 10:04:05 -0700400 args.extend(["-sdk-version", "31"])
Anton Hanssonbd2021c2021-04-06 19:21:34 +0000401 args.extend(["-default-min-sdk-version", "24"])
Jeff Gaston1cc06092018-03-28 15:51:02 -0400402 if include_static_deps:
403 args.append("-static-deps")
Jeff Gaston54868ee2018-04-25 19:43:35 -0400404 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 -0400405 args.extend(["-rewrite=^" + name + "$=" + maven_to_make[name]['name'] for name in rewriteNames])
Alan Viverettecdfc9892021-08-31 19:35:58 +0000406 args.extend(["-rewrite=^" + key + "$=" + value for key, value in deps_rewrite.items()])
407 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]])
408 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 -0400409 args.extend(["-host=" + name for name in maven_to_make if maven_to_make[name].get('host')])
Tony Mak0f658752019-07-19 11:11:05 +0100410 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 -0400411 args.extend(["."])
Dan Willemsen814152e2017-11-06 13:22:11 -0800412 subprocess.check_call(args, stdout=f, cwd=working_dir)
Alan Viverette95f6d362017-04-06 09:40:50 -0400413
414 # Replace the old directory.
Jeff Gastonc302bb92018-03-23 13:53:48 -0400415 output_dir = os.path.join(cwd, transformed_dir)
Alan Viverette3e57a4a2017-08-11 15:49:47 -0400416 mv(working_dir, output_dir)
Alan Viverettec960cfb2017-12-04 13:09:22 -0500417 return True
Alan Viverette95f6d362017-04-06 09:40:50 -0400418
Jeff Gastonc302bb92018-03-23 13:53:48 -0400419# 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 -0500420def transform_maven_lib(working_dir, artifact_info, extract_res):
Dan Willemsen814152e2017-11-06 13:22:11 -0800421 # Move library into working dir
Jeff Gaston9edf86c2018-04-18 13:45:23 -0400422 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 -0400423 mv(artifact_info.dir, new_dir)
Dan Willemsen814152e2017-11-06 13:22:11 -0800424
Alan Viverettec960cfb2017-12-04 13:09:22 -0500425 matcher = artifact_pattern.match(artifact_info.file)
426 maven_lib_name = artifact_info.key
Alan Viveretted4527e62017-05-11 15:03:25 -0400427 maven_lib_vers = matcher.group(2)
Alan Viverettec960cfb2017-12-04 13:09:22 -0500428 maven_lib_type = artifact_info.file[-3:]
Alan Viveretted4527e62017-05-11 15:03:25 -0400429
Alan Viverettef3c12722021-08-30 19:50:33 +0000430 group_artifact = artifact_info.key
431 make_lib_name = maven_to_make[group_artifact]['name']
432 make_dir_name = maven_to_make[group_artifact]['path']
Alan Viveretted4527e62017-05-11 15:03:25 -0400433
Alan Viverette129555e2018-01-30 09:57:57 -0500434 artifact_file = os.path.join(new_dir, artifact_info.file)
435
Colin Cross59b59db2018-04-24 13:58:05 -0700436 if maven_lib_type == "aar":
437 if extract_res:
438 target_dir = os.path.join(working_dir, make_dir_name)
439 if not os.path.exists(target_dir):
440 os.makedirs(target_dir)
Dan Willemsen814152e2017-11-06 13:22:11 -0800441
Alan Viverettec960cfb2017-12-04 13:09:22 -0500442 process_aar(artifact_file, target_dir)
Alan Viveretted4527e62017-05-11 15:03:25 -0400443
Colin Cross59b59db2018-04-24 13:58:05 -0700444 with zipfile.ZipFile(artifact_file) as zip:
445 manifests_dir = os.path.join(working_dir, "manifests")
446 zip.extract("AndroidManifest.xml", os.path.join(manifests_dir, make_lib_name))
Dan Willemsend677b602017-11-08 22:13:17 -0800447
Alan Viverettef5cb0e62017-11-17 15:15:23 -0500448 print(maven_lib_vers, ":", maven_lib_name, "->", make_lib_name)
Alan Viveretted4527e62017-05-11 15:03:25 -0400449
Alan Viverette95f6d362017-04-06 09:40:50 -0400450
Alan Viverettec960cfb2017-12-04 13:09:22 -0500451def process_aar(artifact_file, target_dir):
Alan Viverette95f6d362017-04-06 09:40:50 -0400452 # Extract AAR file to target_dir.
453 with zipfile.ZipFile(artifact_file) as zip:
454 zip.extractall(target_dir)
455
Dan Willemsen814152e2017-11-06 13:22:11 -0800456 # Remove classes.jar
Alan Viverette95f6d362017-04-06 09:40:50 -0400457 classes_jar = os.path.join(target_dir, "classes.jar")
458 if os.path.exists(classes_jar):
Dan Willemsen814152e2017-11-06 13:22:11 -0800459 os.remove(classes_jar)
Alan Viverette95f6d362017-04-06 09:40:50 -0400460
461 # Remove or preserve empty dirs.
462 for root, dirs, files in os.walk(target_dir):
463 for dir in dirs:
464 dir_path = os.path.join(root, dir)
465 if not os.listdir(dir_path):
466 os.rmdir(dir_path)
467
468 # Remove top-level cruft.
469 for file in blacklist_files:
470 file_path = os.path.join(target_dir, file)
471 if os.path.exists(file_path):
472 os.remove(file_path)
473
Alan Viverettef17c9402017-07-19 12:57:40 -0400474
Saeid Farivar Asanjan54cd34e2021-10-01 16:47:54 +0000475class GMavenArtifact(object):
476 # A map from group:library to the latest available version
477 key_versions_map = {}
478 def __init__(self, artifact_glob):
479 try:
480 (group, library, version, ext) = artifact_glob.split(':')
481 except ValueError:
482 raise ValueError(f'Error in {artifact_glob} expected: group:library:version:ext')
483
484 if not group or not library or not version or not ext:
485 raise ValueError(f'Error in {artifact_glob} expected: group:library:version:ext')
486
487 self.group = group
488 self.group_path = group.replace('.', '/')
489 self.library = library
490 self.key = f'{group}:{library}'
491 self.version = version
492 self.ext = ext
493
494 def get_pom_file_url(self):
495 return f'{GMAVEN_BASE_URL}/{self.group_path}/{self.library}/{self.version}/{self.library}-{self.version}.pom'
496
497 def get_artifact_url(self):
498 return f'{GMAVEN_BASE_URL}/{self.group_path}/{self.library}/{self.version}/{self.library}-{self.version}.{self.ext}'
499
500 def get_latest_version(self):
501 latest_version = GMavenArtifact.key_versions_map[self.key] \
502 if self.key in GMavenArtifact.key_versions_map else None
503
504 if not latest_version:
505 print(f'Fetching latest version for {self.key}')
506 group_index_url = f'{GMAVEN_BASE_URL}/{self.group_path}/group-index.xml'
507 import xml.etree.ElementTree as ET
508 tree = ET.parse(urllib.request.urlopen(group_index_url))
509 root = tree.getroot()
510 libraries = root.findall('./*[@versions]')
511 for library in libraries:
512 key = f'{root.tag}:{library.tag}'
513 GMavenArtifact.key_versions_map[key] = library.get('versions').split(',')[-1]
514 latest_version = GMavenArtifact.key_versions_map[self.key]
515 return latest_version
516
517
518def fetch_gmaven_artifact(artifact):
519 """Fetch a GMaven artifact.
520
521 Downloads a GMaven artifact
522 (https://developer.android.com/studio/build/dependencies#gmaven-access)
523
524 Args:
525 artifact_glob: an instance of GMavenArtifact.
526 """
527 download_to = os.path.join('gmaven', artifact.group, artifact.library, artifact.version)
528
529 _DownloadFileToDisk(artifact.get_pom_file_url(), os.path.join(download_to, f'{artifact.library}-{artifact.version}.pom'))
530 _DownloadFileToDisk(artifact.get_artifact_url(), os.path.join(download_to, f'{artifact.library}-{artifact.version}.{artifact.ext}'))
531
532 return download_to
533
534
535def _DownloadFileToDisk(url, filepath):
536 """Download the file at URL to the location dictated by the path.
537
538 Args:
539 url: Remote URL to download file from.
540 filepath: Filesystem path to write the file to.
541 """
542 print(f'Downloading URL: {url}')
543 file_data = urllib.request.urlopen(url)
544
545 try:
546 os.makedirs(os.path.dirname(filepath))
547 except os.error:
548 # This is a common situation - os.makedirs fails if dir already exists.
549 pass
550 try:
551 with open(filepath, 'wb') as f:
552 f.write(six.ensure_binary(file_data.read()))
553 except:
554 os.remove(os.path.dirname(filepath))
555 raise
556
557
Alan Viverettecd3de262017-08-14 09:51:30 -0400558def fetch_artifact(target, build_id, artifact_path):
Jeff Sharkeyabe16df2021-05-25 10:09:03 -0600559 global args
Jiyong Park1d1c9632018-05-29 17:45:27 +0900560 download_to = os.path.join('.', os.path.dirname(artifact_path))
561 print('Fetching %s from %s ...' % (artifact_path, target))
562 if not os.path.exists(download_to):
563 os.makedirs(download_to)
Jeff Sharkeyabe16df2021-05-25 10:09:03 -0600564 if args.beyond_corp:
565 fetch_cmd = [FETCH_ARTIFACT_BEYOND_CORP, '--use_oauth2',
566 '--bid', str(build_id), '--target', target, artifact_path, download_to]
567 else:
568 fetch_cmd = [FETCH_ARTIFACT,
569 '--bid', str(build_id), '--target', target, artifact_path, download_to]
Jeff Gaston97a9b762018-10-02 15:15:12 -0400570 print("Running: " + ' '.join(fetch_cmd))
Alan Viverette45837092017-05-12 14:50:53 -0400571 try:
Alan Viverettecd3de262017-08-14 09:51:30 -0400572 subprocess.check_output(fetch_cmd, stderr=subprocess.STDOUT)
Alan Viverette45837092017-05-12 14:50:53 -0400573 except subprocess.CalledProcessError:
Jeff Gaston13e38412018-02-06 14:45:36 -0500574 print_e('FAIL: Unable to retrieve %s artifact for build ID %s' % (artifact_path, build_id))
Alan Viverettec1c32b62017-12-20 09:40:36 -0500575 print_e('Please make sure you are authenticated for build server access!')
Alan Viverette45837092017-05-12 14:50:53 -0400576 return None
577 return artifact_path
578
579
Anton Hansson1d01a032018-04-09 10:29:37 +0100580def fetch_artifacts(target, build_id, artifact_dict):
581 for artifact, target_path in artifact_dict.items():
582 artifact_path = fetch_artifact(target, build_id.url_id, artifact)
583 if not artifact_path:
584 return False
585 mv(artifact_path, target_path)
586 return True
587
588
Alan Viverette129555e2018-01-30 09:57:57 -0500589def extract_artifact(artifact_path):
Alan Viverette45837092017-05-12 14:50:53 -0400590 # Unzip the repo archive into a separate directory.
Alan Viverette3e57a4a2017-08-11 15:49:47 -0400591 repo_dir = os.path.basename(artifact_path)[:-4]
Alan Viverette45837092017-05-12 14:50:53 -0400592 with zipfile.ZipFile(artifact_path) as zipFile:
Alan Viverette3e57a4a2017-08-11 15:49:47 -0400593 zipFile.extractall(repo_dir)
Alan Viverette3e57a4a2017-08-11 15:49:47 -0400594 return repo_dir
595
596
Alan Viverette7e897e22018-03-09 15:24:10 -0500597def fetch_and_extract(target, build_id, file, artifact_path=None):
598 if not artifact_path:
599 artifact_path = fetch_artifact(target, build_id, file)
Alan Viverette129555e2018-01-30 09:57:57 -0500600 if not artifact_path:
601 return None
602 return extract_artifact(artifact_path)
603
604
Saeid Farivar Asanjan54cd34e2021-10-01 16:47:54 +0000605def update_gmaven(gmaven_artifacts):
606 artifacts = [GMavenArtifact(artifact) for artifact in gmaven_artifacts]
607 for artifact in artifacts:
608 if artifact.version == 'latest':
609 artifact.version = artifact.get_latest_version()
610
611 artifact_dirs = [fetch_gmaven_artifact(artifact) for artifact in artifacts]
612 if not transform_maven_repos(['gmaven'], gmaven_dir, extract_res=False):
613 return []
614 return [artifact.key for artifact in artifacts]
615
616
Jeff Gaston08a2ee42018-05-07 18:08:41 -0400617def update_androidx(target, build_id, local_file):
Jeff Gastonbbd6bfc2018-03-27 17:35:49 -0400618 if build_id:
Anthony Chenacbb4872018-07-02 11:22:48 -0700619 repo_file = 'top-of-tree-m2repository-all-%s.zip' % build_id.fs_id
Jeff Gastonbbd6bfc2018-03-27 17:35:49 -0400620 repo_dir = fetch_and_extract(target, build_id.url_id, repo_file, None)
621 else:
622 repo_dir = fetch_and_extract(target, None, None, local_file)
623 if not repo_dir:
624 print_e('Failed to extract AndroidX repository')
625 return False
626
Tony Mak0f658752019-07-19 11:11:05 +0100627 # Keep JavaPlugins.bp file untounched.
628 java_plugins_bp_path = os.path.join(androidx_dir, 'JavaPlugins.bp')
629 tmp_java_plugins_bp_path = os.path.join('/tmp', 'JavaPlugins.bp')
630 mv(java_plugins_bp_path, tmp_java_plugins_bp_path)
Jeff Gastonbbd6bfc2018-03-27 17:35:49 -0400631
Tony Mak0f658752019-07-19 11:11:05 +0100632 # Transform the repo archive into a Makefile-compatible format.
633 if not transform_maven_repos([repo_dir], androidx_dir, extract_res=False):
634 return False
635
636 # Import JavaPlugins.bp in Android.bp.
637 makefile = os.path.join(androidx_dir, 'Android.bp')
638 with open(makefile, "a+") as f:
639 f.write('\nbuild = ["JavaPlugins.bp"]\n')
640 mv(tmp_java_plugins_bp_path, java_plugins_bp_path)
641
642 return True
Jeff Gastonbbd6bfc2018-03-27 17:35:49 -0400643
Alan Viverette6dc45752020-04-16 14:56:20 +0000644
Jeff Gaston782c3e32018-02-06 14:36:17 -0500645def update_jetifier(target, build_id):
646 repo_file = 'jetifier-standalone.zip'
647 repo_dir = fetch_and_extract(target, build_id.url_id, repo_file)
648 if not repo_dir:
649 print_e('Failed to extract Jetifier')
650 return False
651
652 rm(jetifier_dir)
Jeff Gaston553a4372018-03-29 18:34:22 -0400653 mv(os.path.join(repo_dir, 'jetifier-standalone'), jetifier_dir)
654 os.chmod(os.path.join(jetifier_dir, 'bin', 'jetifier-standalone'), 0o755)
Jeff Gaston782c3e32018-02-06 14:36:17 -0500655 return True
656
Alan Viverette7e897e22018-03-09 15:24:10 -0500657
Alan Viverette6dc45752020-04-16 14:56:20 +0000658def update_constraint(local_file):
Jeff Gaston9edf86c2018-04-18 13:45:23 -0400659 repo_dir = extract_artifact(local_file)
660 if not repo_dir:
Alan Viverette6dc45752020-04-16 14:56:20 +0000661 print_e('Failed to extract Constraint Layout')
Jeff Gaston9edf86c2018-04-18 13:45:23 -0400662 return False
663 return transform_maven_repos([repo_dir], os.path.join(extras_dir, 'constraint-layout-x'), extract_res=False)
664
Alan Viverette45837092017-05-12 14:50:53 -0400665
Jeff Gaston6e7e7502018-04-04 00:22:45 -0400666def update_material(file):
667 design_dir = extract_artifact(file)
668 if not design_dir:
Alan Viverette6dc45752020-04-16 14:56:20 +0000669 print_e('Failed to extract Material Design Components')
Jeff Gaston6e7e7502018-04-04 00:22:45 -0400670 return False
671
672 # Don't bother extracting resources -- this should only be used with AAPT2.
673 return transform_maven_repos([design_dir],
674 os.path.join(extras_dir, 'material-design-x'), extract_res=False)
675
Paul Duffin1fed8212021-10-29 17:02:38 +0100676def update_framework(target, build_id, sdk_dir):
Anton Hansson83f92172020-03-26 11:12:03 +0000677 api_scope_list = ['public', 'system', 'test', 'module-lib', 'system-server']
Sundong Ahn66091f22018-08-29 18:54:28 +0900678 if sdk_dir == 'current':
679 api_scope_list.append('core')
680
681 for api_scope in api_scope_list:
Jiyong Park1d1c9632018-05-29 17:45:27 +0900682 target_dir = path(sdk_dir, api_scope)
Sundong Ahn66091f22018-08-29 18:54:28 +0900683 if api_scope == 'core':
684 artifact_to_path = {'core.current.stubs.jar': path(target_dir, 'android.jar')}
685 else:
Paul Duffin6815a312021-10-28 13:02:51 +0100686 artifact_to_path = {
687 'apistubs/android/' + api_scope + '/*.jar': path(target_dir, '*'),
688 }
689 if api_scope == 'public' or api_scope == 'module-lib':
690 # Distinct core-for-system-modules.jar files are only provided
691 # for the public and module-lib API surfaces.
692 artifact_to_path['system-modules/' + api_scope + '/core-for-system-modules.jar'] = path(target_dir, '*')
Anton Hansson1d01a032018-04-09 10:29:37 +0100693
Paul Duffin1fed8212021-10-29 17:02:38 +0100694 if not fetch_artifacts(target, build_id, artifact_to_path):
Anton Hansson1d01a032018-04-09 10:29:37 +0100695 return False
696
Jiyong Park1d1c9632018-05-29 17:45:27 +0900697 if api_scope == 'public':
Anton Hansson1d01a032018-04-09 10:29:37 +0100698 # Fetch a few artifacts from the public sdk.
Sundong Ahn66091f22018-08-29 18:54:28 +0900699 artifact = 'sdk-repo-linux-platforms-%s.zip' % build_id.fs_id
Paul Duffin1fed8212021-10-29 17:02:38 +0100700 artifact_path = fetch_artifact(target, build_id.url_id, artifact)
Anton Hansson9709fd42018-04-03 16:52:13 +0100701 if not artifact_path:
702 return False
Anton Hansson1d01a032018-04-09 10:29:37 +0100703
704 with zipfile.ZipFile(artifact_path) as zipFile:
Colin Crossd338d702020-07-10 19:17:54 -0700705 extra_files = [
706 'android.jar',
707 'framework.aidl',
708 'uiautomator.jar',
Colin Crossd338d702020-07-10 19:17:54 -0700709 'data/annotations.zip',
710 'data/api-versions.xml']
711 for filename in extra_files:
Anton Hanssona26e4812020-03-25 12:54:39 +0000712 matches = list(filter(lambda path: filename in path, zipFile.namelist()))
713 if len(matches) != 1:
714 print_e('Expected 1 file named \'%s\' in zip %s, found %d' %
715 (filename, zipFile.filename, len(matches)))
716 return False
717 zip_path = matches[0]
718 src_path = zipFile.extract(zip_path)
719 dst_path = path(target_dir, filename)
720 mv(src_path, dst_path)
Anton Hansson9709fd42018-04-03 16:52:13 +0100721
Anton Hansson73be1512021-06-24 10:56:05 +0100722 # Filtered API DB is currently only available for "public"
Paul Duffin1fed8212021-10-29 17:02:38 +0100723 fetch_artifacts(target, build_id, {'api-versions-public-filtered.xml': path(target_dir, 'data/api-versions-filtered.xml')})
Anton Hansson73be1512021-06-24 10:56:05 +0100724
Alan Viverettecd3de262017-08-14 09:51:30 -0400725 return True
Alan Viverette45837092017-05-12 14:50:53 -0400726
Sundong Ahncc34cc32018-07-11 15:18:47 +0900727def update_makefile(build_id):
728 template = '"%s",\n\
729 "current"'
730 makefile = os.path.join(git_dir, 'Android.bp')
731
732 with open(makefile, 'r+') as f:
733 contents = f.read().replace('"current"', template % build_id)
734 f.seek(0)
735 f.write(contents)
736
737 return True
Alan Viverette45837092017-05-12 14:50:53 -0400738
Paul Duffin1fed8212021-10-29 17:02:38 +0100739def finalize_sdk(target, build_id, sdk_version):
Anton Hansson1d01a032018-04-09 10:29:37 +0100740 target_finalize_dir = '%d' % sdk_version
Anton Hansson9709fd42018-04-03 16:52:13 +0100741
Anton Hanssonaa554c02020-04-30 14:06:20 +0100742 for api_scope in ['public', 'system', 'test', 'module-lib', 'system-server']:
Sundong Ahn66091f22018-08-29 18:54:28 +0900743 artifact_to_path = {'apistubs/android/' + api_scope + '/api/*.txt':
744 path(target_finalize_dir, api_scope, 'api', '*')}
745
Paul Duffin1fed8212021-10-29 17:02:38 +0100746 if not fetch_artifacts(target, build_id, artifact_to_path):
Sundong Ahn66091f22018-08-29 18:54:28 +0900747 return False
748
Paul Duffin1fed8212021-10-29 17:02:38 +0100749 return update_framework(target, build_id, target_finalize_dir) \
Sundong Ahncc34cc32018-07-11 15:18:47 +0900750 and update_makefile(target_finalize_dir)
Anton Hansson9709fd42018-04-03 16:52:13 +0100751
Anton Hansson9709fd42018-04-03 16:52:13 +0100752
Paul Duffin1fed8212021-10-29 17:02:38 +0100753def update_framework_current(target, build_id):
754 return update_framework(target, build_id, current_path)
Anton Hansson9709fd42018-04-03 16:52:13 +0100755
756
Alan Viverettec1c32b62017-12-20 09:40:36 -0500757def update_buildtools(target, arch, build_id):
Jeff Gaston13e38412018-02-06 14:45:36 -0500758 artifact_path = fetch_and_extract(target, build_id.url_id,
759 "sdk-repo-%s-build-tools-%s.zip" % (arch, build_id.fs_id))
Alan Viverettec1c32b62017-12-20 09:40:36 -0500760 if not artifact_path:
761 return False
762
763 top_level_dir = os.listdir(artifact_path)[0]
764 src_path = os.path.join(artifact_path, top_level_dir)
765 dst_path = path(buildtools_dir, arch)
Colin Cross20648d32021-02-12 13:30:51 -0800766
767 # There are a few libraries that have been manually added to the
768 # build tools, copy them from the destination back to the source
769 # before the destination is overwritten.
770 files_to_save = (
771 'lib64/libconscrypt_openjdk_jni.dylib',
772 'lib64/libconscrypt_openjdk_jni.so',
773 'bin/lib64/libwinpthread-1.dll',
774 )
775 for file in files_to_save:
776 src_file = os.path.join(dst_path, file)
777 dst_file = os.path.join(src_path, file)
778 if os.path.exists(dst_path):
779 mv(src_file, dst_file)
780
Alan Viverettec1c32b62017-12-20 09:40:36 -0500781 mv(src_path, dst_path)
782
783 # Move all top-level files to /bin and make them executable
784 bin_path = path(dst_path, 'bin')
785 top_level_files = filter(lambda e: os.path.isfile(path(dst_path, e)), os.listdir(dst_path))
786 for file in top_level_files:
787 src_file = path(dst_path, file)
788 dst_file = path(bin_path, file)
789 mv(src_file, dst_file)
790 os.chmod(dst_file, 0o755)
791
Colin Cross6673ceb2021-02-12 13:14:14 -0800792 # Make the files under lld-bin executable
793 lld_bin_files = os.listdir(os.path.join(dst_path, 'lld-bin'))
794 for file in lld_bin_files:
795 os.chmod(os.path.join(dst_path, 'lld-bin', file), 0o755)
796
Alan Viverettec1c32b62017-12-20 09:40:36 -0500797 # Remove renderscript
798 rm(path(dst_path, 'renderscript'))
799
800 return True
801
802
Alan Viverettecd3de262017-08-14 09:51:30 -0400803def append(text, more_text):
804 if text:
805 return "%s, %s" % (text, more_text)
806 return more_text
Alan Viverette45837092017-05-12 14:50:53 -0400807
Alan Viverette95f6d362017-04-06 09:40:50 -0400808
Jeff Gaston13e38412018-02-06 14:45:36 -0500809class buildId(object):
810 def __init__(self, url_id, fs_id):
811 # id when used in build server urls
812 self.url_id = url_id
813 # id when used in build commands
814 self.fs_id = fs_id
815
Jeff Gastonb9b09052018-02-05 14:16:05 -0500816def getBuildId(args):
Jeff Gaston13e38412018-02-06 14:45:36 -0500817 # must be in the format 12345 or P12345
Jeff Gastonb9b09052018-02-05 14:16:05 -0500818 source = args.source
Jeff Gaston13e38412018-02-06 14:45:36 -0500819 number_text = source[:]
820 presubmit = False
821 if number_text.startswith("P"):
822 presubmit = True
823 number_text = number_text[1:]
824 if not number_text.isnumeric():
Alan Viverette7e897e22018-03-09 15:24:10 -0500825 return None
Jeff Gaston13e38412018-02-06 14:45:36 -0500826 url_id = source
827 fs_id = url_id
828 if presubmit:
829 fs_id = "0"
830 args.file = False
831 return buildId(url_id, fs_id)
Jeff Gastonb9b09052018-02-05 14:16:05 -0500832
Colin Cross573e1212018-02-12 14:59:52 -0800833def getFile(args):
834 source = args.source
835 if not source.isnumeric():
836 return args.source
Alan Viverette7e897e22018-03-09 15:24:10 -0500837 return None
Colin Cross573e1212018-02-12 14:59:52 -0800838
Alan Viverette4ec9a172018-02-20 16:19:31 -0500839
840def script_relative(rel_path):
Jeff Gastona68a8d42018-03-23 14:00:13 -0400841 return os.path.join(script_dir, rel_path)
Alan Viverette4ec9a172018-02-20 16:19:31 -0500842
843
Jeff Gastoncc296a82018-03-23 14:33:24 -0400844def uncommittedChangesExist():
845 try:
846 # Make sure we don't overwrite any pending changes.
847 diffCommand = "cd " + git_dir + " && git diff --quiet"
848 subprocess.check_call(diffCommand, shell=True)
849 subprocess.check_call(diffCommand + " --cached", shell=True)
850 return False
851 except subprocess.CalledProcessError:
852 return True
853
854
Jeff Gastona7fba9b2018-03-26 23:48:51 -0400855rm(temp_dir)
Alan Viveretted4527e62017-05-11 15:03:25 -0400856parser = argparse.ArgumentParser(
Alan Viverette45837092017-05-12 14:50:53 -0400857 description=('Update current prebuilts'))
Alan Viveretted4527e62017-05-11 15:03:25 -0400858parser.add_argument(
Saeid Farivar Asanjan54cd34e2021-10-01 16:47:54 +0000859 'source', nargs='?',
Alan Viverette129555e2018-01-30 09:57:57 -0500860 help='Build server build ID or local Maven ZIP file')
861parser.add_argument(
Jeff Gaston6e7e7502018-04-04 00:22:45 -0400862 '-m', '--material', action="store_true",
Alan Viverette6dc45752020-04-16 14:56:20 +0000863 help='If specified, updates only Material Design Components')
Jeff Gaston6e7e7502018-04-04 00:22:45 -0400864parser.add_argument(
Alan Viverette3e57a4a2017-08-11 15:49:47 -0400865 '-c', '--constraint', action="store_true",
866 help='If specified, updates only Constraint Layout')
867parser.add_argument(
Jeff Gaston782c3e32018-02-06 14:36:17 -0500868 '-j', '--jetifier', action="store_true",
869 help='If specified, updates only Jetifier')
870parser.add_argument(
Alan Viverette5bfe05b2017-06-06 14:21:29 -0400871 '-p', '--platform', action="store_true",
872 help='If specified, updates only the Android Platform')
Alan Viverettec1c32b62017-12-20 09:40:36 -0500873parser.add_argument(
Anton Hansson9709fd42018-04-03 16:52:13 +0100874 '-f', '--finalize_sdk', type=int,
Anton Hansson4bcebac2022-04-07 17:23:18 +0100875 help='Finalize the build as the specified SDK version. Must be used together with -e')
876parser.add_argument(
877 '-e', '--finalize_extension', type=int,
878 help='Finalize the build as the specified extension SDK version. Must be used together with -f')
Anton Hansson57a1b142022-04-07 17:27:41 +0100879parser.add_argument('--bug', type=int, help='The bug number to add to the commit message.')
Anton Hansson9709fd42018-04-03 16:52:13 +0100880parser.add_argument(
Paul Duffin1fed8212021-10-29 17:02:38 +0100881 '--sdk_target',
882 default=framework_sdk_target,
883 help='If specified, the name of the build target from which to retrieve the SDK when -p or -f is specified.')
884parser.add_argument(
Alan Viverettec1c32b62017-12-20 09:40:36 -0500885 '-b', '--buildtools', action="store_true",
886 help='If specified, updates only the Build Tools')
Jeff Gastoncc296a82018-03-23 14:33:24 -0400887parser.add_argument(
Alan Viverette6dc45752020-04-16 14:56:20 +0000888 '-x', '--androidx', action="store_true",
889 help='If specified, updates only the Jetpack (androidx) libraries excluding those covered by other arguments')
Jeff Gaston41fd5e62018-04-25 17:02:02 -0400890parser.add_argument(
Saeid Farivar Asanjan54cd34e2021-10-01 16:47:54 +0000891 '-g', '--gmaven', action="store_true",
892 help='If specified, updates only the artifact from GMaven libraries excluding those covered by other arguments')
893parser.add_argument(
Jeff Gastoncc296a82018-03-23 14:33:24 -0400894 '--commit-first', action="store_true",
895 help='If specified, then if uncommited changes exist, commit before continuing')
Jeff Sharkeyabe16df2021-05-25 10:09:03 -0600896parser.add_argument(
897 '--beyond-corp', action="store_true",
898 help='If specified, then fetch artifacts with tooling that works on BeyondCorp devices')
Alan Viveretted4527e62017-05-11 15:03:25 -0400899args = parser.parse_args()
Jeff Gaston56fe2762018-02-06 14:54:37 -0500900args.file = True
Anton Hansson4bcebac2022-04-07 17:23:18 +0100901
Saeid Farivar Asanjan54cd34e2021-10-01 16:47:54 +0000902if not args.source and (args.platform or args.buildtools \
903 or args.jetifier or args.androidx or args.material \
904 or args.finalize_sdk or args.constraint):
Alan Viverette129555e2018-01-30 09:57:57 -0500905 parser.error("You must specify a build ID or local Maven ZIP file")
Alan Viveretted4527e62017-05-11 15:03:25 -0400906 sys.exit(1)
Saeid Farivar Asanjan54cd34e2021-10-01 16:47:54 +0000907if not (args.gmaven or args.platform or args.buildtools \
Alan Viverette6dc45752020-04-16 14:56:20 +0000908 or args.jetifier or args.androidx or args.material \
Anton Hansson4bcebac2022-04-07 17:23:18 +0100909 or args.finalize_sdk or args.finalize_extension or args.constraint):
Alan Viverettec1c32b62017-12-20 09:40:36 -0500910 parser.error("You must specify at least one target to update")
Alan Viverettecd3de262017-08-14 09:51:30 -0400911 sys.exit(1)
Saeid Farivar Asanjan54cd34e2021-10-01 16:47:54 +0000912if (args.constraint or args.material or args.androidx or args.gmaven) \
Colin Cross74683bc2018-04-11 17:36:18 -0700913 and which('pom2bp') is None:
Louis Pullen-Freilich61bb70e2019-04-09 16:15:32 +0100914 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 -0500915 sys.exit(1)
Anton Hansson4bcebac2022-04-07 17:23:18 +0100916if (args.finalize_sdk is None) != (args.finalize_extension is None):
917 parser.error("Either both or neither of -e and -f must be specified.")
918 sys.exit(1)
Anton Hansson57a1b142022-04-07 17:27:41 +0100919if args.finalize_sdk and not args.bug:
920 parser.error("Specifying a bug ID with --bug is required when finalizing an SDK.")
921 sys.exit(1)
Alan Viveretted4527e62017-05-11 15:03:25 -0400922
Jeff Gastoncc296a82018-03-23 14:33:24 -0400923if uncommittedChangesExist():
924 if args.commit_first:
925 subprocess.check_call("cd " + git_dir + " && git add -u", shell=True)
926 subprocess.check_call("cd " + git_dir + " && git commit -m 'save working state'", shell=True)
927
928if uncommittedChangesExist():
Anton Hansson10861a02018-04-06 13:57:08 +0100929 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 -0400930 sys.exit(1)
931
Anton Hansson57a1b142022-04-07 17:27:41 +0100932commit_message_suffix = ""
933if args.bug:
934 commit_message_suffix = "\n\nBug: %d" % args.bug
935
Alan Viveretted4527e62017-05-11 15:03:25 -0400936try:
Alan Viverettecd3de262017-08-14 09:51:30 -0400937 components = None
938 if args.constraint:
Jeff Gaston9edf86c2018-04-18 13:45:23 -0400939 if update_constraint_x(getFile(args)):
940 components = append(components, 'Constraint Layout X')
941 else:
942 print_e('Failed to update Constraint Layout X, aborting...')
Alan Viverettecd3de262017-08-14 09:51:30 -0400943 sys.exit(1)
Saeid Farivar Asanjan54cd34e2021-10-01 16:47:54 +0000944 if args.gmaven:
945 updated_artifacts = update_gmaven(gmaven_artifacts)
946 if updated_artifacts:
947 components = append(components, '\n'.join(updated_artifacts))
948 else:
949 print_e('Failed to update GMaven, aborting...')
950 sys.exit(1)
Jeff Gastonbbd6bfc2018-03-27 17:35:49 -0400951 if args.androidx:
Jeff Gaston17ccf8f2018-08-29 11:33:19 -0400952 if update_androidx('androidx', \
Jeff Gastonbbd6bfc2018-03-27 17:35:49 -0400953 getBuildId(args), getFile(args)):
954 components = append(components, 'AndroidX')
955 else:
956 print_e('Failed to update AndroidX, aborting...')
957 sys.exit(1)
Jeff Gaston782c3e32018-02-06 14:36:17 -0500958 if args.jetifier:
Jeff Gaston17ccf8f2018-08-29 11:33:19 -0400959 if update_jetifier('androidx', getBuildId(args)):
Jeff Gaston782c3e32018-02-06 14:36:17 -0500960 components = append(components, 'Jetifier')
961 else:
962 print_e('Failed to update Jetifier, aborting...')
963 sys.exit(1)
Anton Hanssonbe15e8c2018-04-26 17:35:45 +0100964 if args.platform or args.finalize_sdk:
Paul Duffin1fed8212021-10-29 17:02:38 +0100965 if update_framework_current(args.sdk_target, getBuildId(args)):
Alan Viverettecd3de262017-08-14 09:51:30 -0400966 components = append(components, 'platform SDK')
967 else:
Alan Viverettef5cb0e62017-11-17 15:15:23 -0500968 print_e('Failed to update platform SDK, aborting...')
Alan Viverettecd3de262017-08-14 09:51:30 -0400969 sys.exit(1)
Anton Hansson9709fd42018-04-03 16:52:13 +0100970 if args.finalize_sdk:
Anton Hanssonbe15e8c2018-04-26 17:35:45 +0100971 n = args.finalize_sdk
Anton Hansson4bcebac2022-04-07 17:23:18 +0100972 if not finalize_sdk(args.sdk_target, getBuildId(args), n):
Anton Hanssonbe15e8c2018-04-26 17:35:45 +0100973 print_e('Failed to finalize SDK %d, aborting...' % n)
Anton Hansson9709fd42018-04-03 16:52:13 +0100974 sys.exit(1)
Anton Hansson4bcebac2022-04-07 17:23:18 +0100975 # We commit the finalized dir separately from the current sdk update.
976 msg = "Import final sdk version %d from build %s%s" % (n, getBuildId(args).url_id, commit_message_suffix)
977 subprocess.check_call(['git', 'add', '%d' % n])
978 subprocess.check_call(['git', 'add', 'Android.bp'])
979 subprocess.check_call(['git', 'commit', '-m', msg])
980
981 # Finalize extension sdk level
982 cmd = extension_sdk_finalization_cmd.format(
983 bug=args.bug,
984 extension_version=args.finalize_extension,
985 build_id=getBuildId(args).url_id)
986 subprocess.check_call(cmd.split(' '), cwd=repo_root_dir.resolve())
Jeff Gaston6e7e7502018-04-04 00:22:45 -0400987 if args.material:
988 if update_material(getFile(args)):
989 components = append(components, 'intermediate-AndroidX Design Library')
990 else:
991 print_e('Failed to update intermediate-AndroidX Design Library, aborting...')
Alan Viverette129555e2018-01-30 09:57:57 -0500992 sys.exit(1)
Alan Viverettec1c32b62017-12-20 09:40:36 -0500993 if args.buildtools:
Jeff Gastonb9b09052018-02-05 14:16:05 -0500994 if update_buildtools('sdk_phone_armv7-sdk_mac', 'darwin', getBuildId(args)) \
995 and update_buildtools('sdk_phone_x86_64-sdk', 'linux', getBuildId(args)) \
996 and update_buildtools('sdk_phone_armv7-win_sdk', 'windows', getBuildId(args)):
Alan Viverettec1c32b62017-12-20 09:40:36 -0500997 components = append(components, 'build tools')
998 else:
999 print_e('Failed to update build tools, aborting...')
1000 sys.exit(1)
Jeff Gastonb70daa92018-03-29 20:10:22 -04001001
Jeff Gastonf12f3ce2018-03-23 16:41:24 -04001002
Alan Viveretted4527e62017-05-11 15:03:25 -04001003
Colin Cross941d9802018-05-03 21:37:57 -07001004 subprocess.check_call(['git', 'add', current_path, buildtools_dir])
Saeid Farivar Asanjan54cd34e2021-10-01 16:47:54 +00001005 if not args.source and args.gmaven:
1006 src_msg = "GMaven"
1007 elif not args.source.isnumeric():
Alan Viverette129555e2018-01-30 09:57:57 -05001008 src_msg = "local Maven ZIP"
1009 else:
Jeff Gaston13e38412018-02-06 14:45:36 -05001010 src_msg = "build %s" % (getBuildId(args).url_id)
Anton Hansson57a1b142022-04-07 17:27:41 +01001011 msg = "Import %s from %s\n\n%s%s" % (components, src_msg, flatten(sys.argv), commit_message_suffix)
Alan Viveretted4527e62017-05-11 15:03:25 -04001012 subprocess.check_call(['git', 'commit', '-m', msg])
Anton Hanssonbe15e8c2018-04-26 17:35:45 +01001013 if args.finalize_sdk:
Anton Hansson4bcebac2022-04-07 17:23:18 +01001014 print('NOTE: Created three commits:')
1015 subprocess.check_call(['git', 'log', '-3', '--oneline'])
Alan Viverettef5cb0e62017-11-17 15:15:23 -05001016 print('Remember to test this change before uploading it to Gerrit!')
Alan Viveretted4527e62017-05-11 15:03:25 -04001017
1018finally:
1019 # Revert all stray files, including the downloaded zip.
1020 try:
1021 with open(os.devnull, 'w') as bitbucket:
1022 subprocess.check_call(['git', 'add', '-Af', '.'], stdout=bitbucket)
1023 subprocess.check_call(
Jeff Gaston9edf86c2018-04-18 13:45:23 -04001024 ['git', 'commit', '-m', 'COMMIT TO REVERT - RESET ME!!!', '--allow-empty'], stdout=bitbucket)
Alan Viveretted4527e62017-05-11 15:03:25 -04001025 subprocess.check_call(['git', 'reset', '--hard', 'HEAD~1'], stdout=bitbucket)
1026 except subprocess.CalledProcessError:
Alan Viverettef5cb0e62017-11-17 15:15:23 -05001027 print_e('ERROR: Failed cleaning up, manual cleanup required!!!')