blob: e859748226d32521990b12ecc757450f5326b7ce [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'
56GRADLE_TASK_TEST_DEPS_JAR = ':test:packageTestDeps'
Søren Gjessea28c4612023-11-01 14:55:27 +010057GRADLE_TASK_TEST_JAR = ':test:relocateTestsForR8LibWithRelocatedDeps'
Rico Wind93755fb2023-10-09 13:29:29 +020058
Søren Gjessedc9d8a22017-10-12 12:40:59 +020059R8 = 'r8'
Tamas Kenez03ab76f2018-12-07 14:33:25 +010060R8LIB = 'r8lib'
Søren Gjessedc9d8a22017-10-12 12:40:59 +020061
Morten Krogh-Jespersen51db2b02020-11-11 12:49:26 +010062ALL_DEPS_JAR = os.path.join(LIBS, 'deps_all.jar')
Rico Wind74fab302017-10-02 07:25:33 +020063R8_JAR = os.path.join(LIBS, 'r8.jar')
Tamas Kenez03ab76f2018-12-07 14:33:25 +010064R8LIB_JAR = os.path.join(LIBS, 'r8lib.jar')
Rico Wind158ef9f2022-05-19 11:08:30 +020065R8LIB_MAP = '%s.map' % R8LIB_JAR
Mads Agerb10c07f2017-11-27 13:25:52 +010066R8_SRC_JAR = os.path.join(LIBS, 'r8-src.jar')
Tamas Kenez03ab76f2018-12-07 14:33:25 +010067R8LIB_EXCLUDE_DEPS_JAR = os.path.join(LIBS, 'r8lib-exclude-deps.jar')
Tamas Kenez180be092018-12-05 15:23:06 +010068R8_FULL_EXCLUDE_DEPS_JAR = os.path.join(LIBS, 'r8-full-exclude-deps.jar')
Ian Zerny077a73f2023-10-31 09:05:47 +010069THREADING_MODULE_BLOCKING_JAR = os.path.join(LIBS, 'threading-module-blocking.jar')
70THREADING_MODULE_SINGLE_THREADED_JAR = os.path.join(LIBS, 'threading-module-single-threaded.jar')
Ian Zerny161ff742022-01-20 12:39:40 +010071R8_TESTS_JAR = os.path.join(LIBS, 'r8tests.jar')
72R8LIB_TESTS_JAR = os.path.join(LIBS, 'r8libtestdeps-cf.jar')
73R8_TESTS_DEPS_JAR = os.path.join(LIBS, 'test_deps_all.jar')
74R8LIB_TESTS_DEPS_JAR = R8_TESTS_DEPS_JAR
Rico Wind8fc8bfa2019-03-22 09:57:36 +010075MAVEN_ZIP_LIB = os.path.join(LIBS, 'r8lib.zip')
Clément Béra3718ad02023-09-05 14:12:48 +020076LIBRARY_DESUGAR_CONVERSIONS_LEGACY_ZIP = os.path.join(
77 CUSTOM_CONVERSION_DIR, 'library_desugar_conversions_legacy.jar')
78LIBRARY_DESUGAR_CONVERSIONS_ZIP = os.path.join(
79 CUSTOM_CONVERSION_DIR, 'library_desugar_conversions.jar')
Ian Zernyf13d18f2023-05-24 12:50:37 +020080KEEPANNO_ANNOTATIONS_JAR = os.path.join(LIBS, 'keepanno-annotations.jar')
Ian Zernya6af7772023-11-21 14:05:57 +010081KEEPANNO_ANNOTATIONS_DOC = os.path.join('d8_r8', 'keepanno', 'build', 'docs', 'javadoc')
Søren Gjesse17fc67d2019-12-04 14:50:17 +010082
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +020083DESUGAR_CONFIGURATION = os.path.join('src', 'library_desugar',
84 'desugar_jdk_libs.json')
85DESUGAR_IMPLEMENTATION = os.path.join('third_party', 'openjdk',
86 'desugar_jdk_libs',
87 'desugar_jdk_libs.jar')
Søren Gjesse705a3b12022-03-17 11:37:30 +010088DESUGAR_CONFIGURATION_JDK11_LEGACY = os.path.join(
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +020089 'src', 'library_desugar', 'jdk11', 'desugar_jdk_libs_legacy.json')
Søren Gjesse2b047692022-08-19 16:34:38 +020090DESUGAR_CONFIGURATION_JDK11_MINIMAL = os.path.join(
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +020091 'src', 'library_desugar', 'jdk11', 'desugar_jdk_libs_minimal.json')
92DESUGAR_CONFIGURATION_JDK11 = os.path.join('src', 'library_desugar', 'jdk11',
93 'desugar_jdk_libs.json')
94DESUGAR_CONFIGURATION_JDK11_NIO = os.path.join('src', 'library_desugar',
95 'jdk11',
96 'desugar_jdk_libs_nio.json')
97DESUGAR_IMPLEMENTATION_JDK11 = os.path.join('third_party', 'openjdk',
98 'desugar_jdk_libs_11',
99 'desugar_jdk_libs.jar')
Søren Gjesse6e5e5842019-09-03 08:48:30 +0200100DESUGAR_CONFIGURATION_MAVEN_ZIP = os.path.join(
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200101 LIBS, 'desugar_jdk_libs_configuration.zip')
Søren Gjessee18fa6e2022-06-24 15:14:53 +0200102DESUGAR_CONFIGURATION_JDK11_LEGACY_MAVEN_ZIP = os.path.join(
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200103 LIBS, 'desugar_jdk_libs_configuration_jdk11_legacy.zip')
Søren Gjesse2b047692022-08-19 16:34:38 +0200104DESUGAR_CONFIGURATION_JDK11_MINIMAL_MAVEN_ZIP = os.path.join(
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200105 LIBS, 'desugar_jdk_libs_configuration_jdk11_minimal.zip')
Søren Gjesse2b047692022-08-19 16:34:38 +0200106DESUGAR_CONFIGURATION_JDK11_MAVEN_ZIP = os.path.join(
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200107 LIBS, 'desugar_jdk_libs_configuration_jdk11.zip')
Søren Gjesse2b047692022-08-19 16:34:38 +0200108DESUGAR_CONFIGURATION_JDK11_NIO_MAVEN_ZIP = os.path.join(
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200109 LIBS, 'desugar_jdk_libs_configuration_jdk11_nio.zip')
Mads Ager12a56bc2017-11-27 11:51:25 +0100110GENERATED_LICENSE = os.path.join(GENERATED_LICENSE_DIR, 'LICENSE')
Mathias Rav3fb4a3a2018-05-29 15:41:36 +0200111RT_JAR = os.path.join(REPO_ROOT, 'third_party/openjdk/openjdk-rt-1.8/rt.jar')
Mathias Ravb46dc002018-06-06 09:37:11 +0200112R8LIB_KEEP_RULES = os.path.join(REPO_ROOT, 'src/main/keep.txt')
Morten Krogh-Jespersen480784d2019-02-05 08:10:46 +0100113CF_SEGMENTS_TOOL = os.path.join(THIRD_PARTY, 'cf_segments')
Morten Krogh-Jespersen38c7ca02019-02-04 10:39:57 +0100114PINNED_R8_JAR = os.path.join(REPO_ROOT, 'third_party/r8/r8.jar')
115PINNED_PGR8_JAR = os.path.join(REPO_ROOT, 'third_party/r8/r8-pg6.0.1.jar')
Rico Wind8bd693f2023-10-13 11:29:32 +0200116
Morten Krogh-Jespersen45d7a7b2020-11-02 08:31:09 +0100117OPENSOURCE_DUMPS_DIR = os.path.join(THIRD_PARTY, 'opensource-apps')
Morten Krogh-Jespersen86222742021-03-02 11:13:33 +0100118INTERNAL_DUMPS_DIR = os.path.join(THIRD_PARTY, 'internal-apps')
Søren Gjesse1c115b52019-08-14 12:43:57 +0200119BAZEL_SHA_FILE = os.path.join(THIRD_PARTY, 'bazel.tar.gz.sha1')
120BAZEL_TOOL = os.path.join(THIRD_PARTY, 'bazel')
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200121JAVA8_SHA_FILE = os.path.join(THIRD_PARTY, 'openjdk', 'jdk8',
122 'linux-x86.tar.gz.sha1')
123JAVA11_SHA_FILE = os.path.join(THIRD_PARTY, 'openjdk', 'jdk-11',
124 'linux.tar.gz.sha1')
125DESUGAR_JDK_LIBS_11_SHA_FILE = os.path.join(THIRD_PARTY, 'openjdk',
126 'desugar_jdk_libs_11.tar.gz.sha1')
127IGNORE_WARNINGS_RULES = os.path.join(REPO_ROOT, 'src', 'test',
128 'ignorewarnings.rules')
Morten Krogh-Jespersen220e5702019-02-27 12:57:01 +0100129ANDROID_HOME_ENVIROMENT_NAME = "ANDROID_HOME"
130ANDROID_TOOLS_VERSION_ENVIRONMENT_NAME = "ANDROID_TOOLS_VERSION"
Morten Krogh-Jespersenc8efedd2019-01-28 11:36:17 +0100131USER_HOME = os.path.expanduser('~')
Morten Krogh-Jespersen220e5702019-02-27 12:57:01 +0100132
Morten Krogh-Jespersen0981b722019-10-09 10:00:33 +0200133R8_TEST_RESULTS_BUCKET = 'r8-test-results'
Rico Wind635b2de2022-04-25 10:35:14 +0200134R8_INTERNAL_TEST_RESULTS_BUCKET = 'r8-internal-test-results'
Morten Krogh-Jespersen0981b722019-10-09 10:00:33 +0200135
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200136
Morten Krogh-Jespersen0981b722019-10-09 10:00:33 +0200137def archive_file(name, gs_dir, src_file):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200138 gs_file = '%s/%s' % (gs_dir, name)
139 upload_file_to_cloud_storage(src_file, gs_file)
140
Morten Krogh-Jespersen0981b722019-10-09 10:00:33 +0200141
142def archive_value(name, gs_dir, value):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200143 with TempDir() as temp:
144 temparchive = os.path.join(temp, name)
145 with open(temparchive, 'w') as f:
146 f.write(str(value))
147 archive_file(name, gs_dir, temparchive)
148
Morten Krogh-Jespersen0981b722019-10-09 10:00:33 +0200149
Christoffer Quist Adamsen4d38d032021-04-20 12:31:31 +0200150def find_cloud_storage_file_from_options(name, options, orElse=None):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200151 # Import archive on-demand since archive depends on utils.
152 from archive import GetUploadDestination
153 hash_or_version = find_hash_or_version_from_options(options)
154 if not hash_or_version:
155 return orElse
156 is_hash = options.commit_hash is not None
157 download_path = GetUploadDestination(hash_or_version, name, is_hash)
158 if file_exists_on_cloud_storage(download_path):
159 out = tempfile.NamedTemporaryFile().name
160 download_file_from_cloud_storage(download_path, out)
161 return out
162 else:
163 raise Exception('Could not find file {} from hash/version: {}.'.format(
164 name, hash_or_version))
165
Christoffer Quist Adamsen4d38d032021-04-20 12:31:31 +0200166
167def find_r8_jar_from_options(options):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200168 return find_cloud_storage_file_from_options('r8.jar', options)
Christoffer Quist Adamsen4d38d032021-04-20 12:31:31 +0200169
Christoffer Quist Adamsen4d38d032021-04-20 12:31:31 +0200170
171def find_hash_or_version_from_options(options):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200172 if options.tag:
173 return find_hash_or_version_from_tag(options.tag)
174 else:
175 return options.commit_hash or options.version
176
Christoffer Quist Adamsen4d38d032021-04-20 12:31:31 +0200177
178def find_hash_or_version_from_tag(tag_or_hash):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200179 info = subprocess.check_output(
180 ['git', 'show', tag_or_hash, '-s',
181 '--format=oneline']).decode('utf-8').splitlines()[-1].split()
182 # The info should be on the following form [hash,"Version",version]
183 if len(info) == 3 and len(info[0]) == 40 and info[1] == "Version":
184 return info[2]
185 return None
186
Christoffer Quist Adamsen4d38d032021-04-20 12:31:31 +0200187
Morten Krogh-Jespersen220e5702019-02-27 12:57:01 +0100188def getAndroidHome():
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200189 return os.environ.get(ANDROID_HOME_ENVIROMENT_NAME,
190 os.path.join(USER_HOME, 'Android', 'Sdk'))
191
Morten Krogh-Jespersen220e5702019-02-27 12:57:01 +0100192
193def getAndroidBuildTools():
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200194 if ANDROID_TOOLS_VERSION_ENVIRONMENT_NAME in os.environ:
195 version = os.environ.get(ANDROID_TOOLS_VERSION_ENVIRONMENT_NAME)
196 build_tools_dir = os.path.join(getAndroidHome(), 'build-tools', version)
197 assert os.path.exists(build_tools_dir)
Christoffer Quist Adamsen8c803b42022-05-31 10:36:17 +0200198 return build_tools_dir
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200199 else:
200 versions = ['33.0.1', '32.0.0']
201 for version in versions:
202 build_tools_dir = os.path.join(getAndroidHome(), 'build-tools',
203 version)
204 if os.path.exists(build_tools_dir):
205 return build_tools_dir
206 raise Exception('Unable to find Android build-tools')
207
Morten Krogh-Jespersenc8efedd2019-01-28 11:36:17 +0100208
Christoffer Quist Adamsen5c9ded12021-01-14 14:29:37 +0100209def is_python3():
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200210 return sys.version_info.major == 3
211
Christoffer Quist Adamsen5c9ded12021-01-14 14:29:37 +0100212
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100213def Print(s, quiet=False):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200214 if quiet:
215 return
216 print(s)
217
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100218
219def Warn(message):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200220 CRED = '\033[91m'
221 CEND = '\033[0m'
222 print(CRED + message + CEND)
223
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100224
Christoffer Quist Adamsen65ef2982023-08-24 08:45:39 +0200225def PrintCmd(cmd, env=None, quiet=False, worker_id=None):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200226 if quiet:
227 return
228 if type(cmd) is list:
229 cmd = ' '.join(cmd)
230 if env:
231 env = ' '.join(['{}=\"{}\"'.format(x, y) for x, y in env.iteritems()])
232 print_thread('Running: {} {}'.format(env, cmd), worker_id)
233 else:
234 print_thread('Running: {}'.format(cmd), worker_id)
235 # I know this will hit os on windows eventually if we don't do this.
236 sys.stdout.flush()
237
Mads Ager418d1ca2017-05-22 09:35:49 +0200238
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100239class ProgressLogger(object):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200240 CLEAR_LINE = '\033[K'
241 UP = '\033[F'
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100242
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200243 def __init__(self, quiet=False):
244 self._count = 0
245 self._has_printed = False
246 self._quiet = quiet
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100247
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200248 def log(self, text):
249 if len(text.strip()) == 0:
250 return
251 if self._quiet:
252 if self._has_printed:
253 sys.stdout.write(ProgressLogger.UP + ProgressLogger.CLEAR_LINE)
254 if len(text) > 140:
255 text = text[0:140] + '...'
256 print(text)
257 self._has_printed = True
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100258
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200259 def done(self):
260 if self._quiet and self._has_printed:
261 sys.stdout.write(ProgressLogger.UP + ProgressLogger.CLEAR_LINE)
262 print('')
263 sys.stdout.write(ProgressLogger.UP)
264
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100265
Morten Krogh-Jespersen7cdd3a72019-03-13 14:58:25 +0100266def RunCmd(cmd, env_vars=None, quiet=False, fail=True, logging=True):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200267 PrintCmd(cmd, env=env_vars, quiet=quiet)
268 env = os.environ.copy()
269 if env_vars:
270 env.update(env_vars)
271 process = subprocess.Popen(cmd,
272 env=env,
273 stdout=subprocess.PIPE,
274 stderr=subprocess.STDOUT)
275 stdout = []
276 logger = ProgressLogger(quiet=quiet) if logging else None
277 failed = False
278 while True:
279 line = process.stdout.readline().decode('utf-8')
280 if line != '':
281 stripped = line.rstrip()
282 stdout.append(stripped)
283 if logger:
284 logger.log(stripped)
285 # TODO(christofferqa): r8 should fail with non-zero exit code.
286 if ('AssertionError:' in stripped or
287 'CompilationError:' in stripped or
288 'CompilationFailedException:' in stripped or
289 'Compilation failed' in stripped or
290 'FAILURE:' in stripped or
291 'org.gradle.api.ProjectConfigurationException' in stripped
292 or 'BUILD FAILED' in stripped):
293 failed = True
294 else:
295 if logger:
296 logger.done()
297 exit_code = process.poll()
298 if exit_code or failed:
299 for line in stdout:
300 Warn(line)
301 if fail:
302 raise subprocess.CalledProcessError(
303 exit_code or -1, cmd, output='\n'.join(stdout))
304 return stdout
305
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100306
Rico Windf80f5a22017-06-16 09:15:57 +0200307def IsWindows():
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200308 return defines.IsWindows()
309
Ian Zerny5fffb0a2019-02-11 13:54:22 +0100310
Ian Zerny5fffb0a2019-02-11 13:54:22 +0100311def EnsureDepFromGoogleCloudStorage(dep, tgz, sha1, msg):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200312 if (not os.path.exists(dep) or not os.path.exists(tgz) or
313 os.path.getmtime(tgz) < os.path.getmtime(sha1)):
314 DownloadFromGoogleCloudStorage(sha1)
315 # Update the mtime of the tar file to make sure we do not run again unless
316 # there is an update.
317 os.utime(tgz, None)
318 else:
319 print('Ensure cloud dependency:', msg, 'present')
320
Rico Windf80f5a22017-06-16 09:15:57 +0200321
Jean-Marie Henaffe4e36d12018-04-05 10:33:50 +0200322def DownloadFromX20(sha1_file):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200323 download_script = os.path.join(REPO_ROOT, 'tools', 'download_from_x20.py')
324 cmd = [download_script, sha1_file]
Rico Wind59593922021-03-03 09:12:36 +0100325 PrintCmd(cmd)
326 subprocess.check_call(cmd)
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200327
328
329def DownloadFromGoogleCloudStorage(sha1_file,
330 bucket='r8-deps',
331 auth=False,
332 quiet=False):
333 suffix = '.bat' if IsWindows() else ''
334 download_script = 'download_from_google_storage%s' % suffix
335 cmd = [download_script]
336 if not auth:
337 cmd.append('-n')
338 cmd.extend(['-b', bucket, '-u', '-s', sha1_file])
339 if not quiet:
340 PrintCmd(cmd)
341 subprocess.check_call(cmd)
342 else:
343 subprocess.check_output(cmd)
344
Mads Ager418d1ca2017-05-22 09:35:49 +0200345
346def get_sha1(filename):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200347 sha1 = hashlib.sha1()
348 with open(filename, 'rb') as f:
349 while True:
350 chunk = f.read(1024 * 1024)
351 if not chunk:
352 break
353 sha1.update(chunk)
354 return sha1.hexdigest()
355
Mads Ager418d1ca2017-05-22 09:35:49 +0200356
Ian Zernyc2de7b72023-09-06 20:52:16 +0200357def get_HEAD_branch():
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200358 result = subprocess.check_output(
359 ['git', 'rev-parse', '--abbrev-ref', 'HEAD']).decode('utf-8')
360 return result.strip()
361
Ian Zernyc2de7b72023-09-06 20:52:16 +0200362
Jean-Marie Henaff7a64eec2018-05-31 15:30:35 +0200363def get_HEAD_sha1():
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200364 return get_HEAD_sha1_for_checkout(REPO_ROOT)
365
Morten Krogh-Jespersene0ce6a32019-02-07 11:44:45 +0100366
Ian Zerny9f0345d2023-09-07 11:15:00 +0200367def get_HEAD_diff_stat():
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200368 return subprocess.check_output(['git', 'diff', '--stat']).decode('utf-8')
369
Ian Zerny9f0345d2023-09-07 11:15:00 +0200370
Morten Krogh-Jespersene0ce6a32019-02-07 11:44:45 +0100371def get_HEAD_sha1_for_checkout(checkout):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200372 cmd = ['git', 'rev-parse', 'HEAD']
373 PrintCmd(cmd)
374 with ChangedWorkingDirectory(checkout):
375 return subprocess.check_output(cmd).decode('utf-8').strip()
376
Jean-Marie Henaff7a64eec2018-05-31 15:30:35 +0200377
Tamas Kenez971eec62017-05-24 11:08:40 +0200378def makedirs_if_needed(path):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200379 try:
380 os.makedirs(path)
381 except OSError:
382 if not os.path.isdir(path):
383 raise
384
Tamas Kenez971eec62017-05-24 11:08:40 +0200385
Rico Windef7420c2021-10-14 13:16:01 +0200386def get_gsutil():
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200387 return 'gsutil.py' if os.name != 'nt' else 'gsutil.py.bat'
388
Rico Windef7420c2021-10-14 13:16:01 +0200389
Rico Wind03424282022-04-26 15:09:51 +0200390def upload_file_to_cloud_storage(source, destination):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200391 cmd = [get_gsutil(), 'cp']
392 cmd += [source, destination]
393 PrintCmd(cmd)
394 subprocess.check_call(cmd)
395
Ian Zernya6af7772023-11-21 14:05:57 +0100396def upload_directory_to_cloud_storage(source, destination, parallel=True):
397 cmd = [get_gsutil()]
398 if parallel:
399 cmd += ['-m']
400 cmd += ['cp', '-R']
401 cmd += [source, destination]
402 PrintCmd(cmd)
403 subprocess.check_call(cmd)
Rico Windb4621c12017-08-28 12:48:53 +0200404
Rico Wind139eece2018-09-25 09:42:09 +0200405def delete_file_from_cloud_storage(destination):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200406 cmd = [get_gsutil(), 'rm', destination]
407 PrintCmd(cmd)
408 subprocess.check_call(cmd)
409
Rico Wind139eece2018-09-25 09:42:09 +0200410
Rico Wind4fd2dda2018-09-26 17:41:45 +0200411def ls_files_on_cloud_storage(destination):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200412 cmd = [get_gsutil(), 'ls', destination]
413 PrintCmd(cmd)
414 return subprocess.check_output(cmd).decode('utf-8')
415
Rico Wind4fd2dda2018-09-26 17:41:45 +0200416
Rico Wind139eece2018-09-25 09:42:09 +0200417def cat_file_on_cloud_storage(destination, ignore_errors=False):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200418 cmd = [get_gsutil(), 'cat', destination]
419 PrintCmd(cmd)
420 try:
421 return subprocess.check_output(cmd).decode('utf-8').strip()
422 except subprocess.CalledProcessError as e:
423 if ignore_errors:
424 return ''
425 else:
426 raise e
427
Rico Wind139eece2018-09-25 09:42:09 +0200428
429def file_exists_on_cloud_storage(destination):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200430 cmd = [get_gsutil(), 'ls', destination]
431 PrintCmd(cmd)
432 return subprocess.call(cmd) == 0
433
Rico Wind139eece2018-09-25 09:42:09 +0200434
Christoffer Quist Adamsen870fa462020-12-15 10:50:54 +0100435def download_file_from_cloud_storage(source, destination, quiet=False):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200436 cmd = [get_gsutil(), 'cp', source, destination]
437 PrintCmd(cmd, quiet=quiet)
438 subprocess.check_call(cmd)
439
Jean-Marie Henaff7a64eec2018-05-31 15:30:35 +0200440
Morten Krogh-Jespersen220e5702019-02-27 12:57:01 +0100441def create_archive(name, sources=None):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200442 if not sources:
443 sources = [name]
444 tarname = '%s.tar.gz' % name
445 with tarfile.open(tarname, 'w:gz') as tar:
446 for source in sources:
447 tar.add(source)
448 return tarname
449
Jean-Marie Henaff7a64eec2018-05-31 15:30:35 +0200450
451def extract_dir(filename):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200452 return filename[0:len(filename) - len('.tar.gz')]
453
Jean-Marie Henaff7a64eec2018-05-31 15:30:35 +0200454
455def unpack_archive(filename):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200456 dest_dir = extract_dir(filename)
457 if os.path.exists(dest_dir):
458 print('Deleting existing dir %s' % dest_dir)
459 shutil.rmtree(dest_dir)
460 dirname = os.path.dirname(os.path.abspath(filename))
461 with tarfile.open(filename, 'r:gz') as tar:
462 tar.extractall(path=dirname)
463
Jean-Marie Henaff7a64eec2018-05-31 15:30:35 +0200464
Morten Krogh-Jespersenec3047b2020-08-18 13:09:06 +0200465def check_gcert():
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200466 status = subprocess.call(['gcertstatus'])
467 if status != 0:
468 subprocess.check_call(['gcert'])
469
Morten Krogh-Jespersen54090862019-02-19 11:31:10 +0100470
Rico Wind1a29c4f2018-01-25 08:43:08 +0100471# Note that gcs is eventually consistent with regards to list operations.
472# This is not a problem in our case, but don't ever use this method
473# for synchronization.
474def cloud_storage_exists(destination):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200475 cmd = [get_gsutil(), 'ls', destination]
476 PrintCmd(cmd)
477 exit_code = subprocess.call(cmd)
478 return exit_code == 0
479
Rico Wind1a29c4f2018-01-25 08:43:08 +0100480
Mads Ager418d1ca2017-05-22 09:35:49 +0200481class TempDir(object):
Mads Ager418d1ca2017-05-22 09:35:49 +0200482
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200483 def __init__(self, prefix='', delete=True):
484 self._temp_dir = None
485 self._prefix = prefix
486 self._delete = delete
Mads Ager418d1ca2017-05-22 09:35:49 +0200487
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200488 def __enter__(self):
489 self._temp_dir = tempfile.mkdtemp(self._prefix)
490 return self._temp_dir
491
492 def __exit__(self, *_):
493 if self._delete:
494 shutil.rmtree(self._temp_dir, ignore_errors=True)
495
Mads Ager418d1ca2017-05-22 09:35:49 +0200496
497class ChangedWorkingDirectory(object):
Mads Ager418d1ca2017-05-22 09:35:49 +0200498
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200499 def __init__(self, working_directory, quiet=False):
500 self._quiet = quiet
501 self._working_directory = working_directory
Mads Ager418d1ca2017-05-22 09:35:49 +0200502
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200503 def __enter__(self):
504 self._old_cwd = os.getcwd()
505 if not self._quiet:
506 print('Enter directory:', self._working_directory)
507 os.chdir(self._working_directory)
508
509 def __exit__(self, *_):
510 if not self._quiet:
511 print('Enter directory:', self._old_cwd)
512 os.chdir(self._old_cwd)
513
Tamas Kenez82efeb52017-06-12 13:56:22 +0200514
515# Reading Android CTS test_result.xml
516
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200517
Tamas Kenez82efeb52017-06-12 13:56:22 +0200518class CtsModule(object):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200519
520 def __init__(self, module_name):
521 self.name = module_name
522
Tamas Kenez82efeb52017-06-12 13:56:22 +0200523
524class CtsTestCase(object):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200525
526 def __init__(self, test_case_name):
527 self.name = test_case_name
528
Tamas Kenez82efeb52017-06-12 13:56:22 +0200529
530class CtsTest(object):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200531
532 def __init__(self, test_name, outcome):
533 self.name = test_name
534 self.outcome = outcome
535
Tamas Kenez82efeb52017-06-12 13:56:22 +0200536
537# Generator yielding CtsModule, CtsTestCase or CtsTest from
538# reading through a CTS test_result.xml file.
539def read_cts_test_result(file_xml):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200540 re_module = re.compile('<Module name="([^"]*)"')
541 re_test_case = re.compile('<TestCase name="([^"]*)"')
542 re_test = re.compile('<Test result="(pass|fail)" name="([^"]*)"')
543 with open(file_xml) as f:
544 for line in f:
545 m = re_module.search(line)
546 if m:
547 yield CtsModule(m.groups()[0])
548 continue
549 m = re_test_case.search(line)
550 if m:
551 yield CtsTestCase(m.groups()[0])
552 continue
553 m = re_test.search(line)
554 if m:
555 outcome = m.groups()[0]
556 assert outcome in ['fail', 'pass']
557 yield CtsTest(m.groups()[1], outcome == 'pass')
558
Tamas Kenezfc34cd82017-07-13 12:43:57 +0200559
560def grep_memoryuse(logfile):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200561 re_vmhwm = re.compile('^VmHWM:[ \t]*([0-9]+)[ \t]*([a-zA-Z]*)')
562 result = None
563 with open(logfile) as f:
564 for line in f:
565 m = re_vmhwm.search(line)
566 if m:
567 groups = m.groups()
568 s = len(groups)
569 if s >= 1:
570 result = int(groups[0])
571 if s >= 2:
572 unit = groups[1]
573 if unit == 'kB':
574 result *= 1024
575 elif unit != '':
576 raise Exception(
577 'Unrecognized unit in memory usage log: {}'.
578 format(unit))
579 if result is None:
580 raise Exception('No memory usage found in log: {}'.format(logfile))
581 return result
582
Tamas Kenez02bff032017-07-18 12:13:58 +0200583
584# Return a dictionary: {segment_name -> segments_size}
585def getDexSegmentSizes(dex_files):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200586 assert len(dex_files) > 0
587 cmd = [jdk.GetJavaExecutable(), '-jar', R8_JAR, 'dexsegments']
588 cmd.extend(dex_files)
589 PrintCmd(cmd)
590 output = subprocess.check_output(cmd).decode('utf-8')
Tamas Kenez02bff032017-07-18 12:13:58 +0200591
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200592 matches = DEX_SEGMENTS_RESULT_PATTERN.findall(output)
Tamas Kenez02bff032017-07-18 12:13:58 +0200593
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200594 if matches is None or len(matches) == 0:
595 raise Exception('DexSegments failed to return any output for' \
596 ' these files: {}'.format(dex_files))
Tamas Kenez02bff032017-07-18 12:13:58 +0200597
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200598 result = {}
Tamas Kenez02bff032017-07-18 12:13:58 +0200599
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200600 for match in matches:
601 result[match[0]] = int(match[1])
Tamas Kenez02bff032017-07-18 12:13:58 +0200602
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200603 return result
604
Tamas Kenez02bff032017-07-18 12:13:58 +0200605
Morten Krogh-Jespersen38c7ca02019-02-04 10:39:57 +0100606# Return a dictionary: {segment_name -> segments_size}
607def getCfSegmentSizes(cfFile):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200608 cmd = [
609 jdk.GetJavaExecutable(), '-cp', CF_SEGMENTS_TOOL,
610 'com.android.tools.r8.cf_segments.MeasureLib', cfFile
611 ]
612 PrintCmd(cmd)
613 output = subprocess.check_output(cmd).decode('utf-8')
Morten Krogh-Jespersen38c7ca02019-02-04 10:39:57 +0100614
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200615 matches = DEX_SEGMENTS_RESULT_PATTERN.findall(output)
Morten Krogh-Jespersen38c7ca02019-02-04 10:39:57 +0100616
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200617 if matches is None or len(matches) == 0:
618 raise Exception('CfSegments failed to return any output for' \
619 ' the file: ' + cfFile)
Morten Krogh-Jespersen38c7ca02019-02-04 10:39:57 +0100620
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200621 result = {}
Morten Krogh-Jespersen38c7ca02019-02-04 10:39:57 +0100622
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200623 for match in matches:
624 result[match[0]] = int(match[1])
Morten Krogh-Jespersen38c7ca02019-02-04 10:39:57 +0100625
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200626 return result
627
Morten Krogh-Jespersen38c7ca02019-02-04 10:39:57 +0100628
Søren Gjesse1c115b52019-08-14 12:43:57 +0200629def get_maven_path(artifact, version):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200630 return os.path.join('com', 'android', 'tools', artifact, version)
631
Rico Windc0b16382018-05-17 13:23:43 +0200632
Morten Krogh-Jespersen38c7ca02019-02-04 10:39:57 +0100633def print_cfsegments(prefix, cf_files):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200634 for cf_file in cf_files:
635 for segment_name, size in getCfSegmentSizes(cf_file).items():
636 print('{}-{}(CodeSize): {}'.format(prefix, segment_name, size))
637
Morten Krogh-Jespersen38c7ca02019-02-04 10:39:57 +0100638
Christoffer Quist Adamsenbe6661d2023-08-24 11:01:12 +0200639def print_dexsegments(prefix, dex_files, worker_id=None):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200640 for segment_name, size in getDexSegmentSizes(dex_files).items():
641 print_thread('{}-{}(CodeSize): {}'.format(prefix, segment_name, size),
642 worker_id)
643
Tamas Kenez2cf47cf2017-07-25 10:22:52 +0200644
Mads Agerbc7b2ce2018-02-05 11:28:47 +0100645# Ensure that we are not benchmarking with a google jvm.
Tamas Kenez2cf47cf2017-07-25 10:22:52 +0200646def check_java_version():
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200647 cmd = [jdk.GetJavaExecutable(), '-version']
648 output = subprocess.check_output(cmd,
649 stderr=subprocess.STDOUT).decode('utf-8')
650 m = re.search('openjdk version "([^"]*)"', output)
651 if m is None:
652 raise Exception("Can't check java version: no version string in output"
653 " of 'java -version': '{}'".format(output))
654 version = m.groups(0)[0]
655 m = re.search('google', version)
656 if m is not None:
657 raise Exception("Do not use google JVM for benchmarking: " + version)
658
Tamas Kenez0cad51c2017-08-21 14:42:01 +0200659
Christoffer Quist Adamsen17879c12019-01-22 16:13:54 +0100660def get_android_jar_dir(api):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200661 return os.path.join(REPO_ROOT, ANDROID_JAR_DIR.format(api=api))
662
Christoffer Quist Adamsen17879c12019-01-22 16:13:54 +0100663
Rico Wind9d70f612018-08-31 09:17:43 +0200664def get_android_jar(api):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200665 return os.path.join(REPO_ROOT, ANDROID_JAR.format(api=api))
666
Rico Windda6836e2018-12-07 12:32:03 +0100667
Rico Windfaaac012019-02-25 11:24:05 +0100668def is_bot():
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200669 return 'SWARMING_BOT_ID' in os.environ
670
Morten Krogh-Jespersen16e925d2019-01-25 14:40:38 +0100671
672def uncompressed_size(path):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200673 return sum(z.file_size for z in zipfile.ZipFile(path).infolist())
674
Morten Krogh-Jespersen0de13732019-03-01 08:56:39 +0100675
Søren Gjesse2b047692022-08-19 16:34:38 +0200676def desugar_configuration_name_and_version(configuration, is_for_maven):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200677 name = 'desugar_jdk_libs_configuration'
678 with open(configuration, 'r') as f:
679 configuration_json = json.loads(f.read())
680 configuration_format_version = \
681 configuration_json.get('configuration_format_version')
682 if (not configuration_format_version):
683 raise Exception('No "configuration_format_version" found in ' +
684 configuration)
685 if (configuration_format_version != 3 and
686 configuration_format_version != 5 and
Clément Béra43b5cf02023-11-06 14:14:52 +0100687 configuration_format_version != (200 if is_for_maven else 101)):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200688 raise Exception(
689 'Unsupported "configuration_format_version" "%s" found in %s' %
690 (configuration_format_version, configuration))
691 version = configuration_json.get('version')
692 if not version:
Clément Béra43b5cf02023-11-06 14:14:52 +0100693 if configuration_format_version == (200 if is_for_maven else 101):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200694 identifier = configuration_json.get('identifier')
695 if not identifier:
696 raise Exception('No "identifier" found in ' + configuration)
697 identifier_split = identifier.split(':')
698 if (len(identifier_split) != 3):
699 raise Exception('Invalid "identifier" found in ' +
700 configuration)
701 if (identifier_split[0] != 'com.tools.android'):
702 raise Exception('Invalid "identifier" found in ' +
703 configuration)
704 if not identifier_split[1].startswith(
705 'desugar_jdk_libs_configuration'):
706 raise Exception('Invalid "identifier" found in ' +
707 configuration)
708 name = identifier_split[1]
709 version = identifier_split[2]
710 else:
711 raise Exception('No "version" found in ' + configuration)
712 else:
Clément Béra43b5cf02023-11-06 14:14:52 +0100713 if configuration_format_version == (200 if is_for_maven else 101):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200714 raise Exception('No "version" expected in ' + configuration)
715 # Disallow prerelease, as older R8 versions cannot parse it causing hard to
716 # understand errors.
717 check_basic_semver_version(version,
718 'in ' + configuration,
719 allowPrerelease=False)
720 return (name, version)
721
Søren Gjesse1e171532019-09-03 09:44:22 +0200722
Søren Gjesse4e5c6fe2019-11-05 17:17:43 +0100723class SemanticVersion:
Søren Gjesse4e5c6fe2019-11-05 17:17:43 +0100724
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200725 def __init__(self, major, minor, patch, prerelease):
726 self.major = major
727 self.minor = minor
728 self.patch = patch
729 self.prerelease = prerelease
730 # Build metadata currently not suppported
731
732 def larger_than(self, other):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200733 if self.major > other.major:
734 return True
735 if self.major == other.major and self.minor > other.minor:
736 return True
737 if self.patch:
738 return (self.major == other.major and self.minor == other.minor and
739 self.patch > other.patch)
Søren Gjesse749a0be2023-10-26 14:07:18 +0200740 if self.prerelease:
741 if other.prerelease:
742 return self.prerelease > other.prerelease
743 else:
744 return False
745
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200746 else:
747 return False
Søren Gjesse4e5c6fe2019-11-05 17:17:43 +0100748
749
Søren Gjesse705a3b12022-03-17 11:37:30 +0100750# Check that the passed string is formatted as a basic semver version (x.y.z or x.y.z-prerelease
751# depending on the value of allowPrerelease).
752# See https://semver.org/. The regexp parts used are not all complient with what is suggested
753# on https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string.
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200754def check_basic_semver_version(version,
755 error_context='',
756 components=3,
757 allowPrerelease=False):
Søren Gjesse4e5c6fe2019-11-05 17:17:43 +0100758 regexp = '^'
759 for x in range(components):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200760 regexp += '([0-9]+)'
761 if x < components - 1:
762 regexp += '\\.'
Søren Gjesse705a3b12022-03-17 11:37:30 +0100763 if allowPrerelease:
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200764 # This part is from
765 # https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string
766 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 +0100767 regexp += '$'
768 reg = re.compile(regexp)
769 match = reg.match(version)
770 if not match:
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200771 raise Exception("Invalid version '" + version + "'" +
772 (' ' + error_context) if len(error_context) > 0 else '')
Søren Gjesse4e5c6fe2019-11-05 17:17:43 +0100773 if components == 2:
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200774 return SemanticVersion(int(match.group(1)), int(match.group(2)), None,
775 None)
Søren Gjesse705a3b12022-03-17 11:37:30 +0100776 elif components == 3 and not allowPrerelease:
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200777 return SemanticVersion(int(match.group(1)), int(match.group(2)),
778 int(match.group(3)), None)
Søren Gjesse705a3b12022-03-17 11:37:30 +0100779 elif components == 3 and allowPrerelease:
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200780 return SemanticVersion(int(match.group(1)), int(match.group(2)),
781 int(match.group(3)), match.group('prerelease'))
Søren Gjesse4e5c6fe2019-11-05 17:17:43 +0100782 else:
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200783 raise Exception('Argument "components" must be 2 or 3')