bingoogolapple.github.io
bingoogolapple.github.io copied to clipboard
Gradle 依赖 diff
方式一:自定义 task 读取
static def getDepMap(String filePath) {
def depMap = new HashMap<String, String>()
new File(filePath).readLines().each {
def splitIndex = it.lastIndexOf(':')
depMap.put(it.substring(0, splitIndex), it.substring(splitIndex))
}
return depMap
}
project.afterEvaluate {
project.android.applicationVariants.all { variant ->
// ./gradlew -q :app:showDepDebug -Pnew=false
tasks.create(name: "showDep${variant.name.capitalize()}", description: "生成所有依赖到 build 目录中") {
doLast {
Configuration configuration = project.configurations."${variant.name}RuntimeClasspath"
def depFileName = "depOld.txt"
if (project.hasProperty("new") && project.property("new") == "true") {
depFileName = "depNew.txt"
}
Set<String> depSet = new HashSet<String>()
configuration.resolvedConfiguration.lenientConfiguration.allModuleDependencies.each {
def identifier = it.module.id
if (identifier.version != 'unspecified') {
depSet.add("${identifier.module}:${identifier.version}\n")
}
}
new File("${project.buildDir.absolutePath}/${depFileName}").withWriter { writer ->
depSet.sort().each {
writer.append(it)
}
}
}
}
}
}
// ./gradlew -q :app:showDepDiff
tasks.create(name: "showDepDiff", description: "打印依赖到根目录文件") {
doLast {
def oldMap = getDepMap("${project.buildDir.absolutePath}/depOld.txt")
def newMap = getDepMap("${project.buildDir.absolutePath}/depNew.txt")
def deleteList = new ArrayList<String>()
def updateList = new ArrayList<String>()
def addList = new ArrayList<String>()
oldMap.each {
if (!newMap.containsKey(it.key)) {
deleteList.add("${it.key}${it.value}")
} else if (newMap.get(it.key) != it.value) {
updateList.add("${it.key.padRight(60)} ${it.value.substring(1).padLeft(15)} => ${newMap.get(it.key).substring(1)}")
}
}
newMap.each {
if (!oldMap.containsKey(it.key)) {
addList.add("${it.key}${it.value}")
}
}
new File("${project.rootDir}/depDiff.txt").withWriter { writer ->
writer.append("删除的依赖 ${deleteList.size()} ==>\n")
deleteList.each {
writer.append("${it}\n")
}
writer.append("\n\n修改的依赖 ${updateList.size()} ==>\n")
updateList.each {
writer.append("${it}\n")
}
writer.append("\n\n新增的依赖 ${addList.size()} ==>\n")
addList.each {
writer.append("${it}\n")
}
writer.flush()
}
}
}