如何为Gradle依赖项{}块编写扩展方法

时间:2018-09-11 07:03:07

标签: gradle groovy kotlin build.gradle

我正在尝试为DependencyHandler编写扩展方法。 自动完成这些方法的主要目标之一。

所以我像这样(Shortcuts.kt)在buildSrc项目中编写了扩展功能:

fun DependencyHandler.autoValue() {
    add("compileOnly", Libs.Auto.autoValueAnnotations)
    add("annotationProcessor", Libs.Auto.autoValueCompiler)
}

并按照https://stackoverflow.com/a/44304198/5435182所述将其注册为扩展模块:

# File: src/main/resources/META-INF/services/org.codehaus.groovy.runtime.ExtensionModule
moduleName = buildSrc
moduleVersion = 1.0
extensionClasses = com.example.test.ShortcutsKt

我想在build.gradle文件中使用这些方法,例如:

dependencies {
    ...
    autoValue()
}

它出现在dependencies{}块内的自动完成列表中,但是在配置时出现错误:

org.gradle.internal.metaobject.AbstractDynamicObject$CustomMessageMissingMethodException: Could not find method autoValue() for arguments [] on object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler.
    at org.gradle.internal.metaobject.AbstractDynamicObject.methodMissingException(AbstractDynamicObject.java:179)
    at org.gradle.internal.metaobject.ConfigureDelegate.invokeMethod(ConfigureDelegate.java:87)
    at org.codehaus.groovy.runtime.metaclass.ClosureMetaClass.invokeOnDelegationObjects(ClosureMetaClass.java:430)
    at org.codehaus.groovy.runtime.metaclass.ClosureMetaClass.invokeMethod(ClosureMetaClass.java:369)
    at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1022)
    at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.callCurrent(PogoMetaClassSite.java:69)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:158)
    at build_dh4v5lw1dkt4b2nii5ope5rmy$_run_closure1.doCall(/.../app/build.gradle:29)

1 个答案:

答案 0 :(得分:1)

Gradle DefaultDependencyHandler实现自定义方法解析策略(以处理诸如testCompile(smth)之类的范围符号),因此可以通过dependencies.ext属性添加其他方法:

dependencies.ext.autoValue = {
    dependencies.add("compileOnly", Libs.Auto.autoValueAnnotations)
    dependencies.add("annotationProcessor", Libs.Auto.autoValueCompiler)
}

但是在这种情况下,您不会自动完成。

要启用自动填充功能,您可以通过dependencies.ext从buildSrc中混合使用这两种方法和代理扩展方法:

import com.example.test.ShortcutsKt

import java.lang.reflect.Method
import java.lang.reflect.Modifier

// DependencyHandler implementation resolves all undeclared methods by self,
// so we need to add these extension methods to dependencies.ext
def methodNames = ShortcutsKt.declaredMethods
        .findAll { isDependencyHandlerExtension(it) }
        .collect { it.name }
        .unique()

methodNames.each { String methodName ->
    dependencies.ext[methodName] = { Object... args ->
        ShortcutsKt."$methodName"(dependencies, *args)
    }
}

private static boolean isDependencyHandlerExtension(Method method) {
    return Modifier.isPublic(method.getModifiers()) &&
            Modifier.isStatic(method.getModifiers()) &&
            method.parameterCount > 0 &&
            method.parameterTypes[0] == DependencyHandler.class
}