blob: b9da37a32db90310ce7c49385e88e0fdedee626f [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': { },
Dave Mankoff84276c52022-01-12 14:10:43 -050064 'androidx.collection:collection-jvm': { },
Alan Viverettef3c12722021-08-30 19:50:33 +000065 'androidx.concurrent:concurrent-futures': { },
66 'androidx.concurrent:concurrent-listenablefuture-callback': { },
67 'androidx.concurrent:concurrent-listenablefuture': { },
68 'androidx.core:core': { },
69 'androidx.core:core-animation': { },
70 'androidx.core:core-ktx': { },
71 'androidx.contentpaging:contentpaging': { },
72 'androidx.coordinatorlayout:coordinatorlayout': { },
73 'androidx.legacy:legacy-support-core-ui': { },
74 'androidx.legacy:legacy-support-core-utils': { },
75 'androidx.cursoradapter:cursoradapter': { },
76 'androidx.browser:browser': { },
77 'androidx.customview:customview': { },
78 'androidx.documentfile:documentfile': { },
79 'androidx.drawerlayout:drawerlayout': { },
80 'androidx.dynamicanimation:dynamicanimation': { },
81 'androidx.emoji:emoji': { },
82 'androidx.emoji:emoji-appcompat': { },
83 'androidx.emoji:emoji-bundled': { },
84 'androidx.emoji2:emoji2': { },
85 'androidx.emoji2:emoji2-views-helper': { },
86 'androidx.exifinterface:exifinterface': { },
87 'androidx.fragment:fragment': { },
88 'androidx.fragment:fragment-ktx': { },
89 'androidx.heifwriter:heifwriter': { },
90 'androidx.interpolator:interpolator': { },
91 'androidx.loader:loader': { },
Alan Viverettef3c12722021-08-30 19:50:33 +000092 'androidx.media:media': { },
93 'androidx.media2:media2-player': { },
94 'androidx.media2:media2-session': { },
95 'androidx.media2:media2-common': { },
96 'androidx.media2:media2-exoplayer': { },
97 'androidx.media2:media2-widget': { },
98 'androidx.navigation:navigation-common': { },
99 'androidx.navigation:navigation-common-ktx': { },
100 'androidx.navigation:navigation-fragment': { },
101 'androidx.navigation:navigation-fragment-ktx': { },
102 'androidx.navigation:navigation-runtime': { },
103 'androidx.navigation:navigation-runtime-ktx': { },
104 'androidx.navigation:navigation-ui': { },
105 'androidx.navigation:navigation-ui-ktx': { },
106 'androidx.percentlayout:percentlayout': { },
107 'androidx.print:print': { },
108 'androidx.recommendation:recommendation': { },
109 'androidx.recyclerview:recyclerview-selection': { },
110 'androidx.savedstate:savedstate': { },
111 'androidx.savedstate:savedstate-ktx': { },
112 'androidx.slidingpanelayout:slidingpanelayout': { },
113 'androidx.swiperefreshlayout:swiperefreshlayout': { },
114 'androidx.textclassifier:textclassifier': { },
115 'androidx.transition:transition': { },
116 'androidx.tvprovider:tvprovider': { },
117 'androidx.legacy:legacy-support-v13': { },
118 'androidx.legacy:legacy-preference-v14': { },
119 'androidx.leanback:leanback': { },
Dave Mankoff84276c52022-01-12 14:10:43 -0500120 'androidx.leanback:leanback-grid': { },
Alan Viverettef3c12722021-08-30 19:50:33 +0000121 'androidx.leanback:leanback-preference': { },
122 'androidx.legacy:legacy-support-v4': { },
123 'androidx.appcompat:appcompat': { },
124 'androidx.appcompat:appcompat-resources': { },
125 'androidx.cardview:cardview': { },
126 'androidx.gridlayout:gridlayout': { },
127 'androidx.mediarouter:mediarouter': { },
128 'androidx.palette:palette': { },
129 'androidx.preference:preference': { },
130 'androidx.recyclerview:recyclerview': { },
131 'androidx.vectordrawable:vectordrawable': { },
132 'androidx.viewpager:viewpager': { },
133 'androidx.viewpager2:viewpager2': { },
134 'androidx.wear:wear': { },
135 'androidx.wear:wear-ongoing': { },
136 'androidx.webkit:webkit': { },
137 'androidx.biometric:biometric': { },
138 'androidx.autofill:autofill': { },
139 'androidx.appsearch:appsearch': { },
Alan Viverette0723aff2021-08-31 17:07:47 +0000140 'androidx.appsearch:appsearch-local-storage': {'name':'androidx.appsearch_appsearch_local_storage'},
141 'androidx.appsearch:appsearch-platform-storage': { },
142 'androidx.appsearch:appsearch-compiler': {'name':'androidx.appsearch_appsearch-compiler', 'host':True},
Alan Viverettef3c12722021-08-30 19:50:33 +0000143 'androidx.car.app:app': { },
144 'androidx.car.app:app-automotive': { },
145 'androidx.car.app:app-testing': { },
146 'androidx.startup:startup-runtime': { },
Alan Viverettecdfc9892021-08-31 19:35:58 +0000147 'androidx.window:window': {'optional-uses-libs':{'androidx.window.extensions', 'androidx.window.sidecar'}},
Alan Viverettef3c12722021-08-30 19:50:33 +0000148 'androidx.resourceinspection:resourceinspection-annotation': { },
149 'androidx.profileinstaller:profileinstaller': { },
Aurimas Liutikas6e87bbf2021-07-30 10:04:05 -0700150
Alan Viverettef44e2f92021-08-31 17:26:26 +0000151 # AndroidX for Compose
Colin Cross58866d42021-09-17 14:40:35 -0700152 'androidx.compose.compiler:compiler-hosted': { 'host':True },
Alan Viverettef44e2f92021-08-31 17:26:26 +0000153 'androidx.compose.runtime:runtime': { },
154 'androidx.compose.runtime:runtime-saveable': { },
Dave Mankoffbafd3b62022-03-03 14:51:40 -0500155 'androidx.compose.runtime:runtime-livedata': { },
Alan Viverettef44e2f92021-08-31 17:26:26 +0000156 'androidx.compose.foundation:foundation': { },
157 'androidx.compose.foundation:foundation-layout': { },
158 'androidx.compose.foundation:foundation-text': { },
159 'androidx.compose.ui:ui': { },
160 'androidx.compose.ui:ui-geometry': { },
161 'androidx.compose.ui:ui-graphics': { },
162 'androidx.compose.ui:ui-text': { },
Dave Mankoff84276c52022-01-12 14:10:43 -0500163 'androidx.compose.ui:ui-tooling': { },
164 'androidx.compose.ui:ui-tooling-preview': { },
165 'androidx.compose.ui:ui-tooling-data': { },
Alan Viverettef44e2f92021-08-31 17:26:26 +0000166 'androidx.compose.ui:ui-unit': { },
167 'androidx.compose.ui:ui-util': { },
Jordan Demeulenaere606dca92022-07-29 16:09:28 +0200168 'androidx.compose.ui:ui-test': { },
169 'androidx.compose.ui:ui-test-junit4': { },
Alan Viverettef44e2f92021-08-31 17:26:26 +0000170 'androidx.compose.animation:animation-core': { },
171 'androidx.compose.animation:animation': { },
172 'androidx.compose.material:material-icons-core': { },
Jordan Demeulenaere606dca92022-07-29 16:09:28 +0200173 'androidx.compose.material:material-icons-extended': { },
Alan Viverettef44e2f92021-08-31 17:26:26 +0000174 'androidx.compose.material:material-ripple': { },
175 'androidx.compose.material:material': { },
Jordan Demeulenaeref79b4792022-03-14 15:35:43 +0100176 'androidx.compose.material3:material3': { },
Alan Viverettef44e2f92021-08-31 17:26:26 +0000177 'androidx.activity:activity-compose': { },
Jordan Demeulenaere606dca92022-07-29 16:09:28 +0200178 'androidx.navigation:navigation-compose': { },
179 'androidx.lifecycle:lifecycle-viewmodel-compose': { },
Alan Viverettef44e2f92021-08-31 17:26:26 +0000180
Jeff Gastonbbd6bfc2018-03-27 17:35:49 -0400181 # AndroidX for Multidex
Alan Viverette0723aff2021-08-31 17:07:47 +0000182 'androidx.multidex:multidex': { },
183 'androidx.multidex:multidex-instrumentation': { },
Jeff Gastonbbd6bfc2018-03-27 17:35:49 -0400184
185 # AndroidX for Constraint Layout
Alan Viverette0723aff2021-08-31 17:07:47 +0000186 'androidx.constraintlayout:constraintlayout': {'name':'androidx-constraintlayout_constraintlayout'},
187 'androidx.constraintlayout:constraintlayout-solver': {'name':'androidx-constraintlayout_constraintlayout-solver'},
Jeff Gastonbbd6bfc2018-03-27 17:35:49 -0400188
189 # AndroidX for Architecture Components
Alan Viverettef3c12722021-08-30 19:50:33 +0000190 'androidx.arch.core:core-common': { },
191 'androidx.arch.core:core-runtime': { },
192 'androidx.lifecycle:lifecycle-common': { },
193 'androidx.lifecycle:lifecycle-common-java8': { },
194 'androidx.lifecycle:lifecycle-extensions': { },
195 'androidx.lifecycle:lifecycle-livedata': { },
196 'androidx.lifecycle:lifecycle-livedata-ktx': { },
197 'androidx.lifecycle:lifecycle-livedata-core': { },
198 'androidx.lifecycle:lifecycle-livedata-core-ktx': { },
199 'androidx.lifecycle:lifecycle-process': { },
200 'androidx.lifecycle:lifecycle-runtime': { },
201 'androidx.lifecycle:lifecycle-runtime-ktx': { },
202 'androidx.lifecycle:lifecycle-service': { },
203 'androidx.lifecycle:lifecycle-viewmodel': { },
204 'androidx.lifecycle:lifecycle-viewmodel-ktx': { },
205 'androidx.lifecycle:lifecycle-viewmodel-savedstate': { },
206 'androidx.paging:paging-common': { },
207 'androidx.paging:paging-common-ktx': { },
208 'androidx.paging:paging-runtime': { },
209 'androidx.sqlite:sqlite': { },
210 'androidx.sqlite:sqlite-framework': { },
Alan Viverette0723aff2021-08-31 17:07:47 +0000211 'androidx.room:room-common': {'host_and_device':True},
Alan Viverettecdfc9892021-08-31 19:35:58 +0000212 'androidx.room:room-compiler': {'host':True, 'extra-static-libs':{'guava-21.0'}},
Alan Viverette0723aff2021-08-31 17:07:47 +0000213 'androidx.room:room-migration': {'host_and_device':True},
Alan Viverettef3c12722021-08-30 19:50:33 +0000214 'androidx.room:room-runtime': { },
215 'androidx.room:room-testing': { },
Alan Viverette0723aff2021-08-31 17:07:47 +0000216 'androidx.room:room-compiler-processing': {'host':True},
Alan Viverettef3c12722021-08-30 19:50:33 +0000217 'androidx.work:work-runtime': { },
218 'androidx.work:work-runtime-ktx': { },
219 'androidx.work:work-testing': { },
Allenab72f012018-01-29 18:10:23 -0800220
Jeff Gaston6e7e7502018-04-04 00:22:45 -0400221 # Third-party dependencies
Jeff Gastona0bce602018-08-24 14:05:03 -0400222 'com.google.android:flexbox': {'name':'flexbox', 'path':'flexbox'},
Jeff Gaston6e7e7502018-04-04 00:22:45 -0400223
Jeff Gastonfa7c7e82018-04-06 13:35:48 -0400224 # Androidx Material Design Components
Alan Viverettef3c12722021-08-30 19:50:33 +0000225 'com.google.android.material:material': { },
Alan Viverette95f6d362017-04-06 09:40:50 -0400226}
227
Alan Viverettecdfc9892021-08-31 19:35:58 +0000228# Mapping of POM dependencies to Soong build targets
229deps_rewrite = {
230 'auto-common':'auto_common',
231 'auto-value-annotations':'auto_value_annotations',
232 'com.google.auto.value:auto-value':'auto_value_plugin',
233 'monitor':'androidx.test.monitor',
234 'rules':'androidx.test.rules',
235 'runner':'androidx.test.runner',
236 'androidx.test:core':'androidx.test.core',
237 'com.squareup:javapoet':'javapoet',
238 'com.google.guava:listenablefuture':'guava-listenablefuture-prebuilt-jar',
239 'sqlite-jdbc':'xerial-sqlite-jdbc',
240 'gson':'gson-prebuilt-jar',
241 'com.intellij:annotations':'jetbrains-annotations',
242 'javax.annotation:javax.annotation-api':'javax-annotation-api-prebuilt-host-jar',
243 'org.robolectric:robolectric':'Robolectric_all-target',
244 'org.jetbrains.kotlin:kotlin-stdlib-common':'kotlin-stdlib',
245 'org.jetbrains.kotlinx:kotlinx-coroutines-core':'kotlinx_coroutines',
246 'org.jetbrains.kotlinx:kotlinx-coroutines-android':'kotlinx_coroutines_android',
Jordan Demeulenaere606dca92022-07-29 16:09:28 +0200247 'org.jetbrains.kotlinx:kotlinx-coroutines-test':'kotlinx_coroutines_test',
Alan Viverettecdfc9892021-08-31 19:35:58 +0000248 'org.jetbrains.kotlinx:kotlinx-metadata-jvm':'kotlinx_metadata_jvm',
Jordan Demeulenaere606dca92022-07-29 16:09:28 +0200249 'androidx.test.espresso:espresso-core':'androidx.test.espresso.core',
250 'androidx.test.espresso:espresso-idling-resource':'androidx.test.espresso.idling-resource',
Alan Viverettecdfc9892021-08-31 19:35:58 +0000251}
252
Saeid Farivar Asanjan54cd34e2021-10-01 16:47:54 +0000253# List of artifacts that will be updated from GMaven
254# Use pattern: `group:library:version:extension`
255# e.g.:
256# androidx.appcompat:appcompat:1.2.0:aar
257# Use `latest` to always fetch the latest version.
258# e.g.:
259# androidx.appcompat:appcompat:latest:aar
260# Also make sure you add `group:library`:{} to maven_to_make as well.
261gmaven_artifacts = {}
Alan Viverettef3c12722021-08-30 19:50:33 +0000262
263def name_for_artifact(group_artifact):
264 return group_artifact.replace(':','_')
265
266
267def path_for_artifact(group_artifact):
268 return group_artifact.replace('.','/').replace(':','/')
269
270
271# Add automatic entries to maven_to_make.
272for key in maven_to_make:
273 if ('name' not in maven_to_make[key]):
274 maven_to_make[key]['name'] = name_for_artifact(key)
275 if ('path' not in maven_to_make[key]):
276 maven_to_make[key]['path'] = path_for_artifact(key)
277
Alan Viverette95f6d362017-04-06 09:40:50 -0400278# Always remove these files.
279blacklist_files = [
280 'annotations.zip',
281 'public.txt',
282 'R.txt',
Alan Viverette44ad4e42017-08-09 17:45:00 -0400283 'AndroidManifest.xml',
Alan Viverettef48d9b42017-08-17 14:45:46 -0400284 os.path.join('libs','noto-emoji-compat-java.jar')
Alan Viverette95f6d362017-04-06 09:40:50 -0400285]
286
Alan Viverette44ad4e42017-08-09 17:45:00 -0400287artifact_pattern = re.compile(r"^(.+?)-(\d+\.\d+\.\d+(?:-\w+\d+)?(?:-[\d.]+)*)\.(jar|aar)$")
Alan Viverette95f6d362017-04-06 09:40:50 -0400288
Alan Viverettec960cfb2017-12-04 13:09:22 -0500289
290class MavenLibraryInfo:
Jeff Gastonc302bb92018-03-23 13:53:48 -0400291 def __init__(self, key, group_id, artifact_id, version, dir, repo_dir, file):
Alan Viverettec960cfb2017-12-04 13:09:22 -0500292 self.key = key
293 self.group_id = group_id
294 self.artifact_id = artifact_id
295 self.version = version
Jeff Gastonc302bb92018-03-23 13:53:48 -0400296 self.dir = dir
Alan Viverettec960cfb2017-12-04 13:09:22 -0500297 self.repo_dir = repo_dir
298 self.file = file
299
300
Alan Viverettef5cb0e62017-11-17 15:15:23 -0500301def print_e(*args, **kwargs):
302 print(*args, file=sys.stderr, **kwargs)
303
Alan Viverette95f6d362017-04-06 09:40:50 -0400304
305def touch(fname, times=None):
306 with open(fname, 'a'):
307 os.utime(fname, times)
308
309
Alan Viverette45837092017-05-12 14:50:53 -0400310def path(*path_parts):
311 return reduce((lambda x, y: os.path.join(x, y)), path_parts)
312
313
Alan Viverettecd3de262017-08-14 09:51:30 -0400314def flatten(list):
315 return reduce((lambda x, y: "%s %s" % (x, y)), list)
316
317
Alan Viverette45837092017-05-12 14:50:53 -0400318def rm(path):
319 if os.path.isdir(path):
320 rmtree(path)
321 elif os.path.exists(path):
322 os.remove(path)
323
324
325def mv(src_path, dst_path):
Alan Viverette3e57a4a2017-08-11 15:49:47 -0400326 if os.path.exists(dst_path):
Alan Viverettecd3de262017-08-14 09:51:30 -0400327 rm(dst_path)
Alan Viverette3e57a4a2017-08-11 15:49:47 -0400328 if not os.path.exists(os.path.dirname(dst_path)):
329 os.makedirs(os.path.dirname(dst_path))
Jiyong Park1d1c9632018-05-29 17:45:27 +0900330 for f in (glob.glob(src_path)):
331 if '*' in dst_path:
332 dst = os.path.join(os.path.dirname(dst_path), os.path.basename(f))
333 else:
334 dst = dst_path
shepshaparde4127cf2019-09-03 16:08:44 -0700335 move(f, dst)
Alan Viverette45837092017-05-12 14:50:53 -0400336
337
Jeff Gastonc302bb92018-03-23 13:53:48 -0400338def detect_artifacts(maven_repo_dirs):
Alan Viveretted4527e62017-05-11 15:03:25 -0400339 maven_lib_info = {}
340
Dan Willemsen814152e2017-11-06 13:22:11 -0800341 # Find the latest revision for each artifact, remove others
Jeff Gastonc302bb92018-03-23 13:53:48 -0400342 for repo_dir in maven_repo_dirs:
Dan Willemsen814152e2017-11-06 13:22:11 -0800343 for root, dirs, files in os.walk(repo_dir):
344 for file in files:
Alan Viverettec960cfb2017-12-04 13:09:22 -0500345 if file[-4:] == ".pom":
346 # Read the POM (hack hack hack).
347 group_id = ''
348 artifact_id = ''
349 version = ''
350 file = os.path.join(root, file)
351 with open(file) as pom_file:
352 for line in pom_file:
353 if line[:11] == ' <groupId>':
354 group_id = line[11:-11]
355 elif line[:14] == ' <artifactId>':
356 artifact_id = line[14:-14]
357 elif line[:11] == ' <version>':
358 version = line[11:-11]
359 if group_id == '' or artifact_id == '' or version == '':
360 print_e('Failed to find Maven artifact data in ' + file)
361 continue
Alan Viverette95f6d362017-04-06 09:40:50 -0400362
Alan Viverettec960cfb2017-12-04 13:09:22 -0500363 # Locate the artifact.
364 artifact_file = file[:-4]
365 if os.path.exists(artifact_file + '.jar'):
366 artifact_file = artifact_file + '.jar'
367 elif os.path.exists(artifact_file + '.aar'):
368 artifact_file = artifact_file + '.aar'
369 else:
370 print_e('Failed to find artifact for ' + artifact_file)
371 continue
372
373 # Make relative to root.
374 artifact_file = artifact_file[len(root) + 1:]
375
376 # Find the mapping.
377 group_artifact = group_id + ':' + artifact_id
Jeff Gaston3e622ba2018-03-26 23:24:46 -0400378 if group_artifact in maven_to_make:
Alan Viverettec960cfb2017-12-04 13:09:22 -0500379 key = group_artifact
Jeff Gaston3e622ba2018-03-26 23:24:46 -0400380 elif artifact_id in maven_to_make:
381 key = artifact_id
Alan Viverettec960cfb2017-12-04 13:09:22 -0500382 else:
Alan Viverettecdfc9892021-08-31 19:35:58 +0000383 # No mapping entry, skip this library.
Alan Viverettec960cfb2017-12-04 13:09:22 -0500384 continue
385
386 # Store the latest version.
387 version = LooseVersion(version)
388 if key not in maven_lib_info \
389 or version > maven_lib_info[key].version:
390 maven_lib_info[key] = MavenLibraryInfo(key, group_id, artifact_id, version,
391 root, repo_dir, artifact_file)
Alan Viverette95f6d362017-04-06 09:40:50 -0400392
Alan Viverette3e57a4a2017-08-11 15:49:47 -0400393 return maven_lib_info
394
395
Colin Cross59b59db2018-04-24 13:58:05 -0700396def transform_maven_repos(maven_repo_dirs, transformed_dir, extract_res=True, include_static_deps=True):
Alan Viverette3e57a4a2017-08-11 15:49:47 -0400397 cwd = os.getcwd()
398
399 # Use a temporary working directory.
Jeff Gastonc302bb92018-03-23 13:53:48 -0400400 maven_lib_info = detect_artifacts(maven_repo_dirs)
Jeff Gastona68a8d42018-03-23 14:00:13 -0400401 working_dir = temp_dir
Alan Viverette3e57a4a2017-08-11 15:49:47 -0400402
Alan Viverettec960cfb2017-12-04 13:09:22 -0500403 if not maven_lib_info:
404 print_e('Failed to detect artifacts')
405 return False
406
Jeff Gastonc302bb92018-03-23 13:53:48 -0400407 # extract some files (for example, AndroidManifest.xml) from any relevant artifacts
Alan Viveretted4527e62017-05-11 15:03:25 -0400408 for info in maven_lib_info.values():
Alan Viveretted8ce7222017-12-11 17:24:43 -0500409 transform_maven_lib(working_dir, info, extract_res)
Dan Willemsen814152e2017-11-06 13:22:11 -0800410
Colin Cross74683bc2018-04-11 17:36:18 -0700411 # generate a single Android.bp that specifies to use all of the above artifacts
412 makefile = os.path.join(working_dir, 'Android.bp')
Alan Viverette4ec9a172018-02-20 16:19:31 -0500413 with open(makefile, 'w') as f:
Anton Hanssonbd2021c2021-04-06 19:21:34 +0000414 args = ["pom2bp"]
Aurimas Liutikas6e87bbf2021-07-30 10:04:05 -0700415 args.extend(["-sdk-version", "31"])
Anton Hanssonbd2021c2021-04-06 19:21:34 +0000416 args.extend(["-default-min-sdk-version", "24"])
Jeff Gaston1cc06092018-03-28 15:51:02 -0400417 if include_static_deps:
418 args.append("-static-deps")
Jeff Gaston54868ee2018-04-25 19:43:35 -0400419 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 -0400420 args.extend(["-rewrite=^" + name + "$=" + maven_to_make[name]['name'] for name in rewriteNames])
Alan Viverettecdfc9892021-08-31 19:35:58 +0000421 args.extend(["-rewrite=^" + key + "$=" + value for key, value in deps_rewrite.items()])
422 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]])
423 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 -0400424 args.extend(["-host=" + name for name in maven_to_make if maven_to_make[name].get('host')])
Tony Mak0f658752019-07-19 11:11:05 +0100425 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 -0400426 args.extend(["."])
Dan Willemsen814152e2017-11-06 13:22:11 -0800427 subprocess.check_call(args, stdout=f, cwd=working_dir)
Alan Viverette95f6d362017-04-06 09:40:50 -0400428
429 # Replace the old directory.
Jeff Gastonc302bb92018-03-23 13:53:48 -0400430 output_dir = os.path.join(cwd, transformed_dir)
Alan Viverette3e57a4a2017-08-11 15:49:47 -0400431 mv(working_dir, output_dir)
Alan Viverettec960cfb2017-12-04 13:09:22 -0500432 return True
Alan Viverette95f6d362017-04-06 09:40:50 -0400433
Jeff Gastonc302bb92018-03-23 13:53:48 -0400434# 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 -0500435def transform_maven_lib(working_dir, artifact_info, extract_res):
Dan Willemsen814152e2017-11-06 13:22:11 -0800436 # Move library into working dir
Jeff Gaston9edf86c2018-04-18 13:45:23 -0400437 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 -0400438 mv(artifact_info.dir, new_dir)
Dan Willemsen814152e2017-11-06 13:22:11 -0800439
Alan Viverettec960cfb2017-12-04 13:09:22 -0500440 matcher = artifact_pattern.match(artifact_info.file)
441 maven_lib_name = artifact_info.key
Alan Viveretted4527e62017-05-11 15:03:25 -0400442 maven_lib_vers = matcher.group(2)
Alan Viverettec960cfb2017-12-04 13:09:22 -0500443 maven_lib_type = artifact_info.file[-3:]
Alan Viveretted4527e62017-05-11 15:03:25 -0400444
Alan Viverettef3c12722021-08-30 19:50:33 +0000445 group_artifact = artifact_info.key
446 make_lib_name = maven_to_make[group_artifact]['name']
447 make_dir_name = maven_to_make[group_artifact]['path']
Alan Viveretted4527e62017-05-11 15:03:25 -0400448
Alan Viverette129555e2018-01-30 09:57:57 -0500449 artifact_file = os.path.join(new_dir, artifact_info.file)
450
Colin Cross59b59db2018-04-24 13:58:05 -0700451 if maven_lib_type == "aar":
452 if extract_res:
453 target_dir = os.path.join(working_dir, make_dir_name)
454 if not os.path.exists(target_dir):
455 os.makedirs(target_dir)
Dan Willemsen814152e2017-11-06 13:22:11 -0800456
Alan Viverettec960cfb2017-12-04 13:09:22 -0500457 process_aar(artifact_file, target_dir)
Alan Viveretted4527e62017-05-11 15:03:25 -0400458
Colin Cross59b59db2018-04-24 13:58:05 -0700459 with zipfile.ZipFile(artifact_file) as zip:
460 manifests_dir = os.path.join(working_dir, "manifests")
461 zip.extract("AndroidManifest.xml", os.path.join(manifests_dir, make_lib_name))
Dan Willemsend677b602017-11-08 22:13:17 -0800462
Alan Viverettef5cb0e62017-11-17 15:15:23 -0500463 print(maven_lib_vers, ":", maven_lib_name, "->", make_lib_name)
Alan Viveretted4527e62017-05-11 15:03:25 -0400464
Alan Viverette95f6d362017-04-06 09:40:50 -0400465
Alan Viverettec960cfb2017-12-04 13:09:22 -0500466def process_aar(artifact_file, target_dir):
Alan Viverette95f6d362017-04-06 09:40:50 -0400467 # Extract AAR file to target_dir.
468 with zipfile.ZipFile(artifact_file) as zip:
469 zip.extractall(target_dir)
470
Dan Willemsen814152e2017-11-06 13:22:11 -0800471 # Remove classes.jar
Alan Viverette95f6d362017-04-06 09:40:50 -0400472 classes_jar = os.path.join(target_dir, "classes.jar")
473 if os.path.exists(classes_jar):
Dan Willemsen814152e2017-11-06 13:22:11 -0800474 os.remove(classes_jar)
Alan Viverette95f6d362017-04-06 09:40:50 -0400475
476 # Remove or preserve empty dirs.
477 for root, dirs, files in os.walk(target_dir):
478 for dir in dirs:
479 dir_path = os.path.join(root, dir)
480 if not os.listdir(dir_path):
481 os.rmdir(dir_path)
482
483 # Remove top-level cruft.
484 for file in blacklist_files:
485 file_path = os.path.join(target_dir, file)
486 if os.path.exists(file_path):
487 os.remove(file_path)
488
Alan Viverettef17c9402017-07-19 12:57:40 -0400489
Saeid Farivar Asanjan54cd34e2021-10-01 16:47:54 +0000490class GMavenArtifact(object):
491 # A map from group:library to the latest available version
492 key_versions_map = {}
493 def __init__(self, artifact_glob):
494 try:
495 (group, library, version, ext) = artifact_glob.split(':')
496 except ValueError:
497 raise ValueError(f'Error in {artifact_glob} expected: group:library:version:ext')
498
499 if not group or not library or not version or not ext:
500 raise ValueError(f'Error in {artifact_glob} expected: group:library:version:ext')
501
502 self.group = group
503 self.group_path = group.replace('.', '/')
504 self.library = library
505 self.key = f'{group}:{library}'
506 self.version = version
507 self.ext = ext
508
509 def get_pom_file_url(self):
510 return f'{GMAVEN_BASE_URL}/{self.group_path}/{self.library}/{self.version}/{self.library}-{self.version}.pom'
511
512 def get_artifact_url(self):
513 return f'{GMAVEN_BASE_URL}/{self.group_path}/{self.library}/{self.version}/{self.library}-{self.version}.{self.ext}'
514
515 def get_latest_version(self):
516 latest_version = GMavenArtifact.key_versions_map[self.key] \
517 if self.key in GMavenArtifact.key_versions_map else None
518
519 if not latest_version:
520 print(f'Fetching latest version for {self.key}')
521 group_index_url = f'{GMAVEN_BASE_URL}/{self.group_path}/group-index.xml'
522 import xml.etree.ElementTree as ET
523 tree = ET.parse(urllib.request.urlopen(group_index_url))
524 root = tree.getroot()
525 libraries = root.findall('./*[@versions]')
526 for library in libraries:
527 key = f'{root.tag}:{library.tag}'
528 GMavenArtifact.key_versions_map[key] = library.get('versions').split(',')[-1]
529 latest_version = GMavenArtifact.key_versions_map[self.key]
530 return latest_version
531
532
533def fetch_gmaven_artifact(artifact):
534 """Fetch a GMaven artifact.
535
536 Downloads a GMaven artifact
537 (https://developer.android.com/studio/build/dependencies#gmaven-access)
538
539 Args:
540 artifact_glob: an instance of GMavenArtifact.
541 """
542 download_to = os.path.join('gmaven', artifact.group, artifact.library, artifact.version)
543
544 _DownloadFileToDisk(artifact.get_pom_file_url(), os.path.join(download_to, f'{artifact.library}-{artifact.version}.pom'))
545 _DownloadFileToDisk(artifact.get_artifact_url(), os.path.join(download_to, f'{artifact.library}-{artifact.version}.{artifact.ext}'))
546
547 return download_to
548
549
550def _DownloadFileToDisk(url, filepath):
551 """Download the file at URL to the location dictated by the path.
552
553 Args:
554 url: Remote URL to download file from.
555 filepath: Filesystem path to write the file to.
556 """
557 print(f'Downloading URL: {url}')
558 file_data = urllib.request.urlopen(url)
559
560 try:
561 os.makedirs(os.path.dirname(filepath))
562 except os.error:
563 # This is a common situation - os.makedirs fails if dir already exists.
564 pass
565 try:
566 with open(filepath, 'wb') as f:
567 f.write(six.ensure_binary(file_data.read()))
568 except:
569 os.remove(os.path.dirname(filepath))
570 raise
571
572
Alan Viverettecd3de262017-08-14 09:51:30 -0400573def fetch_artifact(target, build_id, artifact_path):
Jeff Sharkeyabe16df2021-05-25 10:09:03 -0600574 global args
Jiyong Park1d1c9632018-05-29 17:45:27 +0900575 download_to = os.path.join('.', os.path.dirname(artifact_path))
576 print('Fetching %s from %s ...' % (artifact_path, target))
577 if not os.path.exists(download_to):
578 os.makedirs(download_to)
Jeff Sharkeyabe16df2021-05-25 10:09:03 -0600579 if args.beyond_corp:
580 fetch_cmd = [FETCH_ARTIFACT_BEYOND_CORP, '--use_oauth2',
581 '--bid', str(build_id), '--target', target, artifact_path, download_to]
582 else:
583 fetch_cmd = [FETCH_ARTIFACT,
584 '--bid', str(build_id), '--target', target, artifact_path, download_to]
Jeff Gaston97a9b762018-10-02 15:15:12 -0400585 print("Running: " + ' '.join(fetch_cmd))
Alan Viverette45837092017-05-12 14:50:53 -0400586 try:
Alan Viverettecd3de262017-08-14 09:51:30 -0400587 subprocess.check_output(fetch_cmd, stderr=subprocess.STDOUT)
Alan Viverette45837092017-05-12 14:50:53 -0400588 except subprocess.CalledProcessError:
Jeff Gaston13e38412018-02-06 14:45:36 -0500589 print_e('FAIL: Unable to retrieve %s artifact for build ID %s' % (artifact_path, build_id))
Alan Viverettec1c32b62017-12-20 09:40:36 -0500590 print_e('Please make sure you are authenticated for build server access!')
Alan Viverette45837092017-05-12 14:50:53 -0400591 return None
592 return artifact_path
593
594
Anton Hansson1d01a032018-04-09 10:29:37 +0100595def fetch_artifacts(target, build_id, artifact_dict):
596 for artifact, target_path in artifact_dict.items():
597 artifact_path = fetch_artifact(target, build_id.url_id, artifact)
598 if not artifact_path:
599 return False
600 mv(artifact_path, target_path)
601 return True
602
603
Alan Viverette129555e2018-01-30 09:57:57 -0500604def extract_artifact(artifact_path):
Alan Viverette45837092017-05-12 14:50:53 -0400605 # Unzip the repo archive into a separate directory.
Alan Viverette3e57a4a2017-08-11 15:49:47 -0400606 repo_dir = os.path.basename(artifact_path)[:-4]
Alan Viverette45837092017-05-12 14:50:53 -0400607 with zipfile.ZipFile(artifact_path) as zipFile:
Alan Viverette3e57a4a2017-08-11 15:49:47 -0400608 zipFile.extractall(repo_dir)
Alan Viverette3e57a4a2017-08-11 15:49:47 -0400609 return repo_dir
610
611
Alan Viverette7e897e22018-03-09 15:24:10 -0500612def fetch_and_extract(target, build_id, file, artifact_path=None):
613 if not artifact_path:
614 artifact_path = fetch_artifact(target, build_id, file)
Alan Viverette129555e2018-01-30 09:57:57 -0500615 if not artifact_path:
616 return None
617 return extract_artifact(artifact_path)
618
619
Saeid Farivar Asanjan54cd34e2021-10-01 16:47:54 +0000620def update_gmaven(gmaven_artifacts):
621 artifacts = [GMavenArtifact(artifact) for artifact in gmaven_artifacts]
622 for artifact in artifacts:
623 if artifact.version == 'latest':
624 artifact.version = artifact.get_latest_version()
625
626 artifact_dirs = [fetch_gmaven_artifact(artifact) for artifact in artifacts]
627 if not transform_maven_repos(['gmaven'], gmaven_dir, extract_res=False):
628 return []
629 return [artifact.key for artifact in artifacts]
630
631
Jeff Gaston08a2ee42018-05-07 18:08:41 -0400632def update_androidx(target, build_id, local_file):
Jeff Gastonbbd6bfc2018-03-27 17:35:49 -0400633 if build_id:
Anthony Chenacbb4872018-07-02 11:22:48 -0700634 repo_file = 'top-of-tree-m2repository-all-%s.zip' % build_id.fs_id
Jeff Gastonbbd6bfc2018-03-27 17:35:49 -0400635 repo_dir = fetch_and_extract(target, build_id.url_id, repo_file, None)
636 else:
637 repo_dir = fetch_and_extract(target, None, None, local_file)
638 if not repo_dir:
639 print_e('Failed to extract AndroidX repository')
640 return False
641
Tony Mak0f658752019-07-19 11:11:05 +0100642 # Keep JavaPlugins.bp file untounched.
643 java_plugins_bp_path = os.path.join(androidx_dir, 'JavaPlugins.bp')
644 tmp_java_plugins_bp_path = os.path.join('/tmp', 'JavaPlugins.bp')
645 mv(java_plugins_bp_path, tmp_java_plugins_bp_path)
Jeff Gastonbbd6bfc2018-03-27 17:35:49 -0400646
Tony Mak0f658752019-07-19 11:11:05 +0100647 # Transform the repo archive into a Makefile-compatible format.
648 if not transform_maven_repos([repo_dir], androidx_dir, extract_res=False):
649 return False
650
651 # Import JavaPlugins.bp in Android.bp.
652 makefile = os.path.join(androidx_dir, 'Android.bp')
653 with open(makefile, "a+") as f:
654 f.write('\nbuild = ["JavaPlugins.bp"]\n')
655 mv(tmp_java_plugins_bp_path, java_plugins_bp_path)
656
657 return True
Jeff Gastonbbd6bfc2018-03-27 17:35:49 -0400658
Alan Viverette6dc45752020-04-16 14:56:20 +0000659
Jeff Gaston782c3e32018-02-06 14:36:17 -0500660def update_jetifier(target, build_id):
661 repo_file = 'jetifier-standalone.zip'
662 repo_dir = fetch_and_extract(target, build_id.url_id, repo_file)
663 if not repo_dir:
664 print_e('Failed to extract Jetifier')
665 return False
666
667 rm(jetifier_dir)
Jeff Gaston553a4372018-03-29 18:34:22 -0400668 mv(os.path.join(repo_dir, 'jetifier-standalone'), jetifier_dir)
669 os.chmod(os.path.join(jetifier_dir, 'bin', 'jetifier-standalone'), 0o755)
Jeff Gaston782c3e32018-02-06 14:36:17 -0500670 return True
671
Alan Viverette7e897e22018-03-09 15:24:10 -0500672
Alan Viverette6dc45752020-04-16 14:56:20 +0000673def update_constraint(local_file):
Jeff Gaston9edf86c2018-04-18 13:45:23 -0400674 repo_dir = extract_artifact(local_file)
675 if not repo_dir:
Alan Viverette6dc45752020-04-16 14:56:20 +0000676 print_e('Failed to extract Constraint Layout')
Jeff Gaston9edf86c2018-04-18 13:45:23 -0400677 return False
678 return transform_maven_repos([repo_dir], os.path.join(extras_dir, 'constraint-layout-x'), extract_res=False)
679
Alan Viverette45837092017-05-12 14:50:53 -0400680
Jeff Gaston6e7e7502018-04-04 00:22:45 -0400681def update_material(file):
682 design_dir = extract_artifact(file)
683 if not design_dir:
Alan Viverette6dc45752020-04-16 14:56:20 +0000684 print_e('Failed to extract Material Design Components')
Jeff Gaston6e7e7502018-04-04 00:22:45 -0400685 return False
686
687 # Don't bother extracting resources -- this should only be used with AAPT2.
688 return transform_maven_repos([design_dir],
689 os.path.join(extras_dir, 'material-design-x'), extract_res=False)
690
Paul Duffin1fed8212021-10-29 17:02:38 +0100691def update_framework(target, build_id, sdk_dir):
Anton Hansson83f92172020-03-26 11:12:03 +0000692 api_scope_list = ['public', 'system', 'test', 'module-lib', 'system-server']
Sundong Ahn66091f22018-08-29 18:54:28 +0900693 if sdk_dir == 'current':
694 api_scope_list.append('core')
695
696 for api_scope in api_scope_list:
Jiyong Park1d1c9632018-05-29 17:45:27 +0900697 target_dir = path(sdk_dir, api_scope)
Sundong Ahn66091f22018-08-29 18:54:28 +0900698 if api_scope == 'core':
699 artifact_to_path = {'core.current.stubs.jar': path(target_dir, 'android.jar')}
700 else:
Paul Duffin6815a312021-10-28 13:02:51 +0100701 artifact_to_path = {
702 'apistubs/android/' + api_scope + '/*.jar': path(target_dir, '*'),
703 }
704 if api_scope == 'public' or api_scope == 'module-lib':
705 # Distinct core-for-system-modules.jar files are only provided
706 # for the public and module-lib API surfaces.
707 artifact_to_path['system-modules/' + api_scope + '/core-for-system-modules.jar'] = path(target_dir, '*')
Anton Hansson1d01a032018-04-09 10:29:37 +0100708
Paul Duffin1fed8212021-10-29 17:02:38 +0100709 if not fetch_artifacts(target, build_id, artifact_to_path):
Anton Hansson1d01a032018-04-09 10:29:37 +0100710 return False
711
Jiyong Park1d1c9632018-05-29 17:45:27 +0900712 if api_scope == 'public':
Anton Hansson1d01a032018-04-09 10:29:37 +0100713 # Fetch a few artifacts from the public sdk.
Sundong Ahn66091f22018-08-29 18:54:28 +0900714 artifact = 'sdk-repo-linux-platforms-%s.zip' % build_id.fs_id
Paul Duffin1fed8212021-10-29 17:02:38 +0100715 artifact_path = fetch_artifact(target, build_id.url_id, artifact)
Anton Hansson9709fd42018-04-03 16:52:13 +0100716 if not artifact_path:
717 return False
Anton Hansson1d01a032018-04-09 10:29:37 +0100718
719 with zipfile.ZipFile(artifact_path) as zipFile:
Colin Crossd338d702020-07-10 19:17:54 -0700720 extra_files = [
721 'android.jar',
722 'framework.aidl',
723 'uiautomator.jar',
Colin Crossd338d702020-07-10 19:17:54 -0700724 'data/annotations.zip',
725 'data/api-versions.xml']
726 for filename in extra_files:
Anton Hanssona26e4812020-03-25 12:54:39 +0000727 matches = list(filter(lambda path: filename in path, zipFile.namelist()))
728 if len(matches) != 1:
729 print_e('Expected 1 file named \'%s\' in zip %s, found %d' %
730 (filename, zipFile.filename, len(matches)))
731 return False
732 zip_path = matches[0]
733 src_path = zipFile.extract(zip_path)
734 dst_path = path(target_dir, filename)
735 mv(src_path, dst_path)
Anton Hansson9709fd42018-04-03 16:52:13 +0100736
Anton Hansson73be1512021-06-24 10:56:05 +0100737 # Filtered API DB is currently only available for "public"
Paul Duffin1fed8212021-10-29 17:02:38 +0100738 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 +0100739
Alan Viverettecd3de262017-08-14 09:51:30 -0400740 return True
Alan Viverette45837092017-05-12 14:50:53 -0400741
Sundong Ahncc34cc32018-07-11 15:18:47 +0900742def update_makefile(build_id):
743 template = '"%s",\n\
744 "current"'
745 makefile = os.path.join(git_dir, 'Android.bp')
746
747 with open(makefile, 'r+') as f:
748 contents = f.read().replace('"current"', template % build_id)
749 f.seek(0)
750 f.write(contents)
751
752 return True
Alan Viverette45837092017-05-12 14:50:53 -0400753
Paul Duffin1fed8212021-10-29 17:02:38 +0100754def finalize_sdk(target, build_id, sdk_version):
Anton Hansson1d01a032018-04-09 10:29:37 +0100755 target_finalize_dir = '%d' % sdk_version
Anton Hansson9709fd42018-04-03 16:52:13 +0100756
Anton Hanssonaa554c02020-04-30 14:06:20 +0100757 for api_scope in ['public', 'system', 'test', 'module-lib', 'system-server']:
Sundong Ahn66091f22018-08-29 18:54:28 +0900758 artifact_to_path = {'apistubs/android/' + api_scope + '/api/*.txt':
759 path(target_finalize_dir, api_scope, 'api', '*')}
760
Paul Duffin1fed8212021-10-29 17:02:38 +0100761 if not fetch_artifacts(target, build_id, artifact_to_path):
Sundong Ahn66091f22018-08-29 18:54:28 +0900762 return False
763
Paul Duffin1fed8212021-10-29 17:02:38 +0100764 return update_framework(target, build_id, target_finalize_dir) \
Sundong Ahncc34cc32018-07-11 15:18:47 +0900765 and update_makefile(target_finalize_dir)
Anton Hansson9709fd42018-04-03 16:52:13 +0100766
Anton Hansson9709fd42018-04-03 16:52:13 +0100767
Paul Duffin1fed8212021-10-29 17:02:38 +0100768def update_framework_current(target, build_id):
769 return update_framework(target, build_id, current_path)
Anton Hansson9709fd42018-04-03 16:52:13 +0100770
771
Alan Viverettec1c32b62017-12-20 09:40:36 -0500772def update_buildtools(target, arch, build_id):
Jeff Gaston13e38412018-02-06 14:45:36 -0500773 artifact_path = fetch_and_extract(target, build_id.url_id,
774 "sdk-repo-%s-build-tools-%s.zip" % (arch, build_id.fs_id))
Alan Viverettec1c32b62017-12-20 09:40:36 -0500775 if not artifact_path:
776 return False
777
778 top_level_dir = os.listdir(artifact_path)[0]
779 src_path = os.path.join(artifact_path, top_level_dir)
780 dst_path = path(buildtools_dir, arch)
Colin Cross20648d32021-02-12 13:30:51 -0800781
782 # There are a few libraries that have been manually added to the
783 # build tools, copy them from the destination back to the source
784 # before the destination is overwritten.
785 files_to_save = (
786 'lib64/libconscrypt_openjdk_jni.dylib',
787 'lib64/libconscrypt_openjdk_jni.so',
788 'bin/lib64/libwinpthread-1.dll',
789 )
790 for file in files_to_save:
791 src_file = os.path.join(dst_path, file)
792 dst_file = os.path.join(src_path, file)
793 if os.path.exists(dst_path):
794 mv(src_file, dst_file)
795
Alan Viverettec1c32b62017-12-20 09:40:36 -0500796 mv(src_path, dst_path)
797
798 # Move all top-level files to /bin and make them executable
799 bin_path = path(dst_path, 'bin')
800 top_level_files = filter(lambda e: os.path.isfile(path(dst_path, e)), os.listdir(dst_path))
801 for file in top_level_files:
802 src_file = path(dst_path, file)
803 dst_file = path(bin_path, file)
804 mv(src_file, dst_file)
805 os.chmod(dst_file, 0o755)
806
Colin Cross6673ceb2021-02-12 13:14:14 -0800807 # Make the files under lld-bin executable
808 lld_bin_files = os.listdir(os.path.join(dst_path, 'lld-bin'))
809 for file in lld_bin_files:
810 os.chmod(os.path.join(dst_path, 'lld-bin', file), 0o755)
811
Alan Viverettec1c32b62017-12-20 09:40:36 -0500812 # Remove renderscript
813 rm(path(dst_path, 'renderscript'))
814
815 return True
816
817
Alan Viverettecd3de262017-08-14 09:51:30 -0400818def append(text, more_text):
819 if text:
820 return "%s, %s" % (text, more_text)
821 return more_text
Alan Viverette45837092017-05-12 14:50:53 -0400822
Alan Viverette95f6d362017-04-06 09:40:50 -0400823
Jeff Gaston13e38412018-02-06 14:45:36 -0500824class buildId(object):
825 def __init__(self, url_id, fs_id):
826 # id when used in build server urls
827 self.url_id = url_id
828 # id when used in build commands
829 self.fs_id = fs_id
830
Jeff Gastonb9b09052018-02-05 14:16:05 -0500831def getBuildId(args):
Jeff Gaston13e38412018-02-06 14:45:36 -0500832 # must be in the format 12345 or P12345
Jeff Gastonb9b09052018-02-05 14:16:05 -0500833 source = args.source
Jeff Gaston13e38412018-02-06 14:45:36 -0500834 number_text = source[:]
835 presubmit = False
836 if number_text.startswith("P"):
837 presubmit = True
838 number_text = number_text[1:]
839 if not number_text.isnumeric():
Alan Viverette7e897e22018-03-09 15:24:10 -0500840 return None
Jeff Gaston13e38412018-02-06 14:45:36 -0500841 url_id = source
842 fs_id = url_id
843 if presubmit:
844 fs_id = "0"
845 args.file = False
846 return buildId(url_id, fs_id)
Jeff Gastonb9b09052018-02-05 14:16:05 -0500847
Colin Cross573e1212018-02-12 14:59:52 -0800848def getFile(args):
849 source = args.source
850 if not source.isnumeric():
851 return args.source
Alan Viverette7e897e22018-03-09 15:24:10 -0500852 return None
Colin Cross573e1212018-02-12 14:59:52 -0800853
Alan Viverette4ec9a172018-02-20 16:19:31 -0500854
855def script_relative(rel_path):
Jeff Gastona68a8d42018-03-23 14:00:13 -0400856 return os.path.join(script_dir, rel_path)
Alan Viverette4ec9a172018-02-20 16:19:31 -0500857
858
Jeff Gastoncc296a82018-03-23 14:33:24 -0400859def uncommittedChangesExist():
860 try:
861 # Make sure we don't overwrite any pending changes.
862 diffCommand = "cd " + git_dir + " && git diff --quiet"
863 subprocess.check_call(diffCommand, shell=True)
864 subprocess.check_call(diffCommand + " --cached", shell=True)
865 return False
866 except subprocess.CalledProcessError:
867 return True
868
869
Jeff Gastona7fba9b2018-03-26 23:48:51 -0400870rm(temp_dir)
Alan Viveretted4527e62017-05-11 15:03:25 -0400871parser = argparse.ArgumentParser(
Alan Viverette45837092017-05-12 14:50:53 -0400872 description=('Update current prebuilts'))
Alan Viveretted4527e62017-05-11 15:03:25 -0400873parser.add_argument(
Saeid Farivar Asanjan54cd34e2021-10-01 16:47:54 +0000874 'source', nargs='?',
Alan Viverette129555e2018-01-30 09:57:57 -0500875 help='Build server build ID or local Maven ZIP file')
876parser.add_argument(
Jeff Gaston6e7e7502018-04-04 00:22:45 -0400877 '-m', '--material', action="store_true",
Alan Viverette6dc45752020-04-16 14:56:20 +0000878 help='If specified, updates only Material Design Components')
Jeff Gaston6e7e7502018-04-04 00:22:45 -0400879parser.add_argument(
Alan Viverette3e57a4a2017-08-11 15:49:47 -0400880 '-c', '--constraint', action="store_true",
881 help='If specified, updates only Constraint Layout')
882parser.add_argument(
Jeff Gaston782c3e32018-02-06 14:36:17 -0500883 '-j', '--jetifier', action="store_true",
884 help='If specified, updates only Jetifier')
885parser.add_argument(
Alan Viverette5bfe05b2017-06-06 14:21:29 -0400886 '-p', '--platform', action="store_true",
887 help='If specified, updates only the Android Platform')
Alan Viverettec1c32b62017-12-20 09:40:36 -0500888parser.add_argument(
Anton Hansson9709fd42018-04-03 16:52:13 +0100889 '-f', '--finalize_sdk', type=int,
Anton Hansson4bcebac2022-04-07 17:23:18 +0100890 help='Finalize the build as the specified SDK version. Must be used together with -e')
891parser.add_argument(
892 '-e', '--finalize_extension', type=int,
893 help='Finalize the build as the specified extension SDK version. Must be used together with -f')
Anton Hansson57a1b142022-04-07 17:27:41 +0100894parser.add_argument('--bug', type=int, help='The bug number to add to the commit message.')
Anton Hansson9709fd42018-04-03 16:52:13 +0100895parser.add_argument(
Paul Duffin1fed8212021-10-29 17:02:38 +0100896 '--sdk_target',
897 default=framework_sdk_target,
898 help='If specified, the name of the build target from which to retrieve the SDK when -p or -f is specified.')
899parser.add_argument(
Alan Viverettec1c32b62017-12-20 09:40:36 -0500900 '-b', '--buildtools', action="store_true",
901 help='If specified, updates only the Build Tools')
Jeff Gastoncc296a82018-03-23 14:33:24 -0400902parser.add_argument(
Alan Viverette6dc45752020-04-16 14:56:20 +0000903 '-x', '--androidx', action="store_true",
904 help='If specified, updates only the Jetpack (androidx) libraries excluding those covered by other arguments')
Jeff Gaston41fd5e62018-04-25 17:02:02 -0400905parser.add_argument(
Saeid Farivar Asanjan54cd34e2021-10-01 16:47:54 +0000906 '-g', '--gmaven', action="store_true",
907 help='If specified, updates only the artifact from GMaven libraries excluding those covered by other arguments')
908parser.add_argument(
Jeff Gastoncc296a82018-03-23 14:33:24 -0400909 '--commit-first', action="store_true",
910 help='If specified, then if uncommited changes exist, commit before continuing')
Jeff Sharkeyabe16df2021-05-25 10:09:03 -0600911parser.add_argument(
912 '--beyond-corp', action="store_true",
913 help='If specified, then fetch artifacts with tooling that works on BeyondCorp devices')
Alan Viveretted4527e62017-05-11 15:03:25 -0400914args = parser.parse_args()
Jeff Gaston56fe2762018-02-06 14:54:37 -0500915args.file = True
Anton Hansson4bcebac2022-04-07 17:23:18 +0100916
Saeid Farivar Asanjan54cd34e2021-10-01 16:47:54 +0000917if not args.source and (args.platform or args.buildtools \
918 or args.jetifier or args.androidx or args.material \
919 or args.finalize_sdk or args.constraint):
Alan Viverette129555e2018-01-30 09:57:57 -0500920 parser.error("You must specify a build ID or local Maven ZIP file")
Alan Viveretted4527e62017-05-11 15:03:25 -0400921 sys.exit(1)
Saeid Farivar Asanjan54cd34e2021-10-01 16:47:54 +0000922if not (args.gmaven or args.platform or args.buildtools \
Alan Viverette6dc45752020-04-16 14:56:20 +0000923 or args.jetifier or args.androidx or args.material \
Anton Hansson4bcebac2022-04-07 17:23:18 +0100924 or args.finalize_sdk or args.finalize_extension or args.constraint):
Alan Viverettec1c32b62017-12-20 09:40:36 -0500925 parser.error("You must specify at least one target to update")
Alan Viverettecd3de262017-08-14 09:51:30 -0400926 sys.exit(1)
Saeid Farivar Asanjan54cd34e2021-10-01 16:47:54 +0000927if (args.constraint or args.material or args.androidx or args.gmaven) \
Colin Cross74683bc2018-04-11 17:36:18 -0700928 and which('pom2bp') is None:
Louis Pullen-Freilich61bb70e2019-04-09 16:15:32 +0100929 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 -0500930 sys.exit(1)
Anton Hansson4bcebac2022-04-07 17:23:18 +0100931if (args.finalize_sdk is None) != (args.finalize_extension is None):
932 parser.error("Either both or neither of -e and -f must be specified.")
933 sys.exit(1)
Anton Hansson57a1b142022-04-07 17:27:41 +0100934if args.finalize_sdk and not args.bug:
935 parser.error("Specifying a bug ID with --bug is required when finalizing an SDK.")
936 sys.exit(1)
Alan Viveretted4527e62017-05-11 15:03:25 -0400937
Jeff Gastoncc296a82018-03-23 14:33:24 -0400938if uncommittedChangesExist():
939 if args.commit_first:
940 subprocess.check_call("cd " + git_dir + " && git add -u", shell=True)
941 subprocess.check_call("cd " + git_dir + " && git commit -m 'save working state'", shell=True)
942
943if uncommittedChangesExist():
Anton Hansson10861a02018-04-06 13:57:08 +0100944 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 -0400945 sys.exit(1)
946
Anton Hansson57a1b142022-04-07 17:27:41 +0100947commit_message_suffix = ""
948if args.bug:
949 commit_message_suffix = "\n\nBug: %d" % args.bug
950
Alan Viveretted4527e62017-05-11 15:03:25 -0400951try:
Alan Viverettecd3de262017-08-14 09:51:30 -0400952 components = None
953 if args.constraint:
Jeff Gaston9edf86c2018-04-18 13:45:23 -0400954 if update_constraint_x(getFile(args)):
955 components = append(components, 'Constraint Layout X')
956 else:
957 print_e('Failed to update Constraint Layout X, aborting...')
Alan Viverettecd3de262017-08-14 09:51:30 -0400958 sys.exit(1)
Saeid Farivar Asanjan54cd34e2021-10-01 16:47:54 +0000959 if args.gmaven:
960 updated_artifacts = update_gmaven(gmaven_artifacts)
961 if updated_artifacts:
962 components = append(components, '\n'.join(updated_artifacts))
963 else:
964 print_e('Failed to update GMaven, aborting...')
965 sys.exit(1)
Jeff Gastonbbd6bfc2018-03-27 17:35:49 -0400966 if args.androidx:
Jeff Gaston17ccf8f2018-08-29 11:33:19 -0400967 if update_androidx('androidx', \
Jeff Gastonbbd6bfc2018-03-27 17:35:49 -0400968 getBuildId(args), getFile(args)):
969 components = append(components, 'AndroidX')
970 else:
971 print_e('Failed to update AndroidX, aborting...')
972 sys.exit(1)
Jeff Gaston782c3e32018-02-06 14:36:17 -0500973 if args.jetifier:
Jeff Gaston17ccf8f2018-08-29 11:33:19 -0400974 if update_jetifier('androidx', getBuildId(args)):
Jeff Gaston782c3e32018-02-06 14:36:17 -0500975 components = append(components, 'Jetifier')
976 else:
977 print_e('Failed to update Jetifier, aborting...')
978 sys.exit(1)
Anton Hanssonbe15e8c2018-04-26 17:35:45 +0100979 if args.platform or args.finalize_sdk:
Paul Duffin1fed8212021-10-29 17:02:38 +0100980 if update_framework_current(args.sdk_target, getBuildId(args)):
Alan Viverettecd3de262017-08-14 09:51:30 -0400981 components = append(components, 'platform SDK')
982 else:
Alan Viverettef5cb0e62017-11-17 15:15:23 -0500983 print_e('Failed to update platform SDK, aborting...')
Alan Viverettecd3de262017-08-14 09:51:30 -0400984 sys.exit(1)
Anton Hansson9709fd42018-04-03 16:52:13 +0100985 if args.finalize_sdk:
Anton Hanssonbe15e8c2018-04-26 17:35:45 +0100986 n = args.finalize_sdk
Anton Hansson4bcebac2022-04-07 17:23:18 +0100987 if not finalize_sdk(args.sdk_target, getBuildId(args), n):
Anton Hanssonbe15e8c2018-04-26 17:35:45 +0100988 print_e('Failed to finalize SDK %d, aborting...' % n)
Anton Hansson9709fd42018-04-03 16:52:13 +0100989 sys.exit(1)
Anton Hansson4bcebac2022-04-07 17:23:18 +0100990 # We commit the finalized dir separately from the current sdk update.
991 msg = "Import final sdk version %d from build %s%s" % (n, getBuildId(args).url_id, commit_message_suffix)
992 subprocess.check_call(['git', 'add', '%d' % n])
993 subprocess.check_call(['git', 'add', 'Android.bp'])
994 subprocess.check_call(['git', 'commit', '-m', msg])
995
996 # Finalize extension sdk level
997 cmd = extension_sdk_finalization_cmd.format(
998 bug=args.bug,
999 extension_version=args.finalize_extension,
1000 build_id=getBuildId(args).url_id)
1001 subprocess.check_call(cmd.split(' '), cwd=repo_root_dir.resolve())
Jeff Gaston6e7e7502018-04-04 00:22:45 -04001002 if args.material:
1003 if update_material(getFile(args)):
1004 components = append(components, 'intermediate-AndroidX Design Library')
1005 else:
1006 print_e('Failed to update intermediate-AndroidX Design Library, aborting...')
Alan Viverette129555e2018-01-30 09:57:57 -05001007 sys.exit(1)
Alan Viverettec1c32b62017-12-20 09:40:36 -05001008 if args.buildtools:
Jeff Gastonb9b09052018-02-05 14:16:05 -05001009 if update_buildtools('sdk_phone_armv7-sdk_mac', 'darwin', getBuildId(args)) \
1010 and update_buildtools('sdk_phone_x86_64-sdk', 'linux', getBuildId(args)) \
1011 and update_buildtools('sdk_phone_armv7-win_sdk', 'windows', getBuildId(args)):
Alan Viverettec1c32b62017-12-20 09:40:36 -05001012 components = append(components, 'build tools')
1013 else:
1014 print_e('Failed to update build tools, aborting...')
1015 sys.exit(1)
Jeff Gastonb70daa92018-03-29 20:10:22 -04001016
Jeff Gastonf12f3ce2018-03-23 16:41:24 -04001017
Alan Viveretted4527e62017-05-11 15:03:25 -04001018
Colin Cross941d9802018-05-03 21:37:57 -07001019 subprocess.check_call(['git', 'add', current_path, buildtools_dir])
Saeid Farivar Asanjan54cd34e2021-10-01 16:47:54 +00001020 if not args.source and args.gmaven:
1021 src_msg = "GMaven"
1022 elif not args.source.isnumeric():
Alan Viverette129555e2018-01-30 09:57:57 -05001023 src_msg = "local Maven ZIP"
1024 else:
Jeff Gaston13e38412018-02-06 14:45:36 -05001025 src_msg = "build %s" % (getBuildId(args).url_id)
Anton Hansson57a1b142022-04-07 17:27:41 +01001026 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 -04001027 subprocess.check_call(['git', 'commit', '-m', msg])
Anton Hanssonbe15e8c2018-04-26 17:35:45 +01001028 if args.finalize_sdk:
Anton Hansson4bcebac2022-04-07 17:23:18 +01001029 print('NOTE: Created three commits:')
1030 subprocess.check_call(['git', 'log', '-3', '--oneline'])
Alan Viverettef5cb0e62017-11-17 15:15:23 -05001031 print('Remember to test this change before uploading it to Gerrit!')
Alan Viveretted4527e62017-05-11 15:03:25 -04001032
1033finally:
1034 # Revert all stray files, including the downloaded zip.
1035 try:
1036 with open(os.devnull, 'w') as bitbucket:
1037 subprocess.check_call(['git', 'add', '-Af', '.'], stdout=bitbucket)
1038 subprocess.check_call(
Jeff Gaston9edf86c2018-04-18 13:45:23 -04001039 ['git', 'commit', '-m', 'COMMIT TO REVERT - RESET ME!!!', '--allow-empty'], stdout=bitbucket)
Alan Viveretted4527e62017-05-11 15:03:25 -04001040 subprocess.check_call(['git', 'reset', '--hard', 'HEAD~1'], stdout=bitbucket)
1041 except subprocess.CalledProcessError:
Alan Viverettef5cb0e62017-11-17 15:15:23 -05001042 print_e('ERROR: Failed cleaning up, manual cleanup required!!!')