├── previews ├── 0.png ├── 1.png ├── 2.png ├── 3.png └── 5.png ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── .gitattributes ├── local.properties ├── .gitignore ├── settings.gradle.kts ├── plugin ├── src │ └── main │ │ └── kotlin │ │ └── com │ │ └── wuyr │ │ └── incrementalcompiler │ │ ├── CompileTaskRegister.kt │ │ ├── tasks │ │ ├── IncrementalDexGenerator.kt │ │ └── IncrementalCompiler.kt │ │ ├── common │ │ ├── FingerprinterRegistryDelegate.kt │ │ └── extensions.kt │ │ └── utils │ │ └── ReflectUtil.kt └── build.gradle.kts ├── gradlew.bat ├── README.md ├── gradlew └── LICENSE /previews/0.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wuyr/incremental-compiler/HEAD/previews/0.png -------------------------------------------------------------------------------- /previews/1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wuyr/incremental-compiler/HEAD/previews/1.png -------------------------------------------------------------------------------- /previews/2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wuyr/incremental-compiler/HEAD/previews/2.png -------------------------------------------------------------------------------- /previews/3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wuyr/incremental-compiler/HEAD/previews/3.png -------------------------------------------------------------------------------- /previews/5.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wuyr/incremental-compiler/HEAD/previews/5.png -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wuyr/incremental-compiler/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # 2 | # https://help.github.com/articles/dealing-with-line-endings/ 3 | # 4 | # These are explicitly windows files and should use crlf 5 | *.bat text eol=crlf 6 | 7 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Wed Jul 14 17:34:35 CST 2021 2 | distributionBase=GRADLE_USER_HOME 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.1.1-bin.zip 4 | distributionPath=wrapper/dists 5 | zipStorePath=wrapper/dists 6 | zipStoreBase=GRADLE_USER_HOME 7 | -------------------------------------------------------------------------------- /local.properties: -------------------------------------------------------------------------------- 1 | ## This file must *NOT* be checked into Version Control Systems, 2 | # as it contains information specific to your local configuration. 3 | # 4 | # Location of the SDK. This is only used by Gradle. 5 | # For customization when using a Version Control System, please read the 6 | # header note. 7 | #Wed Jul 14 12:15:25 CST 2021 8 | sdk.dir=/home/wuyr/Android/android-sdk 9 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .gradle 2 | .idea 3 | /build/ 4 | 5 | # Ignore Gradle GUI config 6 | gradle-app.setting 7 | 8 | # Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) 9 | !gradle-wrapper.jar 10 | 11 | # Cache of project 12 | .gradletasknamecache 13 | 14 | # # Work around https://youtrack.jetbrains.com/issue/IDEA-116898 15 | # gradle/wrapper/gradle-wrapper.properties 16 | 17 | # Ignore Gradle build output directory 18 | build 19 | -------------------------------------------------------------------------------- /settings.gradle.kts: -------------------------------------------------------------------------------- 1 | /* 2 | * This file was generated by the Gradle 'init' task. 3 | * 4 | * The settings file is used to specify which projects to include in your build. 5 | * 6 | * Detailed information about configuring a multi-project build in Gradle can be found 7 | * in the user manual at https://docs.gradle.org/7.1.1/userguide/multi_project_builds.html 8 | */ 9 | 10 | rootProject.name = "incremental-compiler" 11 | include("plugin") 12 | -------------------------------------------------------------------------------- /plugin/src/main/kotlin/com/wuyr/incrementalcompiler/CompileTaskRegister.kt: -------------------------------------------------------------------------------- 1 | package com.wuyr.incrementalcompiler 2 | 3 | import com.wuyr.incrementalcompiler.common.isLibrary 4 | import com.wuyr.incrementalcompiler.common.println 5 | import com.wuyr.incrementalcompiler.tasks.IncrementalCompiler 6 | import com.wuyr.incrementalcompiler.tasks.IncrementalDexGenerator 7 | import org.gradle.api.DefaultTask 8 | import org.gradle.api.Plugin 9 | import org.gradle.api.Project 10 | 11 | /** 12 | * @author wuyr 13 | * @github https://github.com/wuyr/incremental-compiler 14 | * @since 2021-06-08 下午5:18 15 | */ 16 | class CompileTaskRegister : Plugin { 17 | 18 | companion object { 19 | const val COMPILE_TASK_GROUP = "incremental" 20 | var moduleInvolvedCount = 0 21 | var dexPaths = ArrayList() 22 | } 23 | 24 | override fun apply(target: Project) { 25 | moduleInvolvedCount++ 26 | target.tasks.register(IncrementalCompiler.TASK_NAME, IncrementalCompiler::class.java) { 27 | it.apply { 28 | group = COMPILE_TASK_GROUP 29 | generateRFileIfNeeded(this) 30 | doLast { 31 | val compiledFiles = compileKotlin() + compileJava() 32 | if (compiledFiles.isNotEmpty()) { 33 | "Files involved in this compilation:\n${compiledFiles.joinToString("\n")}".println() 34 | } 35 | } 36 | } 37 | } 38 | target.tasks.register(IncrementalDexGenerator.TASK_NAME, IncrementalDexGenerator::class.java) { 39 | it.apply { 40 | group = COMPILE_TASK_GROUP 41 | val compiler = target.tasks.findByName(IncrementalCompiler.TASK_NAME) as IncrementalCompiler 42 | generateRFileIfNeeded(compiler) 43 | doLast { 44 | dexPaths.add(generate(compiler)) 45 | if (dexPaths.size == moduleInvolvedCount) { 46 | dexPaths.filterNotNull().distinct().let { finalDexPaths -> 47 | if (finalDexPaths.isNotEmpty()) { 48 | if (mergeDex("classes.dex", finalDexPaths)) { 49 | "All incremental dex has been merged in: ${project.rootProject.buildDir}/outputs/merged_incremental_dex/classes.dex".println() 50 | } 51 | } 52 | } 53 | moduleInvolvedCount = 0 54 | dexPaths.clear() 55 | } 56 | } 57 | } 58 | } 59 | } 60 | 61 | private fun DefaultTask.generateRFileIfNeeded(compiler: IncrementalCompiler) { 62 | if (compiler.rFileNeeded) { 63 | dependsOn(":${project.name}:${if (project.isLibrary) "generateDebugRFile" else "processDebugResources"}") 64 | } 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /plugin/src/main/kotlin/com/wuyr/incrementalcompiler/tasks/IncrementalDexGenerator.kt: -------------------------------------------------------------------------------- 1 | package com.wuyr.incrementalcompiler.tasks 2 | 3 | import com.wuyr.incrementalcompiler.common.buildToolsVersion 4 | import com.wuyr.incrementalcompiler.common.println 5 | import com.wuyr.incrementalcompiler.common.sdkDirectory 6 | import org.gradle.api.DefaultTask 7 | import org.gradle.internal.os.OperatingSystem 8 | import java.io.File 9 | 10 | /** 11 | * @author wuyr 12 | * @github https://github.com/wuyr/incremental-compiler 13 | * @since 2021-07-03 下午12:22 14 | */ 15 | open class IncrementalDexGenerator : DefaultTask() { 16 | companion object { 17 | const val TASK_NAME = "generateIncrementalDex" 18 | } 19 | 20 | /** 21 | * 生成增量dex 22 | */ 23 | fun generate(compiler: IncrementalCompiler): String? { 24 | val compiledFiles = compiler.compileKotlin() + compiler.compileJava() 25 | if (compiledFiles.isNotEmpty()) { 26 | "Files involved in this compilation:\n${compiledFiles.joinToString("\n")}".println() 27 | val dexOutputDir = "${project.buildDir}/outputs/incremental_dex" 28 | val dexName = "classes.dex" 29 | if (makeDexByD8(dexOutputDir, dexName, compiledFiles)) { 30 | val dexFileDir = "$dexOutputDir/$dexName" 31 | "Incremental dex has been saved in: $dexFileDir".println() 32 | return dexFileDir 33 | } 34 | } 35 | return null 36 | } 37 | 38 | /** 39 | * 合并dex 40 | * @param dexName dex名称 41 | * @param finalDexPaths 需要进行合并的dex路径 42 | */ 43 | fun mergeDex(dexName: String, finalDexPaths: List) = 44 | makeDexByD8("${project.rootProject.buildDir}/outputs/merged_incremental_dex", dexName, finalDexPaths) 45 | 46 | /** 47 | * 生成dex文件 48 | * @param destinationDir 输出路径 49 | * @param dexName dex名称 50 | * @param inputFiles 目标文件 51 | */ 52 | private fun makeDexByD8(destinationDir: String, dexName: String, inputFiles: List): Boolean { 53 | val dexOutputDir = File(destinationDir).apply { mkdirs() } 54 | val d8Command = StringBuilder("${project.sdkDirectory}/build-tools/${project.buildToolsVersion}/d8") 55 | .append(" --output \"").append(dexOutputDir).append("\" ").append(" --debug ") 56 | .append(inputFiles.joinToString("\" \"", "\"", "\"")) 57 | val platformArgs = (if (OperatingSystem.current().isWindows) arrayOf("cmd", "/C") else arrayOf("/bin/bash", "-c")).plus(d8Command.toString()) 58 | val dexDir = File("$dexOutputDir/$dexName").apply { delete() } 59 | val process = Runtime.getRuntime().exec(platformArgs).apply { waitFor() } 60 | return dexDir.exists().also { isSuccess -> 61 | if (isSuccess) { 62 | process.destroy() 63 | } else { 64 | val errorMessage = process.errorStream.reader().readText().also { process.destroy() } 65 | if (errorMessage.isNotEmpty()) { 66 | throw IllegalStateException(errorMessage) 67 | } 68 | } 69 | } 70 | } 71 | } -------------------------------------------------------------------------------- /plugin/src/main/kotlin/com/wuyr/incrementalcompiler/common/FingerprinterRegistryDelegate.kt: -------------------------------------------------------------------------------- 1 | package com.wuyr.incrementalcompiler.common 2 | 3 | import com.wuyr.incrementalcompiler.utils.findMethod 4 | import org.gradle.api.file.FileCollection 5 | import org.gradle.api.internal.project.ProjectInternal 6 | import org.gradle.api.internal.tasks.properties.InputFilePropertySpec 7 | import org.gradle.api.tasks.FileNormalizer 8 | import org.gradle.internal.fingerprint.CurrentFileCollectionFingerprint 9 | import org.gradle.util.GradleVersion 10 | import java.lang.reflect.Method 11 | 12 | /** 13 | * @author wuyr 14 | * @github https://github.com/wuyr/incremental-compiler 15 | * @since 2021-07-13 上午11:48 16 | */ 17 | class FingerprinterRegistryDelegate private constructor(private val fingerprinterRegistry: Any) { 18 | 19 | companion object { 20 | 21 | fun create(project: ProjectInternal) = FingerprinterRegistryDelegate(project.services.get(FileCollectionFingerprinterRegistryClass)) 22 | 23 | // package moved begin at 7.0.2, latest is 7.1.1 24 | private val LARGER_THAN_7_0_2 = GradleVersion.current().version largerThan "7.0.2" 25 | 26 | // method getFingerprinter params changes begin at 6.8.0 27 | private val LARGER_THAN_6_7_1 = GradleVersion.current().version largerThan "6.7.1" 28 | 29 | private val CLASS_PREFIX = if (LARGER_THAN_7_0_2) "org.gradle.internal.execution.fingerprint" else "org.gradle.internal.fingerprint" 30 | 31 | private val FileCollectionFingerprinterRegistryClass = Class.forName("$CLASS_PREFIX.FileCollectionFingerprinterRegistry") 32 | 33 | private val getFingerprinterMethod: Method by lazy { 34 | FileCollectionFingerprinterRegistryClass.getMethod( 35 | "getFingerprinter", if (LARGER_THAN_6_7_1) Class.forName("$CLASS_PREFIX.FileNormalizationSpec") else Class::class.java 36 | ) 37 | } 38 | 39 | private val fingerprintMethod: Method by lazy { 40 | Class.forName("$CLASS_PREFIX.FileCollectionFingerprinter").getMethod("fingerprint", FileCollection::class.java) 41 | } 42 | 43 | private val fromMethod: Method by lazy { 44 | Class.forName("$CLASS_PREFIX.impl.DefaultFileNormalizationSpec").getMethod( 45 | "from", Class::class.java, Class.forName("org.gradle.internal.fingerprint.DirectorySensitivity") 46 | ) 47 | } 48 | 49 | private val getDirectorySensitivityMethod: Method by lazy { InputFilePropertySpec::class.java.getMethod("getDirectorySensitivity") } 50 | 51 | private val getPropertyFilesMethod: Method by lazy { InputFilePropertySpec::class.java.findMethod("getPropertyFiles") } 52 | 53 | private fun Any.getFingerprinter(spec: InputFilePropertySpec) = getFingerprinterMethod.invoke( 54 | this, fromMethod.invoke(null, spec.normalizer, getDirectorySensitivityMethod.invoke(spec)) 55 | ) 56 | 57 | private fun Any.getFingerprinter(type: Class) = getFingerprinterMethod.invoke(this, type) 58 | 59 | private fun Any.fingerprint(fileCollection: FileCollection) = 60 | fingerprintMethod.invoke(this, fileCollection) as CurrentFileCollectionFingerprint 61 | 62 | private val InputFilePropertySpec.properties: FileCollection get() = getPropertyFilesMethod.invoke(this) as FileCollection 63 | } 64 | 65 | /** 66 | * 计算文件指纹 67 | */ 68 | fun fingerprint(spec: InputFilePropertySpec) = 69 | // method getFingerprinter params changes begin at 6.8.0 70 | (if (LARGER_THAN_6_7_1) { 71 | fingerprinterRegistry.getFingerprinter(spec) 72 | } else { 73 | fingerprinterRegistry.getFingerprinter(spec.normalizer) 74 | }).fingerprint(spec.properties) 75 | 76 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## 超快编译源文件的Gradle插件,支持Java和Kotlin 2 | 3 |
4 | 5 | ### 博客详情:敬请期待。。。 6 | 7 |
8 | 9 | ### 介绍: 10 | 插件源自WanAndroid每日一问:[极致的编译优化如何实现?](https://wanandroid.com/wenda/show/18453) 11 | 12 | 插件提供了2个Task:*incremental/incrementalCompile*(增量编译源文件)、*incremental/generateIncrementalDex*(增量编译 + 生成增量dex); 13 | 14 | 每次只会编译有改动的源文件,增量编译过程中不依赖Android Gradle Plugin的任何一个Task(除了需要生成R文件和BuildConfig的时候); 15 | 16 | 与Android Gradle Plugin的*assemble* Task共享编译记录(它编译过的文件且无改动的话,插件Task不会再编译,插件编译过的文件无改动的话它也不会再次编译); 17 | 18 | 19 | >需要clone代码进行本地测试的同学,我在`plugin/build.gradle.kts`里面已把详细步骤说明,这里就不赘述了。 20 | 21 |
22 | 23 | ### 大致原理: 24 | 研究了*assembleDebug*的增量编译的大致原理(Java),发现它是通过JavaCompile的`compile`方法来完成对.java文件的编译的,这个方法有个叫`inputChanges`的参数,它描述了哪些文件在上一次编译后有改动,实现增量编译最重要就是这个参数了。 25 | 26 | **那它是怎么知道哪些文件有改动的呢?** 27 | 28 | 是这样的,*assembleDebug*在每次编译完成之后,都会把本次参与编译的源文件的指纹(md5sum)记录在`project/.gradle/gradle-version/executionHistory/executionHistory.bin`文件里 。如果是第一次编译,那就是全部源文件了,后面每次只保存有变更的,因为没变更的不需要参与编译,它的md5也不会变。 29 | 30 | 指纹对比与直接对比修改日期有个优点就是,只要内容不变它的指纹都是不变的,而判断修改日期的话,可能那个文件刚开始有修改过,但在编译之前又撤销了修改,这样它的修改日期依然会变更。 31 | 32 | **插件的做法是:** 33 | 34 | 初始化完成后直接拿到*compileDebugJavaWithJavac*和*compileDebugKotlin*(如果项目支持Kotlin的话)所对应的Compile(负责编译文件的类); 35 | 36 | 在进行一些基本的配置之后,使用跟*assembleDebug*相同的方式来计算出本次变更的文件,并交给Compile处理; 37 | 38 | Compile编译完成后,把这些参与编译的文件记录到*assembleDebug*这个Task所使用的ExecutionHistoryStore中; 39 | 40 | 如果运行的是*generateIncrementalDex*,还会借助D8工具(D8是SDK 28之后才存在`build-tools`里,这就是为什么要求*compileSdkVersion*不低于28的原因)来把这些类打包到dex里面。 41 | 42 | 43 |
44 | 45 | ### 效果演示: 46 | 随意改动不同module的几个文件: 47 | 48 | ![preview](https://github.com/wuyr/incremental-compiler/raw/main/previews/0.png) 49 | 50 | 通过*generateIncrementalDex*来生成增量dex: 51 | 52 | ![preview](https://github.com/wuyr/incremental-compiler/raw/main/previews/5.png) 53 | 54 | ![preview](https://github.com/wuyr/incremental-compiler/raw/main/previews/1.png) 55 | 56 | Task执行完毕后,在`project/build/outputs/merged_incremental_dex`目录下会生成`classes.dex`: 57 | 58 | ![preview](https://github.com/wuyr/incremental-compiler/raw/main/previews/2.png) 59 | 60 | 直接打开,会发现刚刚2个module中有改动的3个类都在里面了: 61 | 62 | ![preview](https://github.com/wuyr/incremental-compiler/raw/main/previews/3.png) 63 | 64 |
65 | 66 | ### 使用方式: 67 | #### 新版Gradle: 68 | ```groovy 69 | plugins { 70 | ... 71 | id "com.github.wuyr.incrementalcompiler" version "1.0.0" 72 | } 73 | ``` 74 | #### 旧版Gradle: 75 | 在项目下的`build.gradle`(注意不是`module/build.gradle`,是**项目根目录**下的`build.gradle`哦)加上maven地址和classpath,像这样: 76 | ```groovy 77 | buildscript { 78 | ... 79 | repositories { 80 | ... 81 | maven { url "https://plugins.gradle.org/m2/" } 82 | } 83 | 84 | dependencies { 85 | ... 86 | classpath "com.github.wuyr.incrementalcompiler:plugin:1.0.0" 87 | } 88 | } 89 | ``` 90 | 91 | >如果上面的`plugins.gradle.org/m2`访问速度很慢,也可以换成国内的镜像地址,比如阿里云的:
maven { url 'https://maven.aliyun.com/nexus/content/repositories/gradle-plugin' } 92 | 93 | 然后在目标module里加上: 94 | ```groovy 95 | apply plugin: "com.github.wuyr.incrementalcompiler" 96 | ``` 97 | 即可。 98 | 99 |
100 | 101 | #### 应用到所有module: 102 | 如果想为项目中所有module应用的话,可以在项目下的`build.gradle`(注意不是`module/build.gradle`,是**项目根目录**下的`build.gradle`哦)中直接遍历所有module,像这样: 103 | ```groovy 104 | subprojects { 105 | apply plugin: 'com.github.wuyr.incrementalcompiler' 106 | } 107 | ``` 108 | 109 |
110 | 111 | ### 要求: 112 | - *Gradle Version*不低于**6.1.1** 113 | 114 | - *Android Gradle Plugin Version*不低于**3.6.0** 115 | 116 | - *compileSdkVersion*/*buildToolsVersion*不低于**28** 117 | 118 |
119 | 120 | ### 更新日志: 121 | - 1.0.0 完成基本功能。 122 | 123 |
124 | 125 | ### 感谢: 126 | 感谢wanandroid交流群里的 "[Faded](https://github.com/custqqy)"、"亦梦" 帮忙测试各Gradle版本兼容性。 -------------------------------------------------------------------------------- /plugin/build.gradle.kts: -------------------------------------------------------------------------------- 1 | plugins { 2 | `java-gradle-plugin` 3 | id("org.jetbrains.kotlin.jvm") version "1.4.0" 4 | id("org.jetbrains.dokka") version "1.5.0" 5 | id("com.gradle.plugin-publish") version "0.15.0" 6 | } 7 | 8 | repositories { mavenCentral() } 9 | 10 | dependencies { 11 | implementation(platform("org.jetbrains.kotlin:kotlin-bom")) 12 | implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8") 13 | } 14 | 15 | val githubAddress = "https://github.com/wuyr/incremental-compiler" 16 | val pluginName = "incrementalcompiler" 17 | val pluginId = "com.github.wuyr.incrementalcompiler" 18 | group = pluginId 19 | version = "1.0.0" 20 | 21 | gradlePlugin { 22 | plugins { 23 | create(pluginName) { 24 | id = pluginId 25 | displayName = "Incremental Compiler" 26 | implementationClass = "com.wuyr.incrementalcompiler.CompileTaskRegister" 27 | } 28 | } 29 | } 30 | 31 | pluginBundle { 32 | mavenCoordinates { 33 | artifactId = "plugin" 34 | groupId = pluginId 35 | version = version 36 | } 37 | website = githubAddress 38 | vcsUrl = githubAddress 39 | description = 40 | "A Gradle plugin for Android project, used to incrementally compile class and generate incremental DEX, much faster than the [assembleDebug] task." 41 | tags = listOf("incremental", "compile", "dex") 42 | } 43 | 44 | val dokkaHtml by tasks.getting(org.jetbrains.dokka.gradle.DokkaTask::class) 45 | 46 | val javadocJar: TaskProvider by tasks.registering(Jar::class) { 47 | dependsOn(dokkaHtml) 48 | archiveClassifier.set("javadoc") 49 | from(dokkaHtml.outputDirectory) 50 | } 51 | 52 | tasks { 53 | val sourcesJar by creating(Jar::class) { 54 | dependsOn(JavaPlugin.CLASSES_TASK_NAME) 55 | archiveClassifier.convention("sources") 56 | archiveClassifier.set("sources") 57 | from(sourceSets["main"].allSource) 58 | } 59 | artifacts { 60 | add("archives", sourcesJar) 61 | add("archives", javadocJar) 62 | } 63 | } 64 | 65 | /////////////////////////////////////////////////////////////////////////// 66 | // 如需进行本地测试,请注释上面的所有代码,取消注释下面的代码 67 | // 2. 填写下面的本地发布路径 68 | // 3. Sync Now 69 | // 4. 通过执行 publishing/publish 这个Task来发布到本地 70 | // 5. 在目标Project里的根build.gradle的buildscript/repositories节点里加上 maven { url "你填写的路径" } 71 | // 6. 在目标Project里的根build.gradle的buildscript/dependencies节点里加上 classpath "com.wuyr.incrementalcompiler:plugin:插件版本号" 72 | // 7. 在目标Module的build.gradle中加上 apply plugin: 'com.wuyr.incrementalcompiler' 73 | // 8. Sync完成之后即可在Gradle窗口中看到 incremental/generateIncrementalDex 和 incremental/incrementalCompile 这个两Task 74 | /////////////////////////////////////////////////////////////////////////// 75 | 76 | //plugins { 77 | // `java-gradle-plugin` 78 | // `maven-publish` 79 | // id("org.jetbrains.kotlin.jvm") version "1.4.0" 80 | //} 81 | // 82 | //repositories { mavenCentral() } 83 | // 84 | //dependencies { 85 | // implementation(platform("org.jetbrains.kotlin:kotlin-bom")) 86 | // implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8") 87 | //} 88 | // 89 | //val pluginName = "incrementalcompiler" 90 | //val pluginId = "com.wuyr.incrementalcompiler" 91 | //group = pluginId 92 | //version = "1.0.0" 93 | // 94 | //gradlePlugin { 95 | // plugins { 96 | // create(pluginName) { 97 | // id = pluginId 98 | // implementationClass = "com.wuyr.incrementalcompiler.CompileTaskRegister" 99 | // } 100 | // } 101 | //} 102 | // 103 | //publishing { 104 | // repositories { 105 | // maven { 106 | // /////////////////////////////////////////////////////////////////////////// 107 | // // 在这里填写插件发布的本地路径 108 | // /////////////////////////////////////////////////////////////////////////// 109 | // url = uri("/home/wuyr/Desktop/IncrementalCompiler") 110 | // } 111 | // } 112 | //} -------------------------------------------------------------------------------- /plugin/src/main/kotlin/com/wuyr/incrementalcompiler/common/extensions.kt: -------------------------------------------------------------------------------- 1 | package com.wuyr.incrementalcompiler.common 2 | 3 | import com.wuyr.incrementalcompiler.utils.get 4 | import com.wuyr.incrementalcompiler.utils.invoke 5 | import org.gradle.api.Plugin 6 | import org.gradle.api.Project 7 | import java.io.File 8 | 9 | /** 10 | * @author wuyr 11 | * @github https://github.com/wuyr/incremental-compiler 12 | * @since 2021-07-06 下午4:47 13 | */ 14 | 15 | private const val APP_PLUGIN_NAME = "com.android.build.gradle.internal.plugins.AppPlugin" 16 | private const val APP_PLUGIN_NAME_OLD = "com.android.build.gradle.AppPlugin" 17 | private const val LIBRARY_PLUGIN_NAME = "com.android.build.gradle.internal.plugins.LibraryPlugin" 18 | private const val LIBRARY_PLUGIN_NAME_OLD = "com.android.build.gradle.LibraryPlugin" 19 | 20 | val Project.plugin: Plugin<*> 21 | get() = plugins.run { 22 | runCatching { 23 | val androidPlugin = findPlugin("android")!! 24 | androidPlugin::class.get(androidPlugin, "project")!!.plugins.find { 25 | it.javaClass.name == APP_PLUGIN_NAME || it.javaClass.name == APP_PLUGIN_NAME_OLD 26 | }!! 27 | }.getOrElse { find { it.javaClass.name == LIBRARY_PLUGIN_NAME || it.javaClass.name == LIBRARY_PLUGIN_NAME_OLD }!! } 28 | } 29 | 30 | val Plugin<*>.isLibrary: Boolean get() = javaClass.name == LIBRARY_PLUGIN_NAME || javaClass.name == LIBRARY_PLUGIN_NAME_OLD 31 | 32 | val Project.isLibrary: Boolean get() = plugin.isLibrary 33 | 34 | val Project.buildToolsVersion: String 35 | get() = plugin.let { plugin -> 36 | val extension = plugin::class.get(plugin, "extension")!! 37 | extension::class.invoke(extension, "getBuildToolsVersion")!! 38 | } 39 | 40 | val Project.sdkDirectory: String 41 | get() = plugin.let { plugin -> 42 | val extension = plugin::class.get(plugin, "extension")!! 43 | extension::class.invoke(extension, "getSdkDirectory")!!.absolutePath 44 | } 45 | 46 | /** 47 | * 判断版本号是否 > 目标版本 48 | */ 49 | infix fun String.largerThan(target: String): Boolean { 50 | //对比索引记录 51 | var originCompareCursor = 0 52 | var targetCompareCursor = 0 53 | val digitRange = '0'..'9' 54 | while (originCompareCursor < length && targetCompareCursor < target.length) { 55 | //数字结束索引 56 | var originDigitSegmentEndIndex = originCompareCursor 57 | for (index in originCompareCursor until length) { 58 | if (this[index] !in digitRange) break 59 | originDigitSegmentEndIndex++ 60 | } 61 | var targetDigitSegmentEndIndex = targetCompareCursor 62 | for (index in targetCompareCursor until target.length) { 63 | if (target[index] !in digitRange) break 64 | targetDigitSegmentEndIndex++ 65 | } 66 | if (originDigitSegmentEndIndex > originCompareCursor && targetDigitSegmentEndIndex > targetCompareCursor) { 67 | //数字长度 68 | val originDigitSegmentCount = originDigitSegmentEndIndex - originCompareCursor 69 | val targetDigitSegmentCount = targetDigitSegmentEndIndex - targetCompareCursor 70 | if (originDigitSegmentCount != targetDigitSegmentCount) { 71 | //长度不相等 72 | return (originDigitSegmentCount - targetDigitSegmentCount) > 0 73 | } 74 | repeat(originDigitSegmentCount) { index -> 75 | if (this[originCompareCursor + index] != target[targetCompareCursor + index]) { 76 | //数字不相等 77 | return (this[originCompareCursor + index] - target[targetCompareCursor + index]) > 0 78 | } 79 | } 80 | originCompareCursor = originDigitSegmentEndIndex 81 | targetCompareCursor = targetDigitSegmentEndIndex 82 | } else { 83 | //其中一方无数字 84 | if (this[originCompareCursor] != target[targetCompareCursor]) { 85 | return (this[originCompareCursor] - target[targetCompareCursor]) > 0 86 | } 87 | originCompareCursor++ 88 | targetCompareCursor++ 89 | } 90 | } 91 | //部分内容完全相同 92 | return (length - target.length) > 0 93 | } 94 | 95 | fun Any?.println() = println(toString()) -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | # 4 | # Copyright 2015 the original author or authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | ## 21 | ## Gradle start up script for UN*X 22 | ## 23 | ############################################################################## 24 | 25 | # Attempt to set APP_HOME 26 | # Resolve links: $0 may be a link 27 | PRG="$0" 28 | # Need this for relative symlinks. 29 | while [ -h "$PRG" ] ; do 30 | ls=`ls -ld "$PRG"` 31 | link=`expr "$ls" : '.*-> \(.*\)$'` 32 | if expr "$link" : '/.*' > /dev/null; then 33 | PRG="$link" 34 | else 35 | PRG=`dirname "$PRG"`"/$link" 36 | fi 37 | done 38 | SAVED="`pwd`" 39 | cd "`dirname \"$PRG\"`/" >/dev/null 40 | APP_HOME="`pwd -P`" 41 | cd "$SAVED" >/dev/null 42 | 43 | APP_NAME="Gradle" 44 | APP_BASE_NAME=`basename "$0"` 45 | 46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 48 | 49 | # Use the maximum available, or set MAX_FD != -1 to use that value. 50 | MAX_FD="maximum" 51 | 52 | warn () { 53 | echo "$*" 54 | } 55 | 56 | die () { 57 | echo 58 | echo "$*" 59 | echo 60 | exit 1 61 | } 62 | 63 | # OS specific support (must be 'true' or 'false'). 64 | cygwin=false 65 | msys=false 66 | darwin=false 67 | nonstop=false 68 | case "`uname`" in 69 | CYGWIN* ) 70 | cygwin=true 71 | ;; 72 | Darwin* ) 73 | darwin=true 74 | ;; 75 | MSYS* | MINGW* ) 76 | msys=true 77 | ;; 78 | NONSTOP* ) 79 | nonstop=true 80 | ;; 81 | esac 82 | 83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 84 | 85 | 86 | # Determine the Java command to use to start the JVM. 87 | if [ -n "$JAVA_HOME" ] ; then 88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 89 | # IBM's JDK on AIX uses strange locations for the executables 90 | JAVACMD="$JAVA_HOME/jre/sh/java" 91 | else 92 | JAVACMD="$JAVA_HOME/bin/java" 93 | fi 94 | if [ ! -x "$JAVACMD" ] ; then 95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 96 | 97 | Please set the JAVA_HOME variable in your environment to match the 98 | location of your Java installation." 99 | fi 100 | else 101 | JAVACMD="java" 102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 103 | 104 | Please set the JAVA_HOME variable in your environment to match the 105 | location of your Java installation." 106 | fi 107 | 108 | # Increase the maximum file descriptors if we can. 109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 110 | MAX_FD_LIMIT=`ulimit -H -n` 111 | if [ $? -eq 0 ] ; then 112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 113 | MAX_FD="$MAX_FD_LIMIT" 114 | fi 115 | ulimit -n $MAX_FD 116 | if [ $? -ne 0 ] ; then 117 | warn "Could not set maximum file descriptor limit: $MAX_FD" 118 | fi 119 | else 120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 121 | fi 122 | fi 123 | 124 | # For Darwin, add options to specify how the application appears in the dock 125 | if $darwin; then 126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 127 | fi 128 | 129 | # For Cygwin or MSYS, switch paths to Windows format before running java 130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then 131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 133 | 134 | JAVACMD=`cygpath --unix "$JAVACMD"` 135 | 136 | # We build the pattern for arguments to be converted via cygpath 137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 138 | SEP="" 139 | for dir in $ROOTDIRSRAW ; do 140 | ROOTDIRS="$ROOTDIRS$SEP$dir" 141 | SEP="|" 142 | done 143 | OURCYGPATTERN="(^($ROOTDIRS))" 144 | # Add a user-defined pattern to the cygpath arguments 145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 147 | fi 148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 149 | i=0 150 | for arg in "$@" ; do 151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 153 | 154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 156 | else 157 | eval `echo args$i`="\"$arg\"" 158 | fi 159 | i=`expr $i + 1` 160 | done 161 | case $i in 162 | 0) set -- ;; 163 | 1) set -- "$args0" ;; 164 | 2) set -- "$args0" "$args1" ;; 165 | 3) set -- "$args0" "$args1" "$args2" ;; 166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;; 167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 172 | esac 173 | fi 174 | 175 | # Escape application args 176 | save () { 177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 178 | echo " " 179 | } 180 | APP_ARGS=`save "$@"` 181 | 182 | # Collect all arguments for the java command, following the shell quoting and substitution rules 183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 184 | 185 | exec "$JAVACMD" "$@" 186 | -------------------------------------------------------------------------------- /plugin/src/main/kotlin/com/wuyr/incrementalcompiler/utils/ReflectUtil.kt: -------------------------------------------------------------------------------- 1 | @file:Suppress("UNCHECKED_CAST", "KDocMissingDocumentation", "PublicApiImplicitType", "unused") 2 | 3 | package com.wuyr.incrementalcompiler.utils 4 | 5 | import com.wuyr.incrementalcompiler.common.println 6 | import java.io.PrintWriter 7 | import java.io.StringWriter 8 | import java.lang.reflect.Field 9 | import java.lang.reflect.Method 10 | import java.lang.reflect.Modifier 11 | import kotlin.reflect.KClass 12 | 13 | /** 14 | * @author wuyr 15 | * @github https://github.com/wuyr/HookwormForAndroid 16 | * @since 2020-09-10 上午11:32 17 | */ 18 | const val TAG = "ReflectUtil" 19 | 20 | /** 21 | * 发生异常是否抛出(默认不抛出,只打印堆栈信息) 22 | */ 23 | var throwReflectException: Boolean = true 24 | 25 | /** 26 | * 给对象成员变量设置新的值(可以修改final属性,静态的基本类型除外) 27 | * 28 | * @param target 目标对象 29 | * @param fieldName 目标变量名 30 | * @param value 新的值 31 | * 32 | * @return true为成功 33 | */ 34 | fun Class<*>.set(target: Any?, fieldName: String, value: Any?) = try { 35 | findField(fieldName).apply { 36 | isAccessible = true 37 | if (isLocked()) unlock() 38 | set(target, value) 39 | } 40 | true 41 | } catch (e: Exception) { 42 | if (throwReflectException) throw e else false 43 | } 44 | 45 | private fun Field.isLocked() = modifiers and Modifier.FINAL != 0 46 | 47 | private fun Field.unlock() = let { target -> 48 | try { 49 | Field::class.java.getDeclaredField("modifiers") 50 | } catch (e: Exception) { 51 | Field::class.java.getDeclaredField("accessFlags") 52 | }.run { 53 | isAccessible = true 54 | setInt(target, target.modifiers and Modifier.FINAL.inv()) 55 | } 56 | } 57 | 58 | /** 59 | * 获取目标对象的变量值 60 | * 61 | * @param target 目标对象 62 | * @param fieldName 目标变量名 63 | * 64 | * @return 目标变量值(获取失败则返回null) 65 | */ 66 | fun Class<*>.get(target: Any?, fieldName: String) = try { 67 | findField(fieldName).run { 68 | isAccessible = true 69 | get(target) as? T? 70 | } 71 | } catch (e: Exception) { 72 | if (throwReflectException) throw e else e.stackTraceString.println() 73 | null 74 | } 75 | 76 | /** 77 | * 调用目标对象的方法 78 | * 79 | * @param target 目标对象 80 | * @param methodName 目标方法名 81 | * @param paramsPairs 参数类型和参数值的键值对。示例: 82 | *
 83 |  *  val view = LayoutInflater::class.invoke(layoutInflater, "tryInflatePrecompiled",
 84 |  *      Int::class to R.layout.view_test,
 85 |  *      Resource::class to context.resource,
 86 |  *      ViewGroup::class to rootView,
 87 |  *      Boolean::class to false
 88 |  *  )
 89 |  * 
90 | * 91 | * @return 方法返回值 92 | */ 93 | fun Class<*>.invoke(target: Any?, methodName: String, vararg paramsPairs: Pair, Any?> = emptyArray()) = try { 94 | findMethod(methodName, *paramsPairs.map { it.first.java }.toTypedArray()).run { 95 | isAccessible = true 96 | invoke(target, *paramsPairs.map { it.second }.toTypedArray()) as? T? 97 | } 98 | } catch (e: Exception) { 99 | if (throwReflectException) throw e else e.stackTraceString.println() 100 | null 101 | } 102 | 103 | /** 104 | * 同上,此乃调用void方法,即无返回值 105 | */ 106 | fun Class<*>.invokeVoid(target: Any?, methodName: String, vararg paramsPairs: Pair, Any?> = emptyArray()) { 107 | try { 108 | findMethod(methodName, *paramsPairs.map { it.first.java }.toTypedArray()).run { 109 | isAccessible = true 110 | invoke(target, *paramsPairs.map { it.second }.toTypedArray()) 111 | } 112 | } catch (e: Exception) { 113 | if (throwReflectException) throw e else e.stackTraceString.println() 114 | } 115 | } 116 | 117 | /** 118 | * 创建目标类对象 119 | * 120 | * @param paramsPairs 参数类型和参数值的键值对。示例: 121 | *
122 |  *  val context = ContextImpl::class.newInstance(
123 |  *      ActivityThread::class to ...,
124 |  *      LoadedApk::class to ...,
125 |  *      String::class to ...,
126 |  *      IBinder::class to ...,
127 |  *  )
128 |  *
129 |  *  @return 目标对象新实例
130 |  */
131 | fun  Class<*>.newInstance(vararg paramsPairs: Pair, Any?> = emptyArray()) = try {
132 |     getDeclaredConstructor(*paramsPairs.map { it.first.java }.toTypedArray()).run {
133 |         isAccessible = true
134 |         newInstance(*paramsPairs.map { it.second }.toTypedArray()) as? T?
135 |     }
136 | } catch (e: Exception) {
137 |     if (throwReflectException) throw e else e.stackTraceString.println()
138 |     null
139 | }
140 | 
141 | fun Class<*>.findField(fieldName: String): Field {
142 |     declaredFields.forEach {
143 |         if (it.name == fieldName) {
144 |             return it
145 |         }
146 |     }
147 |     if (this == Any::class.java) {
148 |         throw NoSuchFieldException(fieldName)
149 |     } else {
150 |         if (isInterface) {
151 |             interfaces.forEach {
152 |                 runCatching { it.findField(fieldName) }.getOrNull()?.run { return this }
153 |             }
154 |             throw NoSuchFieldException(fieldName)
155 |         } else return superclass.findField(fieldName)
156 |     }
157 | }
158 | 
159 | fun Class<*>.findMethod(methodName: String, parameterTypes: Array> = emptyArray()): Method {
160 |     declaredMethods.forEach {
161 |         if (it.name == methodName && parameterTypes.contentEquals(it.parameterTypes)) {
162 |             return it
163 |         }
164 |     }
165 |     if (this == Any::class.java) {
166 |         throw NoSuchMethodException(parameterTypes.joinToString(prefix = "$methodName(", postfix = ")") { it.name })
167 |     } else {
168 |         if (isInterface) {
169 |             interfaces.forEach {
170 |                 runCatching { it.findMethod(methodName, parameterTypes) }.getOrNull()?.run { return this }
171 |             }
172 |             throw NoSuchMethodException(parameterTypes.joinToString(prefix = "$methodName(", postfix = ")") { it.name })
173 |         } else return superclass.findMethod(methodName, parameterTypes)
174 |     }
175 | }
176 | 
177 | fun  KClass<*>.invoke(target: Any?, methodName: String, vararg paramsPairs: Pair, Any?> = emptyArray()) = try {
178 |     java.run {
179 |         findMethod(methodName, *paramsPairs.map { it.first.java }.toTypedArray()).run {
180 |             isAccessible = true
181 |             invoke(target, *paramsPairs.map { it.second }.toTypedArray()) as? T?
182 |         }
183 |     }
184 | } catch (e: Exception) {
185 |     if (throwReflectException) throw e else e.println()
186 |     null
187 | }
188 | 
189 | fun KClass<*>.invokeVoid(target: Any?, methodName: String, vararg paramsPairs: Pair, Any?> = emptyArray()) {
190 |     try {
191 |         java.run {
192 |             findMethod(methodName, *paramsPairs.map { it.first.java }.toTypedArray()).run {
193 |                 isAccessible = true
194 |                 invoke(target, *paramsPairs.map { it.second }.toTypedArray())
195 |             }
196 |         }
197 |     } catch (e: Exception) {
198 |         if (throwReflectException) throw e else e.stackTraceString.println()
199 |     }
200 | }
201 | 
202 | fun  KClass<*>.newInstance(vararg paramsPairs: Pair, Any?> = emptyArray()) = try {
203 |     java.run {
204 |         getDeclaredConstructor(*paramsPairs.map { it.first.java }.toTypedArray()).run {
205 |             isAccessible = true
206 |             newInstance(*paramsPairs.map { it.second }.toTypedArray()) as? T?
207 |         }
208 |     }
209 | } catch (e: Exception) {
210 |     if (throwReflectException) throw e else e.stackTraceString.println()
211 |     null
212 | }
213 | 
214 | fun String.set(target: Any?, fieldName: String, value: Any?) =
215 |     Class.forName(this).set(target, fieldName, value)
216 | 
217 | fun  String.get(target: Any?, fieldName: String) =
218 |     Class.forName(this).get(target, fieldName)
219 | 
220 | fun  String.invoke(target: Any?, methodName: String, vararg paramsPairs: Pair, Any?>) =
221 |     Class.forName(this).invoke(target, methodName, *paramsPairs)
222 | 
223 | fun String.invokeVoid(target: Any?, methodName: String, vararg paramsPairs: Pair, Any?>) =
224 |     Class.forName(this).invokeVoid(target, methodName, *paramsPairs)
225 | 
226 | fun  String.newInstance(vararg paramsPairs: Pair, Any?>) =
227 |     Class.forName(this).newInstance(*paramsPairs)
228 | 
229 | fun KClass<*>.set(target: Any?, fieldName: String, value: Any?) = java.set(target, fieldName, value)
230 | 
231 | fun  KClass<*>.get(target: Any?, fieldName: String) = java.get(target, fieldName)
232 | 
233 | val Throwable.stackTraceString: String
234 |     get() = StringWriter().use { sw ->
235 |         PrintWriter(sw).use { pw ->
236 |             printStackTrace(pw)
237 |             pw.flush()
238 |         }
239 |         sw.flush()
240 |     }.toString()


