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

问题描述 投票:1回答:1

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

所以我在buildSrc项目中编写了扩展函数(Shortcuts.kt):

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

并将其注册为扩展模块,如here所述:

# 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)
gradle groovy kotlin build.gradle
1个回答
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
}
© www.soinside.com 2019 - 2024. All rights reserved.