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
23 // Used in mobile/android/fenix/app/build.gradle
24 protobuf_plugin = FenixVersions.protobuf_plugin
28 classpath 'org.mozilla.apilint:apilint:0.5.2'
29 classpath 'com.android.tools.build:gradle:8.0.2'
30 classpath 'org.apache.commons:commons-exec:1.3'
31 classpath 'com.diffplug.spotless:spotless-plugin-gradle:6.25.0'
32 classpath 'org.tomlj:tomlj:1.1.0'
33 classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
35 // Used in mobile/android/fenix/app/build.gradle
36 classpath FenixDependencies.androidx_safeargs
37 classpath FenixDependencies.osslicenses_plugin
38 classpath FenixDependencies.tools_benchmarkgradle
39 classpath "org.mozilla.telemetry:glean-gradle-plugin:${Versions.mozilla_glean}"
40 classpath "${ApplicationServicesConfig.groupId}:tooling-nimbus-gradle:${ApplicationServicesConfig.version}"
45 id("io.gitlab.arturbosch.detekt").version("$detekt_plugin")
46 id("com.google.devtools.ksp").version("$ksp_plugin")
49 def tryInt = { string ->
53 if (string.isInteger()) {
54 return string as Integer
59 // Parses the Cargo.lock and returns the version for the given package name.
60 def getRustVersionFor(packageName) {
61 String version = null;
62 TomlParseResult result = Toml.parse(file("Cargo.lock").getText());
63 for (object in result.getArray("package").toList()) {
64 def table = (TomlTable) object
65 if (table.getString("name") == packageName) {
66 if (version != null) {
67 throw new StopExecutionException("Multiple versions for '${packageName}' found." +
68 " Ensure '${packageName}' is only included once.")
70 version = table.getString("version")
77 // Expose the per-object-directory configuration to all projects.
79 mozconfig = gradle.mozconfig
80 topsrcdir = gradle.mozconfig.topsrcdir
81 topobjdir = gradle.mozconfig.topobjdir
83 gleanVersion = "58.1.0"
84 if (gleanVersion != getRustVersionFor("glean")) {
85 throw new StopExecutionException("Mismatched Glean version, expected: ${gleanVersion}," +
86 " found ${getRustVersionFor("glean")}")
89 artifactSuffix = getArtifactSuffix()
90 versionName = getVersionName()
91 versionCode = computeVersionCode()
92 versionNumber = getVersionNumber()
93 buildId = getBuildId()
95 buildToolsVersion = mozconfig.substs.ANDROID_BUILD_TOOLS_VERSION
96 compileSdkVersion = tryInt(mozconfig.substs.ANDROID_TARGET_SDK)
97 targetSdkVersion = tryInt(mozconfig.substs.ANDROID_TARGET_SDK)
98 minSdkVersion = tryInt(mozconfig.substs.MOZ_ANDROID_MIN_SDK_VERSION)
99 manifestPlaceholders = [
100 ANDROID_PACKAGE_NAME: mozconfig.substs.ANDROID_PACKAGE_NAME,
101 ANDROID_TARGET_SDK: mozconfig.substs.ANDROID_TARGET_SDK,
102 MOZ_ANDROID_MIN_SDK_VERSION: mozconfig.substs.MOZ_ANDROID_MIN_SDK_VERSION,
107 gradle.mozconfig.substs.GRADLE_MAVEN_REPOSITORIES.each { repository ->
110 if (gradle.mozconfig.substs.ALLOW_INSECURE_GRADLE_REPOSITORIES) {
111 allowInsecureProtocol = true
117 // Use the semanticdb-javac and semanticdb-kotlinc plugins to generate semanticdb files for Searchfox
118 if (mozconfig.substs.ENABLE_MOZSEARCH_PLUGIN || mozconfig.substs.DOWNLOAD_ALL_GRADLE_DEPENDENCIES) {
119 def targetRoot = new File(topobjdir, "mozsearch_java_index")
120 def semanticdbJavacVersion = "com.sourcegraph:semanticdb-javac:0.9.6"
121 def semanticdbKotlincVersion = "com.sourcegraph:semanticdb-kotlinc:0.4.0"
124 def addDependencyToConfigurationIfExists = { configurationName, dependency ->
125 def configuration = configurations.findByName(configurationName)
126 if (configuration != null) {
127 dependencies.add(configurationName, dependency)
131 addDependencyToConfigurationIfExists("compileOnly", semanticdbJavacVersion)
132 addDependencyToConfigurationIfExists("testCompileOnly", semanticdbJavacVersion)
133 addDependencyToConfigurationIfExists("androidTestCompileOnly", semanticdbJavacVersion)
134 addDependencyToConfigurationIfExists("kotlinCompilerPluginClasspath", semanticdbKotlincVersion)
137 tasks.withType(JavaCompile) {
138 options.compilerArgs += [
139 "-Xplugin:semanticdb -sourceroot:${topsrcdir} -targetroot:${targetRoot}",
143 tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile) {
144 compilerOptions.freeCompilerArgs.addAll([
145 "-P", "plugin:semanticdb-kotlinc:sourceroot=${topsrcdir}",
146 "-P", "plugin:semanticdb-kotlinc:targetroot=${targetRoot}",
151 task downloadDependencies() {
152 description 'Download all dependencies to the Gradle cache'
154 configurations.each { configuration ->
155 if (configuration.canBeResolved) {
156 configuration.allDependencies.each { dependency ->
158 configuration.files(dependency)
160 println("Could not resolve ${configuration.name} -> ${dependency.name}")
161 println(" > ${e.message}")
163 println(" >> ${e.cause}")
165 println(" >> ${e.cause.cause}")
177 buildDir "${topobjdir}/gradle/build"
179 // A stream that processes bytes line by line, prepending a tag before sending
180 // each line to Gradle's logging.
181 class TaggedLogOutputStream extends org.apache.commons.exec.LogOutputStream {
185 TaggedLogOutputStream(tag, logger) {
190 void processLine(String line, int level) {
191 logger.lifecycle("${this.tag} ${line}")
195 ext.geckoBinariesOnlyIf = { task ->
196 // Never when Gradle was invoked within `mach build`.
197 if ('1' == System.env.GRADLE_INVOKED_WITHIN_MACH_BUILD) {
198 rootProject.logger.lifecycle("Skipping task ${task.path} because: within `mach build`")
202 // Never for official builds.
203 if (mozconfig.substs.MOZILLA_OFFICIAL) {
204 rootProject.logger.lifecycle("Skipping task ${task.path} because: MOZILLA_OFFICIAL")
208 // Multi-l10n builds set `AB_CD=multi`, which isn't a valid locale, and
209 // `MOZ_CHROME_MULTILOCALE`. To avoid failures, if Gradle is invoked with
210 // either, we don't invoke Make at all; this allows a multi-locale omnijar
211 // to be consumed without modification.
212 if ('multi' == System.env.AB_CD || System.env.MOZ_CHROME_MULTILOCALE) {
213 rootProject.logger.lifecycle("Skipping task ${task.path} because: AB_CD=multi")
217 // Single-locale l10n repacks set `IS_LANGUAGE_REPACK=1` and handle resource
218 // and code generation themselves.
219 if ('1' == System.env.IS_LANGUAGE_REPACK) {
220 rootProject.logger.lifecycle("Skipping task ${task.path} because: IS_LANGUAGE_REPACK")
224 rootProject.logger.lifecycle("Executing task ${task.path}")
228 // Non-official versions are like "61.0a1", where "a1" is the milestone.
229 // This simply strips that off, leaving "61.0" in this example.
230 def getAppVersionWithoutMilestone() {
231 return project.ext.mozconfig.substs.MOZ_APP_VERSION.replaceFirst(/a[0-9]/, "")
234 // This converts MOZ_APP_VERSION into an integer
237 // We take something like 58.1.2a1 and come out with 5800102
238 // This gives us 3 digits for the major number, and 2 digits
239 // each for the minor and build number. Beta and Release
241 // This must be synchronized with _compute_gecko_version(...) in /taskcluster/gecko_taskgraph/transforms/task.py
242 def computeVersionCode() {
243 String appVersion = getAppVersionWithoutMilestone()
245 // Split on the dot delimiter, e.g. 58.1.1a1 -> ["58, "1", "1a1"]
246 String[] parts = appVersion.split('\\.')
248 assert parts.size() == 2 || parts.size() == 3
251 int code = Integer.parseInt(parts[0]) * 100000
254 code += Integer.parseInt(parts[1]) * 100
257 if (parts.size() == 3) {
258 code += Integer.parseInt(parts[2])
264 def getVersionName() {
265 return "${mozconfig.substs.MOZ_APP_VERSION}-${mozconfig.substs.MOZ_UPDATE_CHANNEL}"
268 // Mimic Python: open(os.path.join(buildconfig.topobjdir, 'buildid.h')).readline().split()[2]
270 return file("${topobjdir}/buildid.h").getText('utf-8').split()[2]
273 def getVersionNumber() {
274 def appVersion = getAppVersionWithoutMilestone()
275 def parts = appVersion.split('\\.')
276 def version = parts[0] + "." + parts[1] + "." + getBuildId()
277 def substs = project.ext.mozconfig.substs
278 if (!substs.MOZILLA_OFFICIAL && !substs.MOZ_ANDROID_FAT_AAR_ARCHITECTURES) {
279 // Use -SNAPSHOT versions locally to enable the local GeckoView substitution flow.
280 version += "-SNAPSHOT"
285 def getArtifactSuffix() {
286 def substs = project.ext.mozconfig.substs
289 // Release artifacts don't specify the channel, for the sake of simplicity.
290 if (substs.MOZ_UPDATE_CHANNEL != 'release') {
291 suffix += "-${mozconfig.substs.MOZ_UPDATE_CHANNEL}"
297 class MachExec extends Exec {
299 // Bug 1543982: When invoking `mach build` recursively, the outer `mach
300 // build` itself modifies the environment, causing configure to run
301 // again. This tries to restore the environment that the outer `mach
302 // build` was invoked in. See the comment in
303 // $topsrcdir/settings.gradle.
304 project.ext.mozconfig.mozconfig.env.unmodified.each { k, v -> environment.remove(k) }
305 environment project.ext.mozconfig.orig_mozconfig.env.unmodified
306 environment 'MOZCONFIG', project.ext.mozconfig.substs.MOZCONFIG
310 task machBuildFaster(type: MachExec) {
311 onlyIf rootProject.ext.geckoBinariesOnlyIf
313 workingDir "${topsrcdir}"
315 commandLine mozconfig.substs.PYTHON3
316 args "${topsrcdir}/mach"
320 // Add `-v` if we're running under `--info` (or `--debug`).
321 if (project.logger.isEnabled(LogLevel.INFO)) {
325 // `path` is like `:machBuildFaster`.
326 standardOutput = new TaggedLogOutputStream("${path}>", logger)
327 errorOutput = standardOutput
330 task machStagePackage(type: MachExec) {
331 onlyIf rootProject.ext.geckoBinariesOnlyIf
333 dependsOn rootProject.machBuildFaster
335 workingDir "${topobjdir}"
337 // We'd prefer this to be a `mach` invocation, but `mach build
338 // mobile/android/installer/stage-package` doesn't work as expected.
339 commandLine mozconfig.substs.GMAKE
341 args "${topobjdir}/mobile/android/installer"
344 outputs.file "${topobjdir}/dist/geckoview/assets/omni.ja"
346 outputs.file "${topobjdir}/dist/geckoview/assets/${mozconfig.substs.ANDROID_CPU_ARCH}/libxul.so"
347 outputs.file "${topobjdir}/dist/geckoview/lib/${mozconfig.substs.ANDROID_CPU_ARCH}/libmozglue.so"
349 // Force running `stage-package`.
350 outputs.upToDateWhen { false }
352 // `path` is like `:machStagePackage`.
353 standardOutput = new TaggedLogOutputStream("${path}>", logger)
354 errorOutput = standardOutput
358 subprojects { project ->
359 tasks.withType(JavaCompile) {
360 // Add compiler args for all code except third-party code.
361 options.compilerArgs += [
362 // Turn on all warnings, except...
364 // Deprecation, because we do use deprecated API for compatibility.
365 "-Xlint:-deprecation",
366 // Serial, because we don't use Java serialization.
368 // Classfile, because javac has a bug with MethodParameters attributes
369 // with Java 7. https://bugs.openjdk.java.net/browse/JDK-8190452
372 // In GeckoView java projects only, turn all remaining warnings
373 // into errors unless marked by @SuppressWarnings.
374 def projectName = project.getName()
375 if (projectName.startsWith('geckoview')
376 || projectName == 'annotations'
377 || projectName == 'exoplayer2'
378 || projectName == 'messaging_example'
379 || projectName == 'port_messaging_example'
380 || projectName == 'test_runner'
382 options.compilerArgs += [
395 languageLevel = '1.8'
399 // Object directories take a huge amount of time for IntelliJ to index.
400 // Exclude them. Convention is that object directories start with obj.
401 // IntelliJ is clever and will not exclude the parts of the object
402 // directory that are referenced, if there are any. In practice,
403 // indexing the entirety of the tree is taking too long, so exclude all
405 def topsrcdirURI = file(topsrcdir).toURI()
406 excludeDirs += files(file(topsrcdir)
407 .listFiles({it.isDirectory()} as FileFilter)
408 .collect({topsrcdirURI.relativize(it.toURI()).toString()}) // Relative paths.
409 .findAll({!it.equals('mobile/')}))
411 // If topobjdir is below topsrcdir, hide only some portions of that tree.
412 def topobjdirURI = file(topobjdir).toURI()
413 if (!topsrcdirURI.relativize(topobjdirURI).isAbsolute()) {
414 excludeDirs -= file(topobjdir)
415 excludeDirs += files(file(topobjdir).listFiles())
416 excludeDirs -= file("${topobjdir}/gradle")
421 subprojects { project ->
422 // Perform spotless lint in GeckoView projects only.
423 def projectName = project.getName()
424 if (projectName.startsWith('geckoview')
425 || projectName == 'annotations'
426 || projectName == 'exoplayer2'
427 || projectName == 'messaging_example'
428 || projectName == 'port_messaging_example'
429 || projectName == 'test_runner'
431 apply plugin: "com.diffplug.spotless"
435 target project.fileTree(project.projectDir) {
437 exclude '**/thirdparty/**'
439 googleJavaFormat('1.17.0')
442 target project.fileTree(project.projectDir) {
444 exclude '**/thirdparty/**'
451 // Set the source and target compatibility for non-GeckoView projects only.
452 if (it.hasProperty('android')) {
455 sourceCompatibility JavaVersion.VERSION_17
456 targetCompatibility JavaVersion.VERSION_17
463 project.configurations.configureEach {
464 resolutionStrategy.capabilitiesResolution.withCapability("org.mozilla.telemetry:glean-native") {
465 def toBeSelected = candidates.find {
466 it.id instanceof ProjectComponentIdentifier && it.id.projectName.contains('geckoview')
468 if (toBeSelected != null) {
471 because 'use GeckoView Glean instead of standalone Glean'