All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.xml.guard.tasks.CustomStringChangeTask.kt Maven / Gradle / Ivy

There is a newer version: 3.0.5
Show newest version
package com.xml.guard.tasks

import com.xml.guard.entensions.GuardExtension
import com.xml.guard.model.MappingParser
import com.xml.guard.utils.aidlDirs
import com.xml.guard.utils.allDependencyAndroidProjects
import com.xml.guard.utils.isAidl
import com.xml.guard.utils.isJava
import com.xml.guard.utils.isKt
import com.xml.guard.utils.isXml
import com.xml.guard.utils.javaDirs
import com.xml.guard.utils.manifestFile
import com.xml.guard.utils.replaceWordsByPattern
import com.xml.guard.utils.resDirs
import org.gradle.api.DefaultTask
import org.gradle.api.tasks.TaskAction
import java.io.File
import javax.inject.Inject

open class CustomStringChangeTask @Inject constructor(
    private val guardExtension: GuardExtension,
    private val variantName: String,
) : DefaultTask() {

    init {
        group = "guard"
    }

    private val mappingFile by lazy { project.file(MappingParser.MAPPING_CUSTOM_STRING) }
    private val mapping by lazy {
        MappingParser.parseCustomString(
            project,
            guardExtension,
            mappingFile,
            isSelfParse = true
        )
    }

    @TaskAction
    fun execute() {
        val androidProjects = allDependencyAndroidProjects(project)

        // 1、混淆自定义字符
        val obfuscateMap = mapping.obfuscateCustomString()

        // 2、替换所有文件里引用到的混淆字符
        if (obfuscateMap.isNotEmpty()) {
            val files = androidProjects.flatMap { project ->
                val dirs = mutableListOf()
                dirs.add(project.manifestFile())
                dirs.addAll(project.aidlDirs(variantName))
                dirs.addAll(project.resDirs(variantName))
                dirs.addAll(project.javaDirs(variantName))
                project.files(dirs).asFileTree.files
            }
            replaceText(files, obfuscateMap)
        }

        // 3、混淆映射写出到文件
        mapping.writeMappingToFile(mappingFile)
    }

    private fun replaceText(
        files: List,
        obfuscateMap: Map
    ) {
        files.forEach { file ->
            if (!file.isXml && !file.isJava && !file.isKt && !file.isAidl) {
                return@forEach
            }
            var replaceText = file.readText()
            obfuscateMap.forEach { (oldName, newName) ->
                replaceText = replaceText.replaceWordsByPattern(oldName, newName)
            }
            file.writeText(replaceText)
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy