Gradle编译时所有Task信息打印

Gradle工程编译的过程,就是执行目标task的过程,如果task存在依赖,则先执行依赖task,如此反复,直到触达无依赖的task
就这样,从无依赖task -> 目标task的执行链即建立,接着依次执行task即可,每个task之间数据传输,主要是通过task inputs和outputs描述文件来完成的
所以,gradle编译所有task信息的打印,应该包含

  1. 按task执行顺序打印task name
  2. 可以打印task的inputs和outputs数据
  3. 将输出json信息保存到本地文件
我写了一个gradle脚本来完成上述信息输出:
import groovy.json.JsonOutput//输出数据结构 class TaskItem{ String aname List inputs = new ArrayList<>() List outputs = new ArrayList<>() }class Dumper{ //正则表达式,用于过滤要dump inputs和outputs的task //这里配置名称包含Jni的task,大家可以根据需要自行配置 String taskInOutDirDumpFilter = "^.*Jni.*" String type File logOutDir List taskList = new ArrayList<>() File logfile boolean isAvaliable = falseDumper(String type, File dir){ this.type = type this.logOutDir = dir }def makeLogFile(){ logfile = new File(logOutDir, "taskdump-${type}.json") if (logfile.exists()) { logfile.delete() }logfile.createNewFile() }def collectData(Task t){ t.doFirst { if (name == "pre${type}Build" && !isAvaliable){ isAvaliable = true makeLogFile() }if (!isAvaliable){ return }TaskItem item = taskList.find { it.aname == path }if (item != null){ return }item = new TaskItem() item.aname = pathtaskList.add(item)def matcher = name =~ taskInOutDirDumpFilter if (matcher.size() > 0){ println "-------match task path = ${path}"t.inputs.each { it.files.each { item.inputs.add(it.absolutePath) } }t.outputs.each { it.files.each { item.outputs.add(it.absolutePath) } } } } }def dumpData2File(){ //println " ------- dumpData2File " + logfile.getPath() def s = JsonOutput.toJson(taskList)logfile.write(s) } }Map dumperMap = new HashMap<>() //数据dump目录 def dumpDir = new File(buildDir, "taskdump") if (!dumpDir.exists()){ dumpDir.mkdirs() }rootProject.childProjects.each { it.value.afterEvaluate {Project pp -> def isAndroidLibrary = pp.plugins.hasPlugin("com.android.library") def variants = isAndroidLibrary ? pp.android.libraryVariants : pp.android.applicationVariantsvariants.all { def variant -> // Create variant and target names def targetName = variant.name.capitalize() def dumper = dumperMap.get(targetName)if (dumper == null){ dumper = new Dumper(targetName, dumpDir) dumperMap.put(targetName, dumper) }pp.tasks.each { dumper.collectData(it) } } } }gradle.buildFinished { dumperMap.each { if (it.value.isAvaliable){ it.value.dumpData2File() } } }

【Gradle编译时所有Task信息打印】将脚本命名并保存到工程目录下,比如dumptask.gradle,并保存道app module的根目录,接着再app module的build.gradle引入
apply from: "dumptask.gradle"

接着执行
./gradlew assembleDebug

执行结束后, dump信息保存到如下文件
app/build/taskdump/taskdump-Debug.json

    推荐阅读