blob: 6faecc8c133f0b5e00378315e6ca2a036a23bc0a [file] [log] [blame]
Mads Ager418d1ca2017-05-22 09:35:49 +02001# Copyright (c) 2016, the R8 project authors. Please see the AUTHORS file
2# for details. All rights reserved. Use of this source code is governed by a
3# BSD-style license that can be found in the LICENSE file.
4
5# Different utility functions used accross scripts
6
7import hashlib
Clément Béra3718ad02023-09-05 14:12:48 +02008import jdk
Søren Gjesse6e5e5842019-09-03 08:48:30 +02009import json
Mads Ager418d1ca2017-05-22 09:35:49 +020010import os
Tamas Kenez82efeb52017-06-12 13:56:22 +020011import re
Mads Ager418d1ca2017-05-22 09:35:49 +020012import shutil
13import subprocess
14import sys
Jean-Marie Henaff7a64eec2018-05-31 15:30:35 +020015import tarfile
Mads Ager418d1ca2017-05-22 09:35:49 +020016import tempfile
Morten Krogh-Jespersen16e925d2019-01-25 14:40:38 +010017import zipfile
Mads Ager418d1ca2017-05-22 09:35:49 +020018
Ian Zerny37097652019-04-11 13:13:27 +020019import defines
Christoffer Quist Adamsen65ef2982023-08-24 08:45:39 +020020from thread_utils import print_thread
Ian Zerny37097652019-04-11 13:13:27 +020021
Christoffer Quist Adamsen17879c12019-01-22 16:13:54 +010022ANDROID_JAR_DIR = 'third_party/android_jar/lib-v{api}'
23ANDROID_JAR = os.path.join(ANDROID_JAR_DIR, 'android.jar')
Ian Zerny3f54e222019-02-12 10:51:17 +010024TOOLS_DIR = defines.TOOLS_DIR
25REPO_ROOT = defines.REPO_ROOT
26THIRD_PARTY = defines.THIRD_PARTY
Christoffer Quist Adamsen4d9fc512022-08-11 19:59:44 +020027BUNDLETOOL_JAR_DIR = os.path.join(THIRD_PARTY, 'bundletool/bundletool-1.11.0')
28BUNDLETOOL_JAR = os.path.join(BUNDLETOOL_JAR_DIR, 'bundletool-all-1.11.0.jar')
Tamas Kenezfc34cd82017-07-13 12:43:57 +020029MEMORY_USE_TMP_FILE = 'memory_use.tmp'
Tamas Kenez02bff032017-07-18 12:13:58 +020030DEX_SEGMENTS_RESULT_PATTERN = re.compile('- ([^:]+): ([0-9]+)')
Rico Windaf9e8fb2023-10-10 09:25:26 +020031
Rico Windb65d75c2023-10-10 11:14:52 +020032DEPENDENCIES_DIR = os.path.join(THIRD_PARTY, 'dependencies')
33
Mads Ager12a56bc2017-11-27 11:51:25 +010034BUILD = os.path.join(REPO_ROOT, 'build')
Morten Krogh-Jespersen51db2b02020-11-11 12:49:26 +010035BUILD_JAVA_MAIN_DIR = os.path.join(BUILD, 'classes', 'java', 'main')
Mads Ager12a56bc2017-11-27 11:51:25 +010036LIBS = os.path.join(BUILD, 'libs')
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +020037CUSTOM_CONVERSION_DIR = os.path.join(THIRD_PARTY, 'openjdk',
38 'custom_conversion')
Mads Ager12a56bc2017-11-27 11:51:25 +010039GENERATED_LICENSE_DIR = os.path.join(BUILD, 'generatedLicense')
Mads Agera4911eb2017-11-22 13:19:36 +010040SRC_ROOT = os.path.join(REPO_ROOT, 'src', 'main', 'java')
Ian Zerny59dfa4c2019-10-25 10:34:36 +020041REPO_SOURCE = 'https://r8.googlesource.com/r8'
Søren Gjessedc9d8a22017-10-12 12:40:59 +020042
Rico Wind93755fb2023-10-09 13:29:29 +020043GRADLE_TASK_CLEAN_TEST = ':test:cleanTest'
44GRADLE_TASK_CONSOLIDATED_LICENSE = ':main:consolidatedLicense'
45GRADLE_TASK_KEEP_ANNO_JAR = ':keepanno:keepAnnoAnnotationsJar'
Ian Zernya6af7772023-11-21 14:05:57 +010046GRADLE_TASK_KEEP_ANNO_DOC = ':keepanno:keepAnnoAnnotationsDoc'
Rico Wind93755fb2023-10-09 13:29:29 +020047GRADLE_TASK_R8 = ':main:r8WithRelocatedDeps'
Christoffer Quist Adamsen31237c32023-10-13 10:59:53 +020048GRADLE_TASK_R8LIB = ':test:assembleR8LibWithRelocatedDeps'
49GRADLE_TASK_R8LIB_NO_DEPS = ':test:assembleR8LibNoDeps'
Ian Zerny077a73f2023-10-31 09:05:47 +010050GRADLE_TASK_THREADING_MODULE_BLOCKING = ':main:threadingModuleBlockingJar'
51GRADLE_TASK_THREADING_MODULE_SINGLE_THREADED = ':main:threadingModuleSingleThreadedJar'
Christoffer Quist Adamsen31237c32023-10-13 10:59:53 +020052GRADLE_TASK_SOURCE_JAR = ':test:packageSources'
Rico Wind93755fb2023-10-09 13:29:29 +020053GRADLE_TASK_SWISS_ARMY_KNIFE = ':main:swissArmyKnife'
54GRADLE_TASK_TEST = ':test:test'
Søren Gjesse397f1a12023-10-13 13:22:31 +020055GRADLE_TASK_ALL_TESTS_WITH_APPLY_MAPPING_JAR = ':test:rewriteTestsForR8LibWithRelocatedDeps'
Rico Wind9365e942024-03-27 12:58:05 +010056GRADLE_TASK_TESTBASE_WITH_APPLY_MAPPING_JAR = ':test:rewriteTestBaseForR8LibWithRelocatedDeps'
Søren Gjesse397f1a12023-10-13 13:22:31 +020057GRADLE_TASK_TEST_DEPS_JAR = ':test:packageTestDeps'
Søren Gjessea28c4612023-11-01 14:55:27 +010058GRADLE_TASK_TEST_JAR = ':test:relocateTestsForR8LibWithRelocatedDeps'
Rico Wind93755fb2023-10-09 13:29:29 +020059
Søren Gjessedc9d8a22017-10-12 12:40:59 +020060R8 = 'r8'
Tamas Kenez03ab76f2018-12-07 14:33:25 +010061R8LIB = 'r8lib'
Søren Gjessedc9d8a22017-10-12 12:40:59 +020062
Morten Krogh-Jespersen51db2b02020-11-11 12:49:26 +010063ALL_DEPS_JAR = os.path.join(LIBS, 'deps_all.jar')
Rico Wind74fab302017-10-02 07:25:33 +020064R8_JAR = os.path.join(LIBS, 'r8.jar')
Tamas Kenez03ab76f2018-12-07 14:33:25 +010065R8LIB_JAR = os.path.join(LIBS, 'r8lib.jar')
Rico Wind158ef9f2022-05-19 11:08:30 +020066R8LIB_MAP = '%s.map' % R8LIB_JAR
Mads Agerb10c07f2017-11-27 13:25:52 +010067R8_SRC_JAR = os.path.join(LIBS, 'r8-src.jar')
Tamas Kenez03ab76f2018-12-07 14:33:25 +010068R8LIB_EXCLUDE_DEPS_JAR = os.path.join(LIBS, 'r8lib-exclude-deps.jar')
Tamas Kenez180be092018-12-05 15:23:06 +010069R8_FULL_EXCLUDE_DEPS_JAR = os.path.join(LIBS, 'r8-full-exclude-deps.jar')
Ian Zerny077a73f2023-10-31 09:05:47 +010070THREADING_MODULE_BLOCKING_JAR = os.path.join(LIBS, 'threading-module-blocking.jar')
71THREADING_MODULE_SINGLE_THREADED_JAR = os.path.join(LIBS, 'threading-module-single-threaded.jar')
Ian Zerny161ff742022-01-20 12:39:40 +010072R8_TESTS_JAR = os.path.join(LIBS, 'r8tests.jar')
Rico Wind9365e942024-03-27 12:58:05 +010073R8_TESTBASE_JAR = os.path.join(LIBS, 'r8test_base.jar')
74R8LIB_TESTBASE_JAR = os.path.join(LIBS, 'r8libtestbase-cf.jar')
Ian Zerny161ff742022-01-20 12:39:40 +010075R8LIB_TESTS_JAR = os.path.join(LIBS, 'r8libtestdeps-cf.jar')
76R8_TESTS_DEPS_JAR = os.path.join(LIBS, 'test_deps_all.jar')
77R8LIB_TESTS_DEPS_JAR = R8_TESTS_DEPS_JAR
Rico Wind8fc8bfa2019-03-22 09:57:36 +010078MAVEN_ZIP_LIB = os.path.join(LIBS, 'r8lib.zip')
Clément Béra3718ad02023-09-05 14:12:48 +020079LIBRARY_DESUGAR_CONVERSIONS_LEGACY_ZIP = os.path.join(
80 CUSTOM_CONVERSION_DIR, 'library_desugar_conversions_legacy.jar')
81LIBRARY_DESUGAR_CONVERSIONS_ZIP = os.path.join(
82 CUSTOM_CONVERSION_DIR, 'library_desugar_conversions.jar')
Ian Zernyf13d18f2023-05-24 12:50:37 +020083KEEPANNO_ANNOTATIONS_JAR = os.path.join(LIBS, 'keepanno-annotations.jar')
Ian Zernya6af7772023-11-21 14:05:57 +010084KEEPANNO_ANNOTATIONS_DOC = os.path.join('d8_r8', 'keepanno', 'build', 'docs', 'javadoc')
Søren Gjesse17fc67d2019-12-04 14:50:17 +010085
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +020086DESUGAR_CONFIGURATION = os.path.join('src', 'library_desugar',
87 'desugar_jdk_libs.json')
88DESUGAR_IMPLEMENTATION = os.path.join('third_party', 'openjdk',
89 'desugar_jdk_libs',
90 'desugar_jdk_libs.jar')
Søren Gjesse705a3b12022-03-17 11:37:30 +010091DESUGAR_CONFIGURATION_JDK11_LEGACY = os.path.join(
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +020092 'src', 'library_desugar', 'jdk11', 'desugar_jdk_libs_legacy.json')
Søren Gjesse2b047692022-08-19 16:34:38 +020093DESUGAR_CONFIGURATION_JDK11_MINIMAL = os.path.join(
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +020094 'src', 'library_desugar', 'jdk11', 'desugar_jdk_libs_minimal.json')
95DESUGAR_CONFIGURATION_JDK11 = os.path.join('src', 'library_desugar', 'jdk11',
96 'desugar_jdk_libs.json')
97DESUGAR_CONFIGURATION_JDK11_NIO = os.path.join('src', 'library_desugar',
98 'jdk11',
99 'desugar_jdk_libs_nio.json')
100DESUGAR_IMPLEMENTATION_JDK11 = os.path.join('third_party', 'openjdk',
101 'desugar_jdk_libs_11',
102 'desugar_jdk_libs.jar')
Søren Gjesse6e5e5842019-09-03 08:48:30 +0200103DESUGAR_CONFIGURATION_MAVEN_ZIP = os.path.join(
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200104 LIBS, 'desugar_jdk_libs_configuration.zip')
Søren Gjessee18fa6e2022-06-24 15:14:53 +0200105DESUGAR_CONFIGURATION_JDK11_LEGACY_MAVEN_ZIP = os.path.join(
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200106 LIBS, 'desugar_jdk_libs_configuration_jdk11_legacy.zip')
Søren Gjesse2b047692022-08-19 16:34:38 +0200107DESUGAR_CONFIGURATION_JDK11_MINIMAL_MAVEN_ZIP = os.path.join(
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200108 LIBS, 'desugar_jdk_libs_configuration_jdk11_minimal.zip')
Søren Gjesse2b047692022-08-19 16:34:38 +0200109DESUGAR_CONFIGURATION_JDK11_MAVEN_ZIP = os.path.join(
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200110 LIBS, 'desugar_jdk_libs_configuration_jdk11.zip')
Søren Gjesse2b047692022-08-19 16:34:38 +0200111DESUGAR_CONFIGURATION_JDK11_NIO_MAVEN_ZIP = os.path.join(
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200112 LIBS, 'desugar_jdk_libs_configuration_jdk11_nio.zip')
Mads Ager12a56bc2017-11-27 11:51:25 +0100113GENERATED_LICENSE = os.path.join(GENERATED_LICENSE_DIR, 'LICENSE')
Mathias Rav3fb4a3a2018-05-29 15:41:36 +0200114RT_JAR = os.path.join(REPO_ROOT, 'third_party/openjdk/openjdk-rt-1.8/rt.jar')
Mathias Ravb46dc002018-06-06 09:37:11 +0200115R8LIB_KEEP_RULES = os.path.join(REPO_ROOT, 'src/main/keep.txt')
Morten Krogh-Jespersen480784d2019-02-05 08:10:46 +0100116CF_SEGMENTS_TOOL = os.path.join(THIRD_PARTY, 'cf_segments')
Morten Krogh-Jespersen38c7ca02019-02-04 10:39:57 +0100117PINNED_R8_JAR = os.path.join(REPO_ROOT, 'third_party/r8/r8.jar')
118PINNED_PGR8_JAR = os.path.join(REPO_ROOT, 'third_party/r8/r8-pg6.0.1.jar')
Rico Wind8bd693f2023-10-13 11:29:32 +0200119
Morten Krogh-Jespersen45d7a7b2020-11-02 08:31:09 +0100120OPENSOURCE_DUMPS_DIR = os.path.join(THIRD_PARTY, 'opensource-apps')
Morten Krogh-Jespersen86222742021-03-02 11:13:33 +0100121INTERNAL_DUMPS_DIR = os.path.join(THIRD_PARTY, 'internal-apps')
Søren Gjesse1c115b52019-08-14 12:43:57 +0200122BAZEL_SHA_FILE = os.path.join(THIRD_PARTY, 'bazel.tar.gz.sha1')
123BAZEL_TOOL = os.path.join(THIRD_PARTY, 'bazel')
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200124JAVA8_SHA_FILE = os.path.join(THIRD_PARTY, 'openjdk', 'jdk8',
125 'linux-x86.tar.gz.sha1')
126JAVA11_SHA_FILE = os.path.join(THIRD_PARTY, 'openjdk', 'jdk-11',
127 'linux.tar.gz.sha1')
128DESUGAR_JDK_LIBS_11_SHA_FILE = os.path.join(THIRD_PARTY, 'openjdk',
129 'desugar_jdk_libs_11.tar.gz.sha1')
130IGNORE_WARNINGS_RULES = os.path.join(REPO_ROOT, 'src', 'test',
131 'ignorewarnings.rules')
Morten Krogh-Jespersen220e5702019-02-27 12:57:01 +0100132ANDROID_HOME_ENVIROMENT_NAME = "ANDROID_HOME"
133ANDROID_TOOLS_VERSION_ENVIRONMENT_NAME = "ANDROID_TOOLS_VERSION"
Morten Krogh-Jespersenc8efedd2019-01-28 11:36:17 +0100134USER_HOME = os.path.expanduser('~')
Morten Krogh-Jespersen220e5702019-02-27 12:57:01 +0100135
Morten Krogh-Jespersen0981b722019-10-09 10:00:33 +0200136R8_TEST_RESULTS_BUCKET = 'r8-test-results'
Rico Wind635b2de2022-04-25 10:35:14 +0200137R8_INTERNAL_TEST_RESULTS_BUCKET = 'r8-internal-test-results'
Morten Krogh-Jespersen0981b722019-10-09 10:00:33 +0200138
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200139
Morten Krogh-Jespersen0981b722019-10-09 10:00:33 +0200140def archive_file(name, gs_dir, src_file):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200141 gs_file = '%s/%s' % (gs_dir, name)
142 upload_file_to_cloud_storage(src_file, gs_file)
143
Morten Krogh-Jespersen0981b722019-10-09 10:00:33 +0200144
145def archive_value(name, gs_dir, value):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200146 with TempDir() as temp:
147 temparchive = os.path.join(temp, name)
148 with open(temparchive, 'w') as f:
149 f.write(str(value))
150 archive_file(name, gs_dir, temparchive)
151
Morten Krogh-Jespersen0981b722019-10-09 10:00:33 +0200152
Christoffer Quist Adamsen4d38d032021-04-20 12:31:31 +0200153def find_cloud_storage_file_from_options(name, options, orElse=None):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200154 # Import archive on-demand since archive depends on utils.
155 from archive import GetUploadDestination
156 hash_or_version = find_hash_or_version_from_options(options)
157 if not hash_or_version:
158 return orElse
159 is_hash = options.commit_hash is not None
160 download_path = GetUploadDestination(hash_or_version, name, is_hash)
161 if file_exists_on_cloud_storage(download_path):
162 out = tempfile.NamedTemporaryFile().name
163 download_file_from_cloud_storage(download_path, out)
164 return out
165 else:
166 raise Exception('Could not find file {} from hash/version: {}.'.format(
167 name, hash_or_version))
168
Christoffer Quist Adamsen4d38d032021-04-20 12:31:31 +0200169
170def find_r8_jar_from_options(options):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200171 return find_cloud_storage_file_from_options('r8.jar', options)
Christoffer Quist Adamsen4d38d032021-04-20 12:31:31 +0200172
Christoffer Quist Adamsen4d38d032021-04-20 12:31:31 +0200173
174def find_hash_or_version_from_options(options):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200175 if options.tag:
176 return find_hash_or_version_from_tag(options.tag)
177 else:
178 return options.commit_hash or options.version
179
Christoffer Quist Adamsen4d38d032021-04-20 12:31:31 +0200180
181def find_hash_or_version_from_tag(tag_or_hash):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200182 info = subprocess.check_output(
183 ['git', 'show', tag_or_hash, '-s',
184 '--format=oneline']).decode('utf-8').splitlines()[-1].split()
185 # The info should be on the following form [hash,"Version",version]
186 if len(info) == 3 and len(info[0]) == 40 and info[1] == "Version":
187 return info[2]
188 return None
189
Christoffer Quist Adamsen4d38d032021-04-20 12:31:31 +0200190
Morten Krogh-Jespersen220e5702019-02-27 12:57:01 +0100191def getAndroidHome():
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200192 return os.environ.get(ANDROID_HOME_ENVIROMENT_NAME,
193 os.path.join(USER_HOME, 'Android', 'Sdk'))
194
Morten Krogh-Jespersen220e5702019-02-27 12:57:01 +0100195
196def getAndroidBuildTools():
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200197 if ANDROID_TOOLS_VERSION_ENVIRONMENT_NAME in os.environ:
198 version = os.environ.get(ANDROID_TOOLS_VERSION_ENVIRONMENT_NAME)
199 build_tools_dir = os.path.join(getAndroidHome(), 'build-tools', version)
200 assert os.path.exists(build_tools_dir)
Christoffer Quist Adamsen8c803b42022-05-31 10:36:17 +0200201 return build_tools_dir
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200202 else:
Christoffer Adamsen500a6522024-02-27 12:27:29 +0000203 versions = ['34.0.0', '33.0.1', '32.0.0']
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200204 for version in versions:
205 build_tools_dir = os.path.join(getAndroidHome(), 'build-tools',
206 version)
207 if os.path.exists(build_tools_dir):
208 return build_tools_dir
209 raise Exception('Unable to find Android build-tools')
210
Morten Krogh-Jespersenc8efedd2019-01-28 11:36:17 +0100211
Christoffer Quist Adamsen5c9ded12021-01-14 14:29:37 +0100212def is_python3():
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200213 return sys.version_info.major == 3
214
Christoffer Quist Adamsen5c9ded12021-01-14 14:29:37 +0100215
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100216def Print(s, quiet=False):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200217 if quiet:
218 return
219 print(s)
220
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100221
222def Warn(message):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200223 CRED = '\033[91m'
224 CEND = '\033[0m'
225 print(CRED + message + CEND)
226
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100227
Christoffer Quist Adamsen65ef2982023-08-24 08:45:39 +0200228def PrintCmd(cmd, env=None, quiet=False, worker_id=None):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200229 if quiet:
230 return
231 if type(cmd) is list:
232 cmd = ' '.join(cmd)
233 if env:
234 env = ' '.join(['{}=\"{}\"'.format(x, y) for x, y in env.iteritems()])
235 print_thread('Running: {} {}'.format(env, cmd), worker_id)
236 else:
237 print_thread('Running: {}'.format(cmd), worker_id)
238 # I know this will hit os on windows eventually if we don't do this.
239 sys.stdout.flush()
240
Mads Ager418d1ca2017-05-22 09:35:49 +0200241
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100242class ProgressLogger(object):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200243 CLEAR_LINE = '\033[K'
244 UP = '\033[F'
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100245
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200246 def __init__(self, quiet=False):
247 self._count = 0
248 self._has_printed = False
249 self._quiet = quiet
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100250
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200251 def log(self, text):
252 if len(text.strip()) == 0:
253 return
254 if self._quiet:
255 if self._has_printed:
256 sys.stdout.write(ProgressLogger.UP + ProgressLogger.CLEAR_LINE)
257 if len(text) > 140:
258 text = text[0:140] + '...'
259 print(text)
260 self._has_printed = True
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100261
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200262 def done(self):
263 if self._quiet and self._has_printed:
264 sys.stdout.write(ProgressLogger.UP + ProgressLogger.CLEAR_LINE)
265 print('')
266 sys.stdout.write(ProgressLogger.UP)
267
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100268
Morten Krogh-Jespersen7cdd3a72019-03-13 14:58:25 +0100269def RunCmd(cmd, env_vars=None, quiet=False, fail=True, logging=True):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200270 PrintCmd(cmd, env=env_vars, quiet=quiet)
271 env = os.environ.copy()
272 if env_vars:
273 env.update(env_vars)
274 process = subprocess.Popen(cmd,
275 env=env,
276 stdout=subprocess.PIPE,
277 stderr=subprocess.STDOUT)
278 stdout = []
279 logger = ProgressLogger(quiet=quiet) if logging else None
280 failed = False
281 while True:
282 line = process.stdout.readline().decode('utf-8')
283 if line != '':
284 stripped = line.rstrip()
285 stdout.append(stripped)
286 if logger:
287 logger.log(stripped)
288 # TODO(christofferqa): r8 should fail with non-zero exit code.
289 if ('AssertionError:' in stripped or
290 'CompilationError:' in stripped or
291 'CompilationFailedException:' in stripped or
292 'Compilation failed' in stripped or
293 'FAILURE:' in stripped or
294 'org.gradle.api.ProjectConfigurationException' in stripped
295 or 'BUILD FAILED' in stripped):
296 failed = True
297 else:
298 if logger:
299 logger.done()
300 exit_code = process.poll()
301 if exit_code or failed:
302 for line in stdout:
303 Warn(line)
304 if fail:
305 raise subprocess.CalledProcessError(
306 exit_code or -1, cmd, output='\n'.join(stdout))
307 return stdout
308
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100309
Rico Windf80f5a22017-06-16 09:15:57 +0200310def IsWindows():
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200311 return defines.IsWindows()
312
Ian Zerny5fffb0a2019-02-11 13:54:22 +0100313
Ian Zerny5fffb0a2019-02-11 13:54:22 +0100314def EnsureDepFromGoogleCloudStorage(dep, tgz, sha1, msg):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200315 if (not os.path.exists(dep) or not os.path.exists(tgz) or
316 os.path.getmtime(tgz) < os.path.getmtime(sha1)):
317 DownloadFromGoogleCloudStorage(sha1)
318 # Update the mtime of the tar file to make sure we do not run again unless
319 # there is an update.
320 os.utime(tgz, None)
321 else:
322 print('Ensure cloud dependency:', msg, 'present')
323
Rico Windf80f5a22017-06-16 09:15:57 +0200324
Jean-Marie Henaffe4e36d12018-04-05 10:33:50 +0200325def DownloadFromX20(sha1_file):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200326 download_script = os.path.join(REPO_ROOT, 'tools', 'download_from_x20.py')
327 cmd = [download_script, sha1_file]
Rico Wind59593922021-03-03 09:12:36 +0100328 PrintCmd(cmd)
329 subprocess.check_call(cmd)
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200330
331
332def DownloadFromGoogleCloudStorage(sha1_file,
333 bucket='r8-deps',
334 auth=False,
335 quiet=False):
336 suffix = '.bat' if IsWindows() else ''
337 download_script = 'download_from_google_storage%s' % suffix
338 cmd = [download_script]
339 if not auth:
340 cmd.append('-n')
341 cmd.extend(['-b', bucket, '-u', '-s', sha1_file])
342 if not quiet:
343 PrintCmd(cmd)
344 subprocess.check_call(cmd)
345 else:
346 subprocess.check_output(cmd)
347
Mads Ager418d1ca2017-05-22 09:35:49 +0200348
349def get_sha1(filename):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200350 sha1 = hashlib.sha1()
351 with open(filename, 'rb') as f:
352 while True:
353 chunk = f.read(1024 * 1024)
354 if not chunk:
355 break
356 sha1.update(chunk)
357 return sha1.hexdigest()
358
Mads Ager418d1ca2017-05-22 09:35:49 +0200359
Ian Zernyc2de7b72023-09-06 20:52:16 +0200360def get_HEAD_branch():
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200361 result = subprocess.check_output(
362 ['git', 'rev-parse', '--abbrev-ref', 'HEAD']).decode('utf-8')
363 return result.strip()
364
Ian Zernyc2de7b72023-09-06 20:52:16 +0200365
Jean-Marie Henaff7a64eec2018-05-31 15:30:35 +0200366def get_HEAD_sha1():
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200367 return get_HEAD_sha1_for_checkout(REPO_ROOT)
368
Morten Krogh-Jespersene0ce6a32019-02-07 11:44:45 +0100369
Ian Zerny9f0345d2023-09-07 11:15:00 +0200370def get_HEAD_diff_stat():
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200371 return subprocess.check_output(['git', 'diff', '--stat']).decode('utf-8')
372
Ian Zerny9f0345d2023-09-07 11:15:00 +0200373
Morten Krogh-Jespersene0ce6a32019-02-07 11:44:45 +0100374def get_HEAD_sha1_for_checkout(checkout):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200375 cmd = ['git', 'rev-parse', 'HEAD']
376 PrintCmd(cmd)
377 with ChangedWorkingDirectory(checkout):
378 return subprocess.check_output(cmd).decode('utf-8').strip()
379
Jean-Marie Henaff7a64eec2018-05-31 15:30:35 +0200380
Tamas Kenez971eec62017-05-24 11:08:40 +0200381def makedirs_if_needed(path):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200382 try:
383 os.makedirs(path)
384 except OSError:
385 if not os.path.isdir(path):
386 raise
387
Tamas Kenez971eec62017-05-24 11:08:40 +0200388
Rico Windef7420c2021-10-14 13:16:01 +0200389def get_gsutil():
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200390 return 'gsutil.py' if os.name != 'nt' else 'gsutil.py.bat'
391
Rico Windef7420c2021-10-14 13:16:01 +0200392
Rico Wind03424282022-04-26 15:09:51 +0200393def upload_file_to_cloud_storage(source, destination):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200394 cmd = [get_gsutil(), 'cp']
395 cmd += [source, destination]
396 PrintCmd(cmd)
397 subprocess.check_call(cmd)
398
Ian Zerny566046e2024-01-04 14:24:56 +0100399def check_dir_args(source, destination):
400 # We require that the dirname of the paths coincide, e.g., src/dirname and dst/dirname
401 # The target is then stripped so the upload command will be: cp -R src/dirname dst/
402 (destination_parent, destination_file) = os.path.split(destination)
403 if os.path.basename(source) != destination_file:
404 raise Exception(
405 'Attempt to upload directory with non-matching directory name: ' +
406 f'{source} and {destination}')
407 if len(destination_parent.strip()) == 0:
408 raise Exception(
409 'Attempt to upload directory to empty destination directory: '
410 + destination)
411 return destination_parent
412
Ian Zernya6af7772023-11-21 14:05:57 +0100413def upload_directory_to_cloud_storage(source, destination, parallel=True):
Ian Zerny566046e2024-01-04 14:24:56 +0100414 destination_parent = check_dir_args(source, destination)
Ian Zernya6af7772023-11-21 14:05:57 +0100415 cmd = [get_gsutil()]
416 if parallel:
417 cmd += ['-m']
418 cmd += ['cp', '-R']
Ian Zerny566046e2024-01-04 14:24:56 +0100419 cmd += [source, destination_parent + '/']
420 PrintCmd(cmd)
421 subprocess.check_call(cmd)
422
423def rsync_directory_to_cloud_storage(source, destination, parallel=True):
424 check_dir_args(source, destination)
425 cmd = [get_gsutil()]
426 if parallel:
427 cmd += ['-m']
428 cmd += ['rsync', '-R']
Ian Zernya6af7772023-11-21 14:05:57 +0100429 cmd += [source, destination]
430 PrintCmd(cmd)
431 subprocess.check_call(cmd)
Rico Windb4621c12017-08-28 12:48:53 +0200432
Rico Wind139eece2018-09-25 09:42:09 +0200433def delete_file_from_cloud_storage(destination):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200434 cmd = [get_gsutil(), 'rm', destination]
435 PrintCmd(cmd)
436 subprocess.check_call(cmd)
437
Rico Wind139eece2018-09-25 09:42:09 +0200438
Rico Wind4fd2dda2018-09-26 17:41:45 +0200439def ls_files_on_cloud_storage(destination):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200440 cmd = [get_gsutil(), 'ls', destination]
441 PrintCmd(cmd)
442 return subprocess.check_output(cmd).decode('utf-8')
443
Rico Wind4fd2dda2018-09-26 17:41:45 +0200444
Rico Wind139eece2018-09-25 09:42:09 +0200445def cat_file_on_cloud_storage(destination, ignore_errors=False):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200446 cmd = [get_gsutil(), 'cat', destination]
447 PrintCmd(cmd)
448 try:
449 return subprocess.check_output(cmd).decode('utf-8').strip()
450 except subprocess.CalledProcessError as e:
451 if ignore_errors:
452 return ''
453 else:
454 raise e
455
Rico Wind139eece2018-09-25 09:42:09 +0200456
457def file_exists_on_cloud_storage(destination):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200458 cmd = [get_gsutil(), 'ls', destination]
459 PrintCmd(cmd)
460 return subprocess.call(cmd) == 0
461
Rico Wind139eece2018-09-25 09:42:09 +0200462
Christoffer Quist Adamsen870fa462020-12-15 10:50:54 +0100463def download_file_from_cloud_storage(source, destination, quiet=False):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200464 cmd = [get_gsutil(), 'cp', source, destination]
465 PrintCmd(cmd, quiet=quiet)
466 subprocess.check_call(cmd)
467
Jean-Marie Henaff7a64eec2018-05-31 15:30:35 +0200468
Morten Krogh-Jespersen220e5702019-02-27 12:57:01 +0100469def create_archive(name, sources=None):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200470 if not sources:
471 sources = [name]
472 tarname = '%s.tar.gz' % name
473 with tarfile.open(tarname, 'w:gz') as tar:
474 for source in sources:
475 tar.add(source)
476 return tarname
477
Jean-Marie Henaff7a64eec2018-05-31 15:30:35 +0200478
479def extract_dir(filename):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200480 return filename[0:len(filename) - len('.tar.gz')]
481
Jean-Marie Henaff7a64eec2018-05-31 15:30:35 +0200482
483def unpack_archive(filename):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200484 dest_dir = extract_dir(filename)
485 if os.path.exists(dest_dir):
486 print('Deleting existing dir %s' % dest_dir)
487 shutil.rmtree(dest_dir)
488 dirname = os.path.dirname(os.path.abspath(filename))
489 with tarfile.open(filename, 'r:gz') as tar:
490 tar.extractall(path=dirname)
491
Jean-Marie Henaff7a64eec2018-05-31 15:30:35 +0200492
Morten Krogh-Jespersenec3047b2020-08-18 13:09:06 +0200493def check_gcert():
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200494 status = subprocess.call(['gcertstatus'])
495 if status != 0:
496 subprocess.check_call(['gcert'])
497
Morten Krogh-Jespersen54090862019-02-19 11:31:10 +0100498
Rico Wind1a29c4f2018-01-25 08:43:08 +0100499# Note that gcs is eventually consistent with regards to list operations.
500# This is not a problem in our case, but don't ever use this method
501# for synchronization.
502def cloud_storage_exists(destination):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200503 cmd = [get_gsutil(), 'ls', destination]
504 PrintCmd(cmd)
505 exit_code = subprocess.call(cmd)
506 return exit_code == 0
507
Rico Wind1a29c4f2018-01-25 08:43:08 +0100508
Mads Ager418d1ca2017-05-22 09:35:49 +0200509class TempDir(object):
Mads Ager418d1ca2017-05-22 09:35:49 +0200510
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200511 def __init__(self, prefix='', delete=True):
512 self._temp_dir = None
513 self._prefix = prefix
514 self._delete = delete
Mads Ager418d1ca2017-05-22 09:35:49 +0200515
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200516 def __enter__(self):
517 self._temp_dir = tempfile.mkdtemp(self._prefix)
518 return self._temp_dir
519
520 def __exit__(self, *_):
521 if self._delete:
522 shutil.rmtree(self._temp_dir, ignore_errors=True)
523
Mads Ager418d1ca2017-05-22 09:35:49 +0200524
525class ChangedWorkingDirectory(object):
Mads Ager418d1ca2017-05-22 09:35:49 +0200526
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200527 def __init__(self, working_directory, quiet=False):
528 self._quiet = quiet
529 self._working_directory = working_directory
Mads Ager418d1ca2017-05-22 09:35:49 +0200530
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200531 def __enter__(self):
532 self._old_cwd = os.getcwd()
533 if not self._quiet:
534 print('Enter directory:', self._working_directory)
535 os.chdir(self._working_directory)
536
537 def __exit__(self, *_):
538 if not self._quiet:
539 print('Enter directory:', self._old_cwd)
540 os.chdir(self._old_cwd)
541
Tamas Kenez82efeb52017-06-12 13:56:22 +0200542
543# Reading Android CTS test_result.xml
544
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200545
Tamas Kenez82efeb52017-06-12 13:56:22 +0200546class CtsModule(object):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200547
548 def __init__(self, module_name):
549 self.name = module_name
550
Tamas Kenez82efeb52017-06-12 13:56:22 +0200551
552class CtsTestCase(object):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200553
554 def __init__(self, test_case_name):
555 self.name = test_case_name
556
Tamas Kenez82efeb52017-06-12 13:56:22 +0200557
558class CtsTest(object):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200559
560 def __init__(self, test_name, outcome):
561 self.name = test_name
562 self.outcome = outcome
563
Tamas Kenez82efeb52017-06-12 13:56:22 +0200564
565# Generator yielding CtsModule, CtsTestCase or CtsTest from
566# reading through a CTS test_result.xml file.
567def read_cts_test_result(file_xml):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200568 re_module = re.compile('<Module name="([^"]*)"')
569 re_test_case = re.compile('<TestCase name="([^"]*)"')
570 re_test = re.compile('<Test result="(pass|fail)" name="([^"]*)"')
571 with open(file_xml) as f:
572 for line in f:
573 m = re_module.search(line)
574 if m:
575 yield CtsModule(m.groups()[0])
576 continue
577 m = re_test_case.search(line)
578 if m:
579 yield CtsTestCase(m.groups()[0])
580 continue
581 m = re_test.search(line)
582 if m:
583 outcome = m.groups()[0]
584 assert outcome in ['fail', 'pass']
585 yield CtsTest(m.groups()[1], outcome == 'pass')
586
Tamas Kenezfc34cd82017-07-13 12:43:57 +0200587
588def grep_memoryuse(logfile):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200589 re_vmhwm = re.compile('^VmHWM:[ \t]*([0-9]+)[ \t]*([a-zA-Z]*)')
590 result = None
591 with open(logfile) as f:
592 for line in f:
593 m = re_vmhwm.search(line)
594 if m:
595 groups = m.groups()
596 s = len(groups)
597 if s >= 1:
598 result = int(groups[0])
599 if s >= 2:
600 unit = groups[1]
601 if unit == 'kB':
602 result *= 1024
603 elif unit != '':
604 raise Exception(
605 'Unrecognized unit in memory usage log: {}'.
606 format(unit))
607 if result is None:
608 raise Exception('No memory usage found in log: {}'.format(logfile))
609 return result
610
Tamas Kenez02bff032017-07-18 12:13:58 +0200611
612# Return a dictionary: {segment_name -> segments_size}
613def getDexSegmentSizes(dex_files):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200614 assert len(dex_files) > 0
615 cmd = [jdk.GetJavaExecutable(), '-jar', R8_JAR, 'dexsegments']
616 cmd.extend(dex_files)
617 PrintCmd(cmd)
618 output = subprocess.check_output(cmd).decode('utf-8')
Tamas Kenez02bff032017-07-18 12:13:58 +0200619
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200620 matches = DEX_SEGMENTS_RESULT_PATTERN.findall(output)
Tamas Kenez02bff032017-07-18 12:13:58 +0200621
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200622 if matches is None or len(matches) == 0:
623 raise Exception('DexSegments failed to return any output for' \
624 ' these files: {}'.format(dex_files))
Tamas Kenez02bff032017-07-18 12:13:58 +0200625
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200626 result = {}
Tamas Kenez02bff032017-07-18 12:13:58 +0200627
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200628 for match in matches:
629 result[match[0]] = int(match[1])
Tamas Kenez02bff032017-07-18 12:13:58 +0200630
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200631 return result
632
Tamas Kenez02bff032017-07-18 12:13:58 +0200633
Morten Krogh-Jespersen38c7ca02019-02-04 10:39:57 +0100634# Return a dictionary: {segment_name -> segments_size}
635def getCfSegmentSizes(cfFile):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200636 cmd = [
637 jdk.GetJavaExecutable(), '-cp', CF_SEGMENTS_TOOL,
638 'com.android.tools.r8.cf_segments.MeasureLib', cfFile
639 ]
640 PrintCmd(cmd)
641 output = subprocess.check_output(cmd).decode('utf-8')
Morten Krogh-Jespersen38c7ca02019-02-04 10:39:57 +0100642
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200643 matches = DEX_SEGMENTS_RESULT_PATTERN.findall(output)
Morten Krogh-Jespersen38c7ca02019-02-04 10:39:57 +0100644
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200645 if matches is None or len(matches) == 0:
646 raise Exception('CfSegments failed to return any output for' \
647 ' the file: ' + cfFile)
Morten Krogh-Jespersen38c7ca02019-02-04 10:39:57 +0100648
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200649 result = {}
Morten Krogh-Jespersen38c7ca02019-02-04 10:39:57 +0100650
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200651 for match in matches:
652 result[match[0]] = int(match[1])
Morten Krogh-Jespersen38c7ca02019-02-04 10:39:57 +0100653
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200654 return result
655
Morten Krogh-Jespersen38c7ca02019-02-04 10:39:57 +0100656
Søren Gjesse1c115b52019-08-14 12:43:57 +0200657def get_maven_path(artifact, version):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200658 return os.path.join('com', 'android', 'tools', artifact, version)
659
Rico Windc0b16382018-05-17 13:23:43 +0200660
Morten Krogh-Jespersen38c7ca02019-02-04 10:39:57 +0100661def print_cfsegments(prefix, cf_files):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200662 for cf_file in cf_files:
663 for segment_name, size in getCfSegmentSizes(cf_file).items():
664 print('{}-{}(CodeSize): {}'.format(prefix, segment_name, size))
665
Morten Krogh-Jespersen38c7ca02019-02-04 10:39:57 +0100666
Christoffer Quist Adamsenbe6661d2023-08-24 11:01:12 +0200667def print_dexsegments(prefix, dex_files, worker_id=None):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200668 for segment_name, size in getDexSegmentSizes(dex_files).items():
669 print_thread('{}-{}(CodeSize): {}'.format(prefix, segment_name, size),
670 worker_id)
671
Tamas Kenez2cf47cf2017-07-25 10:22:52 +0200672
Mads Agerbc7b2ce2018-02-05 11:28:47 +0100673# Ensure that we are not benchmarking with a google jvm.
Tamas Kenez2cf47cf2017-07-25 10:22:52 +0200674def check_java_version():
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200675 cmd = [jdk.GetJavaExecutable(), '-version']
676 output = subprocess.check_output(cmd,
677 stderr=subprocess.STDOUT).decode('utf-8')
678 m = re.search('openjdk version "([^"]*)"', output)
679 if m is None:
680 raise Exception("Can't check java version: no version string in output"
681 " of 'java -version': '{}'".format(output))
682 version = m.groups(0)[0]
683 m = re.search('google', version)
684 if m is not None:
685 raise Exception("Do not use google JVM for benchmarking: " + version)
686
Tamas Kenez0cad51c2017-08-21 14:42:01 +0200687
Christoffer Quist Adamsen17879c12019-01-22 16:13:54 +0100688def get_android_jar_dir(api):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200689 return os.path.join(REPO_ROOT, ANDROID_JAR_DIR.format(api=api))
690
Christoffer Quist Adamsen17879c12019-01-22 16:13:54 +0100691
Rico Wind9d70f612018-08-31 09:17:43 +0200692def get_android_jar(api):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200693 return os.path.join(REPO_ROOT, ANDROID_JAR.format(api=api))
694
Rico Windda6836e2018-12-07 12:32:03 +0100695
Rico Windfaaac012019-02-25 11:24:05 +0100696def is_bot():
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200697 return 'SWARMING_BOT_ID' in os.environ
698
Morten Krogh-Jespersen16e925d2019-01-25 14:40:38 +0100699
700def uncompressed_size(path):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200701 return sum(z.file_size for z in zipfile.ZipFile(path).infolist())
702
Morten Krogh-Jespersen0de13732019-03-01 08:56:39 +0100703
Søren Gjesse2b047692022-08-19 16:34:38 +0200704def desugar_configuration_name_and_version(configuration, is_for_maven):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200705 name = 'desugar_jdk_libs_configuration'
706 with open(configuration, 'r') as f:
707 configuration_json = json.loads(f.read())
708 configuration_format_version = \
709 configuration_json.get('configuration_format_version')
710 if (not configuration_format_version):
711 raise Exception('No "configuration_format_version" found in ' +
712 configuration)
713 if (configuration_format_version != 3 and
714 configuration_format_version != 5 and
Clément Béra43b5cf02023-11-06 14:14:52 +0100715 configuration_format_version != (200 if is_for_maven else 101)):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200716 raise Exception(
717 'Unsupported "configuration_format_version" "%s" found in %s' %
718 (configuration_format_version, configuration))
719 version = configuration_json.get('version')
720 if not version:
Clément Béra43b5cf02023-11-06 14:14:52 +0100721 if configuration_format_version == (200 if is_for_maven else 101):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200722 identifier = configuration_json.get('identifier')
723 if not identifier:
724 raise Exception('No "identifier" found in ' + configuration)
725 identifier_split = identifier.split(':')
726 if (len(identifier_split) != 3):
727 raise Exception('Invalid "identifier" found in ' +
728 configuration)
729 if (identifier_split[0] != 'com.tools.android'):
730 raise Exception('Invalid "identifier" found in ' +
731 configuration)
732 if not identifier_split[1].startswith(
733 'desugar_jdk_libs_configuration'):
734 raise Exception('Invalid "identifier" found in ' +
735 configuration)
736 name = identifier_split[1]
737 version = identifier_split[2]
738 else:
739 raise Exception('No "version" found in ' + configuration)
740 else:
Clément Béra43b5cf02023-11-06 14:14:52 +0100741 if configuration_format_version == (200 if is_for_maven else 101):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200742 raise Exception('No "version" expected in ' + configuration)
743 # Disallow prerelease, as older R8 versions cannot parse it causing hard to
744 # understand errors.
745 check_basic_semver_version(version,
746 'in ' + configuration,
747 allowPrerelease=False)
748 return (name, version)
749
Søren Gjesse1e171532019-09-03 09:44:22 +0200750
Søren Gjesse4e5c6fe2019-11-05 17:17:43 +0100751class SemanticVersion:
Søren Gjesse4e5c6fe2019-11-05 17:17:43 +0100752
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200753 def __init__(self, major, minor, patch, prerelease):
754 self.major = major
755 self.minor = minor
756 self.patch = patch
757 self.prerelease = prerelease
758 # Build metadata currently not suppported
759
760 def larger_than(self, other):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200761 if self.major > other.major:
762 return True
763 if self.major == other.major and self.minor > other.minor:
764 return True
765 if self.patch:
766 return (self.major == other.major and self.minor == other.minor and
767 self.patch > other.patch)
Søren Gjesse749a0be2023-10-26 14:07:18 +0200768 if self.prerelease:
769 if other.prerelease:
770 return self.prerelease > other.prerelease
771 else:
772 return False
773
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200774 else:
775 return False
Søren Gjesse4e5c6fe2019-11-05 17:17:43 +0100776
777
Søren Gjesse705a3b12022-03-17 11:37:30 +0100778# Check that the passed string is formatted as a basic semver version (x.y.z or x.y.z-prerelease
779# depending on the value of allowPrerelease).
780# See https://semver.org/. The regexp parts used are not all complient with what is suggested
781# on https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string.
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200782def check_basic_semver_version(version,
783 error_context='',
784 components=3,
785 allowPrerelease=False):
Søren Gjesse4e5c6fe2019-11-05 17:17:43 +0100786 regexp = '^'
787 for x in range(components):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200788 regexp += '([0-9]+)'
789 if x < components - 1:
790 regexp += '\\.'
Søren Gjesse705a3b12022-03-17 11:37:30 +0100791 if allowPrerelease:
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200792 # This part is from
793 # https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string
794 regexp += r'(?:-(?P<prerelease>(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?'
Søren Gjesse4e5c6fe2019-11-05 17:17:43 +0100795 regexp += '$'
796 reg = re.compile(regexp)
797 match = reg.match(version)
798 if not match:
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200799 raise Exception("Invalid version '" + version + "'" +
800 (' ' + error_context) if len(error_context) > 0 else '')
Søren Gjesse4e5c6fe2019-11-05 17:17:43 +0100801 if components == 2:
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200802 return SemanticVersion(int(match.group(1)), int(match.group(2)), None,
803 None)
Søren Gjesse705a3b12022-03-17 11:37:30 +0100804 elif components == 3 and not allowPrerelease:
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200805 return SemanticVersion(int(match.group(1)), int(match.group(2)),
806 int(match.group(3)), None)
Søren Gjesse705a3b12022-03-17 11:37:30 +0100807 elif components == 3 and allowPrerelease:
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200808 return SemanticVersion(int(match.group(1)), int(match.group(2)),
809 int(match.group(3)), match.group('prerelease'))
Søren Gjesse4e5c6fe2019-11-05 17:17:43 +0100810 else:
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200811 raise Exception('Argument "components" must be 2 or 3')