GenerateKeepRulesForBaselineProfilesTask.kt

/*
 * Copyright 2023 The Android Open Source Project
 *
 * 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.
 */

package androidx.baselineprofile.gradle.apptarget.task

import androidx.baselineprofile.gradle.utils.INTERMEDIATES_BASE_FOLDER
import androidx.baselineprofile.gradle.utils.maybeRegister
import org.gradle.api.DefaultTask
import org.gradle.api.Project
import org.gradle.api.file.RegularFileProperty
import org.gradle.api.tasks.OutputFile
import org.gradle.api.tasks.TaskAction
import org.gradle.api.tasks.TaskProvider
import org.gradle.work.DisableCachingByDefault

/**
 * This task generates a fixed keep rule file that disables obfuscation.
 */
@DisableCachingByDefault(because = "Not worth caching.")
abstract class GenerateKeepRulesForBaselineProfilesTask : DefaultTask() {

    companion object {
        private val KEEP_RULES = """
            # Autogenerated for baseline profiles. Changes to this file will be overwritten.
            -dontobfuscate

        """.trimIndent()

        internal fun maybeRegister(
            project: Project
        ): TaskProvider<GenerateKeepRulesForBaselineProfilesTask> =
            project
                .tasks
                .maybeRegister("generateKeepRulesForBaselineProfile") {
                    it.keepRuleFile.set(
                        project
                            .layout
                            .buildDirectory
                            .file("$INTERMEDIATES_BASE_FOLDER/tmp/dontobfuscate.pro")
                    )
                }
    }

    @get:OutputFile
    abstract val keepRuleFile: RegularFileProperty

    @TaskAction
    fun exec() {
        keepRuleFile.get().asFile.apply {
            writeText(KEEP_RULES)
            logger
                .info("Generated keep rule file for baseline profiles build type in $absolutePath")
        }
    }
}