--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
  1 |                                  Apache License
  2 |                            Version 2.0, January 2004
  3 |                         http://www.apache.org/licenses/
  4 | 
  5 |    TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
  6 | 
  7 |    1. Definitions.
  8 | 
  9 |       "License" shall mean the terms and conditions for use, reproduction,
 10 |       and distribution as defined by Sections 1 through 9 of this document.
 11 | 
 12 |       "Licensor" shall mean the copyright owner or entity authorized by
 13 |       the copyright owner that is granting the License.
 14 | 
 15 |       "Legal Entity" shall mean the union of the acting entity and all
 16 |       other entities that control, are controlled by, or are under common
 17 |       control with that entity. For the purposes of this definition,
 18 |       "control" means (i) the power, direct or indirect, to cause the
 19 |       direction or management of such entity, whether by contract or
 20 |       otherwise, or (ii) ownership of fifty percent (50%) or more of the
 21 |       outstanding shares, or (iii) beneficial ownership of such entity.
 22 | 
 23 |       "You" (or "Your") shall mean an individual or Legal Entity
 24 |       exercising permissions granted by this License.
 25 | 
 26 |       "Source" form shall mean the preferred form for making modifications,
 27 |       including but not limited to software source code, documentation
 28 |       source, and configuration files.
 29 | 
 30 |       "Object" form shall mean any form resulting from mechanical
 31 |       transformation or translation of a Source form, including but
 32 |       not limited to compiled object code, generated documentation,
 33 |       and conversions to other media types.
 34 | 
 35 |       "Work" shall mean the work of authorship, whether in Source or
 36 |       Object form, made available under the License, as indicated by a
 37 |       copyright notice that is included in or attached to the work
 38 |       (an example is provided in the Appendix below).
 39 | 
 40 |       "Derivative Works" shall mean any work, whether in Source or Object
 41 |       form, that is based on (or derived from) the Work and for which the
 42 |       editorial revisions, annotations, elaborations, or other modifications
 43 |       represent, as a whole, an original work of authorship. For the purposes
 44 |       of this License, Derivative Works shall not include works that remain
 45 |       separable from, or merely link (or bind by name) to the interfaces of,
 46 |       the Work and Derivative Works thereof.
 47 | 
 48 |       "Contribution" shall mean any work of authorship, including
 49 |       the original version of the Work and any modifications or additions
 50 |       to that Work or Derivative Works thereof, that is intentionally
 51 |       submitted to Licensor for inclusion in the Work by the copyright owner
 52 |       or by an individual or Legal Entity authorized to submit on behalf of
 53 |       the copyright owner. For the purposes of this definition, "submitted"
 54 |       means any form of electronic, verbal, or written communication sent
 55 |       to the Licensor or its representatives, including but not limited to
 56 |       communication on electronic mailing lists, source code control systems,
 57 |       and issue tracking systems that are managed by, or on behalf of, the
 58 |       Licensor for the purpose of discussing and improving the Work, but
 59 |       excluding communication that is conspicuously marked or otherwise
 60 |       designated in writing by the copyright owner as "Not a Contribution."
 61 | 
 62 |       "Contributor" shall mean Licensor and any individual or Legal Entity
 63 |       on behalf of whom a Contribution has been received by Licensor and
 64 |       subsequently incorporated within the Work.
 65 | 
 66 |    2. Grant of Copyright License. Subject to the terms and conditions of
 67 |       this License, each Contributor hereby grants to You a perpetual,
 68 |       worldwide, non-exclusive, no-charge, royalty-free, irrevocable
 69 |       copyright license to reproduce, prepare Derivative Works of,
 70 |       publicly display, publicly perform, sublicense, and distribute the
 71 |       Work and such Derivative Works in Source or Object form.
 72 | 
 73 |    3. Grant of Patent License. Subject to the terms and conditions of
 74 |       this License, each Contributor hereby grants to You a perpetual,
 75 |       worldwide, non-exclusive, no-charge, royalty-free, irrevocable
 76 |       (except as stated in this section) patent license to make, have made,
 77 |       use, offer to sell, sell, import, and otherwise transfer the Work,
 78 |       where such license applies only to those patent claims licensable
 79 |       by such Contributor that are necessarily infringed by their
 80 |       Contribution(s) alone or by combination of their Contribution(s)
 81 |       with the Work to which such Contribution(s) was submitted. If You
 82 |       institute patent litigation against any entity (including a
 83 |       cross-claim or counterclaim in a lawsuit) alleging that the Work
 84 |       or a Contribution incorporated within the Work constitutes direct
 85 |       or contributory patent infringement, then any patent licenses
 86 |       granted to You under this License for that Work shall terminate
 87 |       as of the date such litigation is filed.
 88 | 
 89 |    4. Redistribution. You may reproduce and distribute copies of the
 90 |       Work or Derivative Works thereof in any medium, with or without
 91 |       modifications, and in Source or Object form, provided that You
 92 |       meet the following conditions:
 93 | 
 94 |       (a) You must give any other recipients of the Work or
 95 |           Derivative Works a copy of this License; and
 96 | 
 97 |       (b) You must cause any modified files to carry prominent notices
 98 |           stating that You changed the files; and
 99 | 
