Last active
July 7, 2025 16:33
-
-
Save vRallev/797ec4b90eebe617fca70abbe27df3d6 to your computer and use it in GitHub Desktop.
Gradle tasks to detect changes in the merged AndroidManifest.xml file for Android applications.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| * Copyright 2025 Ralf Wondratschek | |
| * | |
| * Licensed under the Apache License, Version 2.0 (the "License"); | |
| * you may not use this file except in compliance with the License. | |
| * You may obtain a copy of the License at | |
| * | |
| * http://www.apache.org/licenses/LICENSE-2.0 | |
| * | |
| * Unless required by applicable law or agreed to in writing, software | |
| * distributed under the License is distributed on an "AS IS" BASIS, | |
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| * See the License for the specific language governing permissions and | |
| * limitations under the License. | |
| */ | |
| import com.android.build.api.artifact.SingleArtifact | |
| import com.android.build.api.variant.AndroidComponentsExtension | |
| import org.gradle.api.DefaultTask | |
| import org.gradle.api.GradleException | |
| import org.gradle.api.Project | |
| import org.gradle.api.file.DirectoryProperty | |
| import org.gradle.api.file.RegularFile | |
| import org.gradle.api.file.RegularFileProperty | |
| import org.gradle.api.provider.Property | |
| import org.gradle.api.tasks.CacheableTask | |
| import org.gradle.api.tasks.Copy | |
| import org.gradle.api.tasks.Input | |
| import org.gradle.api.tasks.InputFile | |
| import org.gradle.api.tasks.OutputDirectory | |
| import org.gradle.api.tasks.OutputFile | |
| import org.gradle.api.tasks.PathSensitive | |
| import org.gradle.api.tasks.PathSensitivity | |
| import org.gradle.api.tasks.TaskAction | |
| import org.gradle.language.base.plugins.LifecycleBasePlugin | |
| import org.gradle.process.ExecOperations | |
| import java.io.ByteArrayOutputStream | |
| import javax.inject.Inject | |
| @CacheableTask | |
| abstract class GenerateAndroidManifestBaselineTask : DefaultTask() { | |
| @get:OutputFile | |
| abstract val generatedManifest: RegularFileProperty | |
| @get:PathSensitive(PathSensitivity.NONE) | |
| @get:InputFile | |
| abstract val mergedManifest: RegularFileProperty | |
| @TaskAction | |
| fun taskAction() { | |
| generatedManifest.asFile.get().writeText(mergedManifest.get().readMergedManifest()) | |
| } | |
| } | |
| @CacheableTask | |
| abstract class CheckAndroidManifestDiffTask : DefaultTask() { | |
| // In order for the task to be up-to-date when the inputs have not changed, | |
| // the task must declare an output, even if it's not used. Tasks with no | |
| // output are always run regardless of whether the inputs changed | |
| @get:OutputDirectory | |
| abstract val output: DirectoryProperty | |
| @get:PathSensitive(PathSensitivity.NONE) | |
| @get:InputFile | |
| abstract val baselineManifest: RegularFileProperty | |
| @get:PathSensitive(PathSensitivity.NONE) | |
| @get:InputFile | |
| abstract val generatedManifest: RegularFileProperty | |
| @get:Input | |
| abstract val updateManifestTaskName: Property<String> | |
| @get:Inject | |
| abstract val execOperations: ExecOperations | |
| override fun getGroup(): String = LifecycleBasePlugin.VERIFICATION_GROUP | |
| @TaskAction | |
| fun taskAction() { | |
| val baselineContent = baselineManifest.get().asFile.readText().trim() | |
| val generatedContent = generatedManifest.get().asFile.readText().trim() | |
| if (baselineContent != generatedContent) { | |
| val diffOutputStream = ByteArrayOutputStream() | |
| execOperations.exec { | |
| it.commandLine( | |
| "diff", | |
| "-u", | |
| baselineManifest.get().asFile.absolutePath, | |
| generatedManifest.get().asFile.absolutePath, | |
| ) | |
| it.isIgnoreExitValue = true | |
| it.standardOutput = diffOutputStream | |
| it.errorOutput = diffOutputStream | |
| } | |
| // drop(4) will skip the file names with their timestamp. That's irrelevant for our purposes and only adds noise. | |
| val diffOutput = diffOutputStream.toString().lines().drop(4).joinToString(separator = "\n") | |
| throw GradleException( | |
| "The merged AndroidManifest.xml is different from the baseline! " + | |
| "If this change is intended, run ./gradlew ${updateManifestTaskName.get()}\n\n" + | |
| "Diff:\n\n$diffOutput\n\n" + | |
| "Baseline:\n\n$baselineContent\n\n" + | |
| "Merged AndroidManifest.xml:\n\n$generatedContent", | |
| ) | |
| } | |
| } | |
| } | |
| private fun RegularFile.readMergedManifest(): String { | |
| // Reads the file and transforms the content. For now it replaces the ever changing version code and version name with a constant. | |
| return asFile.readText() | |
| .replace(Regex("""android:versionCode="\d+""""), """android:versionCode="-1"""") | |
| .replace(Regex("""android:versionName="[^"]*""""), """android:versionName="1.0"""") | |
| } | |
| private fun String.capitalized(): String = replaceFirstChar { if (it.isLowerCase()) it.titlecase() else it.toString() } | |
| fun Project.configureAndroidManifestBaselineTasks() { | |
| extensions.getByType(AndroidComponentsExtension::class.java).onVariants { variant -> | |
| val capitalizedVariantName = variant.name.capitalized() | |
| val generateBaselineTaskName = "generateAndroidManifestBaseline${capitalizedVariantName}" | |
| val updateBaselineTaskName = "updateAndroidManifestBaseline${capitalizedVariantName}" | |
| val checkBaselineTaskName = "checkAndroidManifestBaseline${capitalizedVariantName}" | |
| val generatedFile = layout.buildDirectory.file("intermediates/$generateBaselineTaskName/AndroidManifestBaseline.xml") | |
| val baselineFile = layout.projectDirectory.file("manifest-baseline/${variant.name}/AndroidManifestBaseline.xml") | |
| val mergedManifest = variant.artifacts.get(SingleArtifact.MERGED_MANIFEST) | |
| val generateTask = tasks.register(generateBaselineTaskName, GenerateAndroidManifestBaselineTask::class.java) { | |
| it.mergedManifest.set(mergedManifest) | |
| it.generatedManifest.set(generatedFile) | |
| } | |
| tasks.register(updateBaselineTaskName, Copy::class.java) { | |
| it.from(generateTask.map(GenerateAndroidManifestBaselineTask::generatedManifest)) | |
| it.into(baselineFile.asFile.parentFile) | |
| } | |
| tasks.register(checkBaselineTaskName, CheckAndroidManifestDiffTask::class.java) { | |
| it.generatedManifest.set(generateTask.flatMap(GenerateAndroidManifestBaselineTask::generatedManifest)) | |
| it.baselineManifest.set(baselineFile) | |
| it.updateManifestTaskName.set(generateBaselineTaskName) | |
| it.output.set(project.layout.buildDirectory.dir("intermediates/$checkBaselineTaskName")) | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment