main.com.xml.guard.tasks.FindConstraintReferencedIdsTask.kt Maven / Gradle / Ivy
package com.xml.guard.tasks
import com.bytedance.android.plugin.extensions.AabResGuardExtension
import com.tencent.gradle.AndResGuardExtension
import com.xml.guard.model.aabResGuard
import com.xml.guard.model.andResGuard
import com.xml.guard.utils.allDependencyAndroidProjects
import com.xml.guard.utils.findLayoutDirs
import com.xml.guard.utils.isXml
import groovy.util.Node
import groovy.xml.XmlParser
import org.gradle.api.DefaultTask
import org.gradle.api.tasks.TaskAction
import java.io.File
import javax.inject.Inject
/**
* User: ljx
* Date: 2022/4/3
* Time: 20:17
*/
open class FindConstraintReferencedIdsTask @Inject constructor(
private val extensionName: String,
private val variantName: String,
) : DefaultTask() {
init {
group = "guard"
}
@TaskAction
fun execute() {
val layoutDirs = mutableListOf()
val androidProjects = allDependencyAndroidProjects(project)
androidProjects.forEach { project ->
layoutDirs.addAll(project.findLayoutDirs(variantName))
}
val set = findReferencedIds(layoutDirs)
println("ids size is ${set.size} \n$set")
val extension = project.extensions.getByName(extensionName)
val whiteList = when {
andResGuard == extensionName && extension is AndResGuardExtension -> extension.whiteList
aabResGuard == extensionName && extension is AabResGuardExtension -> extension.whiteList
else -> throw IllegalArgumentException("extensionName is $extensionName")
}
(whiteList as MutableCollection).addAll(set)
}
private fun findReferencedIds(layoutDirs: List): Collection {
val set = HashSet()
layoutDirs.flatMap { dir ->
dir.listFiles { file -> file.isXml }?.toList() ?: emptyList()
}.forEach { layoutFile ->
set.addAll(layoutFile.findReferencedIds())
}
return set
}
private fun File.findReferencedIds(): Set {
val set = HashSet()
val childrenList = XmlParser(false, false).parse(this).breadthFirst()
for (children in childrenList) {
val childNode = children as? Node ?: continue
val ids = childNode.attribute("app:constraint_referenced_ids")?.toString()
if (ids.isNullOrBlank()) continue
ids.split(",").forEach {
val id = it.trim()
if (id.isNotEmpty()) {
set.add(if (aabResGuard == extensionName) "*.R.id.${id}" else "R.id.${id}")
}
}
}
return set
}
}