100 |       (c) You must retain, in the Source form of any Derivative Works
101 |           that You distribute, all copyright, patent, trademark, and
102 |           attribution notices from the Source form of the Work,
103 |           excluding those notices that do not pertain to any part of
104 |           the Derivative Works; and
105 | 
106 |       (d) If the Work includes a "NOTICE" text file as part of its
107 |           distribution, then any Derivative Works that You distribute must
108 |           include a readable copy of the attribution notices contained
109 |           within such NOTICE file, excluding those notices that do not
110 |           pertain to any part of the Derivative Works, in at least one
111 |           of the following places: within a NOTICE text file distributed
112 |           as part of the Derivative Works; within the Source form or
113 |           documentation, if provided along with the Derivative Works; or,
114 |           within a display generated by the Derivative Works, if and
115 |           wherever such third-party notices normally appear. The contents
116 |           of the NOTICE file are for informational purposes only and
117 |           do not modify the License. You may add Your own attribution
118 |           notices within Derivative Works that You distribute, alongside
119 |           or as an addendum to the NOTICE text from the Work, provided
120 |           that such additional attribution notices cannot be construed
121 |           as modifying the License.
122 | 
123 |       You may add Your own copyright statement to Your modifications and
124 |       may provide additional or different license terms and conditions
125 |       for use, reproduction, or distribution of Your modifications, or
126 |       for any such Derivative Works as a whole, provided Your use,
127 |       reproduction, and distribution of the Work otherwise complies with
128 |       the conditions stated in this License.
129 | 
130 |    5. Submission of Contributions. Unless You explicitly state otherwise,
131 |       any Contribution intentionally submitted for inclusion in the Work
132 |       by You to the Licensor shall be under the terms and conditions of
133 |       this License, without any additional terms or conditions.
134 |       Notwithstanding the above, nothing herein shall supersede or modify
135 |       the terms of any separate license agreement you may have executed
136 |       with Licensor regarding such Contributions.
137 | 
138 |    6. Trademarks. This License does not grant permission to use the trade
139 |       names, trademarks, service marks, or product names of the Licensor,
140 |       except as required for reasonable and customary use in describing the
141 |       origin of the Work and reproducing the content of the NOTICE file.
142 | 
143 |    7. Disclaimer of Warranty. Unless required by applicable law or
144 |       agreed to in writing, Licensor provides the Work (and each
145 |       Contributor provides its Contributions) on an "AS IS" BASIS,
146 |       WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 |       implied, including, without limitation, any warranties or conditions
148 |       of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 |       PARTICULAR PURPOSE. You are solely responsible for determining the
150 |       appropriateness of using or redistributing the Work and assume any
151 |       risks associated with Your exercise of permissions under this License.
152 | 
153 |    8. Limitation of Liability. In no event and under no legal theory,
154 |       whether in tort (including negligence), contract, or otherwise,
155 |       unless required by applicable law (such as deliberate and grossly
156 |       negligent acts) or agreed to in writing, shall any Contributor be
157 |       liable to You for damages, including any direct, indirect, special,
158 |       incidental, or consequential damages of any character arising as a
159 |       result of this License or out of the use or inability to use the
160 |       Work (including but not limited to damages for loss of goodwill,
161 |       work stoppage, computer failure or malfunction, or any and all
162 |       other commercial damages or losses), even if such Contributor
163 |       has been advised of the possibility of such damages.
164 | 
165 |    9. Accepting Warranty or Additional Liability. While redistributing
166 |       the Work or Derivative Works thereof, You may choose to offer,
167 |       and charge a fee for, acceptance of support, warranty, indemnity,
168 |       or other liability obligations and/or rights consistent with this
169 |       License. However, in accepting such obligations, You may act only
170 |       on Your own behalf and on Your sole responsibility, not on behalf
171 |       of any other Contributor, and only if You agree to indemnify,
172 |       defend, and hold each Contributor harmless for any liability
173 |       incurred by, or claims asserted against, such Contributor by reason
174 |       of your accepting any such warranty or additional liability.
175 | 
176 |    END OF TERMS AND CONDITIONS
177 | 
178 |    APPENDIX: How to apply the Apache License to your work.
179 | 
180 |       To apply the Apache License to your work, attach the following
181 |       boilerplate notice, with the fields enclosed by brackets "[]"
182 |       replaced with your own identifying information. (Don't include
183 |       the brackets!)  The text should be enclosed in the appropriate
184 |       comment syntax for the file format. We also recommend that a
185 |       file or class name and description of purpose be included on the
186 |       same "printed page" as the copyright notice for easier
187 |       identification within third-party archives.
188 | 
189 |    Copyright [yyyy] [name of copyright owner]
190 | 
191 |    Licensed under the Apache License, Version 2.0 (the "License");
192 |    you may not use this file except in compliance with the License.
193 |    You may obtain a copy of the License at
194 | 
195 |        http://www.apache.org/licenses/LICENSE-2.0
196 | 
197 |    Unless required by applicable law or agreed to in writing, software
198 |    distributed under the License is distributed on an "AS IS" BASIS,
199 |    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 |    See the License for the specific language governing permissions and
201 |    limitations under the License.
202 | 


