2 import org.tomlj.TomlParseResult
3 import org.tomlj.TomlTable
7 gradle.mozconfig.substs.GRADLE_MAVEN_REPOSITORIES.each { repository ->
10 if (gradle.mozconfig.substs.ALLOW_INSECURE_GRADLE_REPOSITORIES) {
11 allowInsecureProtocol = true
18 kotlin_version = Versions.kotlin
19 detekt_plugin = Versions.detekt
20 python_envs_plugin = Versions.python_envs_plugin
21 ksp_plugin = Versions.ksp_plugin
25 classpath 'org.mozilla.apilint:apilint:0.5.2'
26 classpath 'com.android.tools.build:gradle:8.0.2'
27 classpath 'org.apache.commons:commons-exec:1.3'
28 classpath 'com.diffplug.spotless:spotless-plugin-gradle:6.25.0'
29 classpath 'org.tomlj:tomlj:1.1.0'
30 classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
35 id("io.gitlab.arturbosch.detekt").version("$detekt_plugin")
36 id("com.google.devtools.ksp").version("$ksp_plugin")
39 def tryInt = { string ->
43 if (string.isInteger()) {
44 return string as Integer
49 // Parses the Cargo.lock and returns the version for the given package name.
50 def getRustVersionFor(packageName) {
51 String version = null;
52 TomlParseResult result = Toml.parse(file("Cargo.lock").getText());
53 for (object in result.getArray("package").toList()) {
54 def table = (TomlTable) object
55 if (table.getString("name") == packageName) {
56 if (version != null) {
57 throw new StopExecutionException("Multiple versions for '${packageName}' found." +
58 " Ensure '${packageName}' is only included once.")
60 version = table.getString("version")
67 // Expose the per-object-directory configuration to all projects.
69 mozconfig = gradle.mozconfig
70 topsrcdir = gradle.mozconfig.topsrcdir
71 topobjdir = gradle.mozconfig.topobjdir
73 gleanVersion = "58.1.0"
74 if (gleanVersion != getRustVersionFor("glean")) {
75 throw new StopExecutionException("Mismatched Glean version, expected: ${gleanVersion}," +
76 " found ${getRustVersionFor("glean")}")
79 artifactSuffix = getArtifactSuffix()
80 versionName = getVersionName()
81 versionCode = computeVersionCode()
82 versionNumber = getVersionNumber()
83 buildId = getBuildId()
85 buildToolsVersion = mozconfig.substs.ANDROID_BUILD_TOOLS_VERSION
86 compileSdkVersion = tryInt(mozconfig.substs.ANDROID_TARGET_SDK)
87 targetSdkVersion = tryInt(mozconfig.substs.ANDROID_TARGET_SDK)
88 minSdkVersion = tryInt(mozconfig.substs.MOZ_ANDROID_MIN_SDK_VERSION)
89 manifestPlaceholders = [
90 ANDROID_PACKAGE_NAME: mozconfig.substs.ANDROID_PACKAGE_NAME,
91 ANDROID_TARGET_SDK: mozconfig.substs.ANDROID_TARGET_SDK,
92 MOZ_ANDROID_MIN_SDK_VERSION: mozconfig.substs.MOZ_ANDROID_MIN_SDK_VERSION,
97 gradle.mozconfig.substs.GRADLE_MAVEN_REPOSITORIES.each { repository ->
100 if (gradle.mozconfig.substs.ALLOW_INSECURE_GRADLE_REPOSITORIES) {
101 allowInsecureProtocol = true
107 // Use the semanticdb-javac and semanticdb-kotlinc plugins to generate semanticdb files for Searchfox
108 if (mozconfig.substs.ENABLE_MOZSEARCH_PLUGIN || mozconfig.substs.DOWNLOAD_ALL_GRADLE_DEPENDENCIES) {
109 def targetRoot = new File(topobjdir, "mozsearch_java_index")
110 def semanticdbJavacVersion = "com.sourcegraph:semanticdb-javac:0.9.6"
111 def semanticdbKotlincVersion = "com.sourcegraph:semanticdb-kotlinc:0.4.0"
114 def addDependencyToConfigurationIfExists = { configurationName, dependency ->
115 def configuration = configurations.findByName(configurationName)
116 if (configuration != null) {
117 dependencies.add(configurationName, dependency)
121 addDependencyToConfigurationIfExists("compileOnly", semanticdbJavacVersion)
122 addDependencyToConfigurationIfExists("testCompileOnly", semanticdbJavacVersion)
123 addDependencyToConfigurationIfExists("androidTestCompileOnly", semanticdbJavacVersion)
124 addDependencyToConfigurationIfExists("kotlinCompilerPluginClasspath", semanticdbKotlincVersion)
127 tasks.withType(JavaCompile) {
128 options.compilerArgs += [
129 "-Xplugin:semanticdb -sourceroot:${topsrcdir} -targetroot:${targetRoot}",
133 tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile) {
134 compilerOptions.freeCompilerArgs.addAll([
135 "-P", "plugin:semanticdb-kotlinc:sourceroot=${topsrcdir}",
136 "-P", "plugin:semanticdb-kotlinc:targetroot=${targetRoot}",
141 task downloadDependencies() {
142 description 'Download all dependencies to the Gradle cache'
144 configurations.each { configuration ->
145 if (configuration.canBeResolved) {
146 configuration.allDependencies.each { dependency ->
148 configuration.files(dependency)
150 println("Could not resolve ${configuration.name} -> ${dependency.name}")
151 println(" > ${e.message}")
153 println(" >> ${e.cause}")
155 println(" >> ${e.cause.cause}")
167 buildDir "${topobjdir}/gradle/build"
169 // A stream that processes bytes line by line, prepending a tag before sending
170 // each line to Gradle's logging.
171 class TaggedLogOutputStream extends org.apache.commons.exec.LogOutputStream {
175 TaggedLogOutputStream(tag, logger) {
180 void processLine(String line, int level) {
181 logger.lifecycle("${this.tag} ${line}")
185 ext.geckoBinariesOnlyIf = { task ->
186 // Never when Gradle was invoked within `mach build`.
187 if ('1' == System.env.GRADLE_INVOKED_WITHIN_MACH_BUILD) {
188 rootProject.logger.lifecycle("Skipping task ${task.path} because: within `mach build`")
192 // Never for official builds.
193 if (mozconfig.substs.MOZILLA_OFFICIAL) {
194 rootProject.logger.lifecycle("Skipping task ${task.path} because: MOZILLA_OFFICIAL")
198 // Multi-l10n builds set `AB_CD=multi`, which isn't a valid locale, and
199 // `MOZ_CHROME_MULTILOCALE`. To avoid failures, if Gradle is invoked with
200 // either, we don't invoke Make at all; this allows a multi-locale omnijar
201 // to be consumed without modification.
202 if ('multi' == System.env.AB_CD || System.env.MOZ_CHROME_MULTILOCALE) {
203 rootProject.logger.lifecycle("Skipping task ${task.path} because: AB_CD=multi")
207 // Single-locale l10n repacks set `IS_LANGUAGE_REPACK=1` and handle resource
208 // and code generation themselves.
209 if ('1' == System.env.IS_LANGUAGE_REPACK) {
210 rootProject.logger.lifecycle("Skipping task ${task.path} because: IS_LANGUAGE_REPACK")
214 rootProject.logger.lifecycle("Executing task ${task.path}")
218 // Non-official versions are like "61.0a1", where "a1" is the milestone.
219 // This simply strips that off, leaving "61.0" in this example.
220 def getAppVersionWithoutMilestone() {
221 return project.ext.mozconfig.substs.MOZ_APP_VERSION.replaceFirst(/a[0-9]/, "")
224 // This converts MOZ_APP_VERSION into an integer
227 // We take something like 58.1.2a1 and come out with 5800102
228 // This gives us 3 digits for the major number, and 2 digits
229 // each for the minor and build number. Beta and Release
231 // This must be synchronized with _compute_gecko_version(...) in /taskcluster/gecko_taskgraph/transforms/task.py
232 def computeVersionCode() {
233 String appVersion = getAppVersionWithoutMilestone()
235 // Split on the dot delimiter, e.g. 58.1.1a1 -> ["58, "1", "1a1"]
236 String[] parts = appVersion.split('\\.')
238 assert parts.size() == 2 || parts.size() == 3
241 int code = Integer.parseInt(parts[0]) * 100000
244 code += Integer.parseInt(parts[1]) * 100
247 if (parts.size() == 3) {
248 code += Integer.parseInt(parts[2])
254 def getVersionName() {
255 return "${mozconfig.substs.MOZ_APP_VERSION}-${mozconfig.substs.MOZ_UPDATE_CHANNEL}"
258 // Mimic Python: open(os.path.join(buildconfig.topobjdir, 'buildid.h')).readline().split()[2]
260 return file("${topobjdir}/buildid.h").getText('utf-8').split()[2]
263 def getVersionNumber() {
264 def appVersion = getAppVersionWithoutMilestone()
265 def parts = appVersion.split('\\.')
266 def version = parts[0] + "." + parts[1] + "." + getBuildId()
267 def substs = project.ext.mozconfig.substs
268 if (!substs.MOZILLA_OFFICIAL && !substs.MOZ_ANDROID_FAT_AAR_ARCHITECTURES) {
269 // Use -SNAPSHOT versions locally to enable the local GeckoView substitution flow.
270 version += "-SNAPSHOT"
275 def getArtifactSuffix() {
276 def substs = project.ext.mozconfig.substs
279 // Release artifacts don't specify the channel, for the sake of simplicity.
280 if (substs.MOZ_UPDATE_CHANNEL != 'release') {
281 suffix += "-${mozconfig.substs.MOZ_UPDATE_CHANNEL}"
287 class MachExec extends Exec {
289 // Bug 1543982: When invoking `mach build` recursively, the outer `mach
290 // build` itself modifies the environment, causing configure to run
291 // again. This tries to restore the environment that the outer `mach
292 // build` was invoked in. See the comment in
293 // $topsrcdir/settings.gradle.
294 project.ext.mozconfig.mozconfig.env.unmodified.each { k, v -> environment.remove(k) }
295 environment project.ext.mozconfig.orig_mozconfig.env.unmodified
296 environment 'MOZCONFIG', project.ext.mozconfig.substs.MOZCONFIG
300 task machBuildFaster(type: MachExec) {
301 onlyIf rootProject.ext.geckoBinariesOnlyIf
303 workingDir "${topsrcdir}"
305 commandLine mozconfig.substs.PYTHON3
306 args "${topsrcdir}/mach"
310 // Add `-v` if we're running under `--info` (or `--debug`).
311 if (project.logger.isEnabled(LogLevel.INFO)) {
315 // `path` is like `:machBuildFaster`.
316 standardOutput = new TaggedLogOutputStream("${path}>", logger)
317 errorOutput = standardOutput
320 task machStagePackage(type: MachExec) {
321 onlyIf rootProject.ext.geckoBinariesOnlyIf
323 dependsOn rootProject.machBuildFaster
325 workingDir "${topobjdir}"
327 // We'd prefer this to be a `mach` invocation, but `mach build
328 // mobile/android/installer/stage-package` doesn't work as expected.
329 commandLine mozconfig.substs.GMAKE
331 args "${topobjdir}/mobile/android/installer"
334 outputs.file "${topobjdir}/dist/geckoview/assets/omni.ja"
336 outputs.file "${topobjdir}/dist/geckoview/assets/${mozconfig.substs.ANDROID_CPU_ARCH}/libxul.so"
337 outputs.file "${topobjdir}/dist/geckoview/lib/${mozconfig.substs.ANDROID_CPU_ARCH}/libmozglue.so"
339 // Force running `stage-package`.
340 outputs.upToDateWhen { false }
342 // `path` is like `:machStagePackage`.
343 standardOutput = new TaggedLogOutputStream("${path}>", logger)
344 errorOutput = standardOutput
348 subprojects { project ->
349 tasks.withType(JavaCompile) {
350 // Add compiler args for all code except third-party code.
351 options.compilerArgs += [
352 // Turn on all warnings, except...
354 // Deprecation, because we do use deprecated API for compatibility.
355 "-Xlint:-deprecation",
356 // Serial, because we don't use Java serialization.
358 // Classfile, because javac has a bug with MethodParameters attributes
359 // with Java 7. https://bugs.openjdk.java.net/browse/JDK-8190452
361 // Turn all remaining warnings into errors,
362 // unless marked by @SuppressWarnings.
372 languageLevel = '1.8'
376 // Object directories take a huge amount of time for IntelliJ to index.
377 // Exclude them. Convention is that object directories start with obj.
378 // IntelliJ is clever and will not exclude the parts of the object
379 // directory that are referenced, if there are any. In practice,
380 // indexing the entirety of the tree is taking too long, so exclude all
382 def topsrcdirURI = file(topsrcdir).toURI()
383 excludeDirs += files(file(topsrcdir)
384 .listFiles({it.isDirectory()} as FileFilter)
385 .collect({topsrcdirURI.relativize(it.toURI()).toString()}) // Relative paths.
386 .findAll({!it.equals('mobile/')}))
388 // If topobjdir is below topsrcdir, hide only some portions of that tree.
389 def topobjdirURI = file(topobjdir).toURI()
390 if (!topsrcdirURI.relativize(topobjdirURI).isAbsolute()) {
391 excludeDirs -= file(topobjdir)
392 excludeDirs += files(file(topobjdir).listFiles())
393 excludeDirs -= file("${topobjdir}/gradle")
399 apply plugin: "com.diffplug.spotless"
403 target project.fileTree(project.projectDir) {
405 exclude '**/thirdparty/**'
407 googleJavaFormat('1.17.0')
410 target project.fileTree(project.projectDir) {
412 exclude '**/thirdparty/**'
418 project.configurations.configureEach {
419 resolutionStrategy.capabilitiesResolution.withCapability("org.mozilla.telemetry:glean-native") {
420 def toBeSelected = candidates.find {
421 it.id instanceof ProjectComponentIdentifier && it.id.projectName.contains('geckoview')
423 if (toBeSelected != null) {
426 because 'use GeckoView Glean instead of standalone Glean'