--------------------------------------------------------------------------------
/plugin/src/main/kotlin/com/wuyr/incrementalcompiler/tasks/IncrementalCompiler.kt:
--------------------------------------------------------------------------------
  1 | package com.wuyr.incrementalcompiler.tasks
  2 | 
  3 | import com.wuyr.incrementalcompiler.common.FingerprinterRegistryDelegate
  4 | import com.wuyr.incrementalcompiler.common.isLibrary
  5 | import com.wuyr.incrementalcompiler.common.plugin
  6 | import com.wuyr.incrementalcompiler.common.println
  7 | import com.wuyr.incrementalcompiler.utils.*
  8 | import org.gradle.api.DefaultTask
  9 | import org.gradle.api.Plugin
 10 | import org.gradle.api.Project
 11 | import org.gradle.api.internal.changedetection.changes.ChangesOnlyIncrementalTaskInputs
 12 | import org.gradle.api.internal.file.FileCollectionFactory
 13 | import org.gradle.api.internal.file.collections.MinimalFileSet
 14 | import org.gradle.api.internal.project.ProjectInternal
 15 | import org.gradle.api.internal.tasks.properties.DefaultTaskProperties
 16 | import org.gradle.api.internal.tasks.properties.InputFilePropertySpec
 17 | import org.gradle.api.internal.tasks.properties.PropertyWalker
 18 | import org.gradle.api.internal.tasks.properties.TaskProperties
 19 | import org.gradle.api.tasks.Internal
 20 | import org.gradle.api.tasks.compile.AbstractCompile
 21 | import org.gradle.api.tasks.compile.JavaCompile
 22 | import org.gradle.api.tasks.incremental.IncrementalTaskInputs
 23 | import org.gradle.api.tasks.incremental.InputFileDetails
 24 | import org.gradle.cache.PersistentIndexedCache
 25 | import org.gradle.caching.internal.origin.OriginMetadata
 26 | import org.gradle.internal.execution.history.AfterPreviousExecutionState
 27 | import org.gradle.internal.execution.history.ExecutionHistoryStore
 28 | import org.gradle.internal.execution.history.changes.*
 29 | import org.gradle.internal.execution.history.impl.DefaultExecutionHistoryStore
 30 | import org.gradle.internal.fingerprint.FileCollectionFingerprint
 31 | import org.gradle.internal.fingerprint.impl.EmptyCurrentFileCollectionFingerprint
 32 | import org.gradle.internal.snapshot.impl.ImplementationSnapshot
 33 | import org.gradle.work.InputChanges
 34 | import java.io.File
 35 | 
 36 | /**
 37 |  * @author wuyr
 38 |  * @github https://github.com/wuyr/incremental-compiler
 39 |  * @since 2021-06-20 下午6:18
 40 |  */
 41 | open class IncrementalCompiler : DefaultTask() {
 42 | 
 43 |     companion object {
 44 |         const val TASK_NAME = "incrementalCompile"
 45 |         private const val COMPILE_KOTLIN_TASK = "compileDebugKotlin"
 46 |         private const val COMPILE_JAVA_TASK = "compileDebugJavaWithJavac"
 47 |     }
 48 | 
 49 |     /**
 50 |      * 是否需要生成R文件
 51 |      */
 52 |     @get: Internal
 53 |     open val rFileNeeded: Boolean
 54 |         get() = (project as ProjectInternal).run {
 55 |             // R file does not exist
 56 |             (((tasks.findByName(COMPILE_KOTLIN_TASK) as? AbstractCompile)?.classpath?.files ?: emptySet())
 57 |                     + ((tasks.findByName(COMPILE_JAVA_TASK) as? AbstractCompile)?.classpath?.files ?: emptySet()))
 58 |                 .filter { it.name == "R.jar" }.any { !it.exists() }
 59 |                     // no local kotlin files compile records and the kotlin source code not empty
 60 |                     || (!services.get(ExecutionHistoryStore::class.java).load(":$name:$COMPILE_KOTLIN_TASK").isPresent
 61 |                     && (tasks.findByName(COMPILE_KOTLIN_TASK) as? AbstractCompile)?.source?.any { it.name.endsWith(".kt") } ?: false)
 62 |                     // no local java files compile records and the java source code not empty
 63 |                     || (!services.get(ExecutionHistoryStore::class.java).load(":$name:$COMPILE_JAVA_TASK").isPresent
 64 |                     && (tasks.findByName(COMPILE_JAVA_TASK) as? AbstractCompile)?.source?.any { it.name.endsWith(".java") } ?: false)
 65 |         }
 66 | 
 67 |     /**
 68 |      * 是否需要生成BuildConfig
 69 |      */
 70 |     private val buildConfigNeeded: Boolean
 71 |         get() = (project as ProjectInternal).run { !File(buildDir, "generated/source/buildConfig/debug").exists() }
 72 | 
 73 |     /**
 74 |      * 编译Kotlin源码
 75 |      */
 76 |     fun compileKotlin(): List {
 77 |         if (buildConfigNeeded) {
 78 |             generateBuildConfig()
 79 |         }
 80 |         initCompileIfNeeded()
 81 |         var compiledFiles = emptyList()
 82 |         val compileTask = (project.tasks.findByName(COMPILE_KOTLIN_TASK) as? AbstractCompile) ?: return emptyList()
 83 |         val sourcePostfix = ".kt"
 84 |         compileTask.doIncrementalCompile(COMPILE_KOTLIN_TASK, sourcePostfix) { inputChanges ->
 85 |             runCatching {
 86 |                 compileTask::class.invokeVoid(
 87 |                     compileTask, "execute",
 88 |                     IncrementalTaskInputs::class to ChangesOnlyIncrementalTaskInputs(inputChanges.allFileChanges)
 89 |                 )
 90 |             }.isSuccess.also { isSuccess ->
 91 |                 if (isSuccess) {
 92 |                     val outputDir = compileTask.destinationDir
 93 |                     compiledFiles = inputChanges.allFileChanges.filter { it.file.name.endsWith(sourcePostfix) && !it.isRemoved }.map {
 94 |                         "${outputDir}/${(it as DefaultFileChange).normalizedPath.substringBeforeLast(".").replace("\\.", "/")}.class".run {
 95 |                             val classFile = File(this)
 96 |                             if (classFile.exists()) this else {
 97 |                                 if (classFile.nameWithoutExtension.endsWith("Kt")) {
 98 |                                     "${classFile.parent}/${classFile.nameWithoutExtension.substringBeforeLast("Kt")}.class"
 99 |                                 } else {
100 |                                     "${classFile.parent}/${classFile.nameWithoutExtension}Kt.class"
101 |                                 }
102 |                             }
103 |                         }
104 |                     }
105 |                 }
106 |             }
107 |         }
108 |         return compiledFiles
109 |     }
110 | 
111 |     /**
112 |      * 编译Java源码
113 |      */
114 |     fun compileJava(): List {
115 |         if (buildConfigNeeded) {
116 |             generateBuildConfig()
117 |         }
118 |         initCompileIfNeeded()
119 |         var compiledFiles = emptyList()
120 |         val compileTask = (project.tasks.findByName(COMPILE_JAVA_TASK) as? AbstractCompile)?.apply {
121 |             outputs.setPreviousOutputFiles(
122 |                 project.createFileCollection(name, HashSet().apply {
123 |                     add(File(project.buildDir, "generated/ap_generated_sources/debug/out").apply { mkdirs() })
124 |                     add(File(project.buildDir, "intermediates/javac/debug/classes").apply { mkdirs() })
125 |                 })
126 |             )
127 |         } ?: return emptyList()
128 |         val sourcePostfix = ".java"
129 |         compileTask.doIncrementalCompile(COMPILE_JAVA_TASK, sourcePostfix) { inputChanges ->
130 |             runCatching {
131 |                 JavaCompile::class.invokeVoid(compileTask, "compile", InputChanges::class to inputChanges)
132 |             }.isSuccess.also { isSuccess ->
133 |                 if (isSuccess) {
134 |                     val outputDir = compileTask.destinationDir
135 |                     compiledFiles = inputChanges.allFileChanges.filter { it.file.name.endsWith(sourcePostfix) && !it.isRemoved }.map {
136 |                         "${outputDir}/${(it as DefaultFileChange).normalizedPath.substringBeforeLast(".").replace("\\.", "/")}.class"
137 |                     }
138 |                 }
139 |             }
140 |         }
141 |         return compiledFiles
142 |     }
143 | 
144 |     private fun generateBuildConfig() = project.tasks.findByName("generateDebugBuildConfig")?.let { it::class.invokeVoid(it, "doTaskAction") }
145 | 
146 |     private var androidTasksCreated = false
147 | 
148 |     private fun initCompileIfNeeded() {
149 |         if (!androidTasksCreated) {
150 |             project.plugin.run {
151 |                 if (!isLibrary) {
152 |                     initCompileSdkVersion()
153 |                     createAndroidTasks()
154 |                     androidTasksCreated = true
155 |                 }
156 |             }
157 |         }
158 |     }
159 | 
160 |     private inline fun AbstractCompile.doIncrementalCompile(taskName: String, sourcePostfix: String, doCompile: (InputChangesInternal) -> Boolean) {
161 |         if (source.isEmpty || source.none { it.name.endsWith(sourcePostfix) }) {
162 |             "${project.name}:$taskName empty source, skipped compile.".println()
163 |             return
164 |         }
165 |         val (inputChanges, currentInputFileProperties) =
166 |             if (taskName == COMPILE_JAVA_TASK) computeJavaChanges() else computeKotlinChanges()
167 |         val fileChanges = inputChanges.allFileChanges
168 |         if (!fileChanges.iterator().hasNext() || fileChanges.none { it.file.name.endsWith(sourcePostfix) }) {
169 |             "${project.name}:$taskName no source has changes, skipped compile.".println()
170 |             return
171 |         }
172 |         fileChanges.logChanges(taskName)
173 |         if (doCompile(inputChanges)) {
174 |             currentInputFileProperties.saveCompileRecords(taskName)
175 |         }
176 |     }
177 | 
178 |     /**
179 |      * 更新本次编译记录
180 |      */
181 |     private fun Map.saveCompileRecords(taskName: String) {
182 |         val storeKey = ":${project.name}:$taskName"
183 |         val defaultExecutionHistoryStore = (project as ProjectInternal).services.get(ExecutionHistoryStore::class.java)
184 |         val optional = defaultExecutionHistoryStore.load(storeKey)
185 |         if (!optional.isPresent) {
186 |             throw IllegalStateException("Please run 'assembleDebug' task first!")
187 |         }
188 |         val lastState = optional.get()
189 |         lastState::class.java.set(lastState, "inputFileProperties", this)
190 |         defaultExecutionHistoryStore::class.get>(
191 |             defaultExecutionHistoryStore, "store"
192 |         )!!.put(storeKey, lastState)
193 |         "$storeKey compile records has saved".println()
194 |     }
195 | 
196 |     private fun MutableIterable.logChanges(taskName: String) {
197 |         "============================".println()
198 |         "${project.name}:$taskName file changes:".println()
199 |         forEach { it.println() }
200 |         "============================".println()
201 |     }
202 | 
203 |     private fun AbstractCompile.computeJavaChanges() = computeChanges(COMPILE_JAVA_TASK)
204 | 
205 |     private fun AbstractCompile.computeKotlinChanges() = computeChanges(COMPILE_KOTLIN_TASK)
206 | 
207 |     /**
208 |      * 根据文件指纹计算有变更的文件
209 |      */
210 |     private fun AbstractCompile.computeChanges(taskName: String): Pair> {
211 |         val target = project as ProjectInternal
212 |         var optional = target.services.get(ExecutionHistoryStore::class.java).load(":${project.name}:$taskName")
213 |         if (!optional.isPresent || isFullCompilation) {
214 |             initStore(taskName)
215 |             optional = target.services.get(ExecutionHistoryStore::class.java).load(":${project.name}:$taskName")
216 |         }
217 |         val lastState = optional.get()
218 |         val lastInputFileProperties = lastState::class.java.get>(lastState, "inputFileProperties")!!
219 |         val currentInputFilePropertiesBuilder = lastInputFileProperties::class.invoke(null, "naturalOrder")!!
220 |         val immutableBiMapClass = lastInputFileProperties::class.java.classLoader.loadClass("com.google.common.collect.ImmutableBiMap")
221 |         val immutableBiMapBuilder = immutableBiMapClass.invoke(null, "builder")!!
222 | 
223 |         fun Any.put(key: Any, value: Any) = this::class.invokeVoid(this, "put", Any::class to key, Any::class to value)
224 | 
225 |         val fingerPrinter = FingerprinterRegistryDelegate.create(target)
226 |         DefaultTaskProperties::class.get>(compileTaskProperties, "inputFileProperties")!!.onEach {
227 |             val value = it.value
228 |             val incremental = it.isIncremental || it.isSkipWhenEmpty
229 |             val propertyName = it.propertyName
230 |             val fingerprint = fingerPrinter.fingerprint(it)
231 |             if (incremental && value != null) {
232 |                 immutableBiMapBuilder.put(propertyName, value)
233 |             }
234 |             currentInputFilePropertiesBuilder.put(propertyName, fingerprint)
235 |         }
236 |         val immutableBiMap = immutableBiMapBuilder::class.invoke>(immutableBiMapBuilder, "build")!!
237 |         val currentInputFileProperties =
238 |             currentInputFilePropertiesBuilder::class.invoke>(currentInputFilePropertiesBuilder, "build")!!
239 |         val incrementalInputProperties = DefaultIncrementalInputProperties::class.newInstance(
240 |             immutableBiMapClass.kotlin to immutableBiMap::class.java.cast(immutableBiMap)
241 |         )!!
242 |         val inputFileChanges = incrementalInputProperties::class.invoke(
243 |             incrementalInputProperties, "incrementalChanges",
244 |             lastInputFileProperties::class to lastInputFileProperties,
245 |             currentInputFileProperties::class to currentInputFileProperties
246 |         )!!
247 |         return IncrementalInputChanges::class.newInstance(
248 |             InputFileChanges::class to inputFileChanges, IncrementalInputProperties::class to incrementalInputProperties
249 |         )!! to currentInputFileProperties
250 |     }
251 | 
252 |     private fun initStore(taskName: String) {
253 |         val target = project as ProjectInternal
254 |         DefaultExecutionHistoryStore::class.java.methods.find { it.name == "store" }?.let {
255 |             val parameterTypes = it.parameterTypes
256 |             val classLoader = parameterTypes[3].classLoader
257 |             val immutableListClass = Class.forName("com.google.common.collect.ImmutableList", true, classLoader)
258 |             val immutableSortedMapClass = Class.forName("com.google.common.collect.ImmutableSortedMap", true, classLoader)
259 |             it.invoke(
260 |                 target.services.get(ExecutionHistoryStore::class.java),
261 |                 ":${project.name}:$taskName",
262 |                 OriginMetadata("", 0),
263 |                 ImplementationSnapshot.of("", null),
264 |                 immutableListClass.cast(
265 |                     Class.forName("com.google.common.collect.RegularImmutableList", true, classLoader).get(null, "EMPTY")!!
266 |                 ),
267 |                 immutableSortedMapClass.cast(immutableSortedMapClass.get(null, "NATURAL_EMPTY_MAP")!!),
268 |                 immutableSortedMapClass.invoke(
269 |                     null, "copyOf", java.util.Map::class to mapOf(
270 |                         "source" to EmptyCurrentFileCollectionFingerprint("CLASSPATH"),
271 |                         "stableSources" to EmptyCurrentFileCollectionFingerprint("CLASSPATH")
272 |                     )
273 |                 )!!,
274 |                 immutableSortedMapClass.cast(immutableSortedMapClass.get(null, "NATURAL_EMPTY_MAP")!!),
275 |                 false
276 |             )
277 |         }
278 |     }
279 | 
280 |     // output dir does not exist or empty
281 |     private val AbstractCompile.isFullCompilation: Boolean
282 |         get() = outputs.files.files.none { it.exists() || it.isDirectory && it.list()?.isNotEmpty() ?: false }
283 | 
284 |     private val DefaultTask.compileTaskProperties: TaskProperties
285 |         get() = DefaultTaskProperties.resolve(
286 |             inputs::class.get(inputs, "propertyWalker")!!,
287 |             inputs::class.get(inputs, "fileCollectionFactory")!!, this
288 |         )
289 | 
290 |     private fun Plugin<*>.createAndroidTasks() = runCatching {
291 |         (project as ProjectInternal).state.configured()
292 |         this::class.java.invokeVoid(project.plugin, "createAndroidTasks")
293 |     }.isSuccess
294 | 
295 |     @Suppress("PrivateApi")
296 |     private fun Plugin<*>.initCompileSdkVersion() {
297 |         val basePluginClass = this::class.java
298 |         val sdkVersion = basePluginClass.invoke(this, "findHighestSdkInstalled")!!
299 |         val extension = basePluginClass.get(this, "extension")!!
300 |         val baseExtensionClass = extension::class.java.classLoader.loadClass("com.android.build.gradle.BaseExtension")
301 |         if (baseExtensionClass.invoke(extension, "getCompileSdkVersion") == null) {
302 |             baseExtensionClass.invokeVoid(extension, "setCompileSdkVersion", String::class to sdkVersion)
303 |         }
304 |     }
305 | 
306 |     private fun Project.createFileCollection(name: String, content: Set) =
307 |         (this as ProjectInternal).services.get(FileCollectionFactory::class.java).create(object : MinimalFileSet {
308 |             override fun getFiles() = content
309 |             override fun getDisplayName() = name
310 |         })
311 | }


--------------------------------------------------------------------------------