Gradle:将 KAPT 生成的 Kotlin 源添加到源 JAR 的正确方法

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

我使用 KAPT 为我的项目生成一些代码,我想将此生成的代码包含到sources.jar 工件中。

通常的技巧是将生成的文件夹添加到主源集,但这不起作用:KAPT 使用源来进行生成,这会创建循环依赖关系。

我已经成功创建了这段构建脚本:

kapt {
    annotationProcessor("com.example.MyGenerator")
}

sourceSets {
    create("generated") {
        kotlin {
           srcDir("${buildDir}/generated/source/kaptKotlin/main")
        }
    }
}

tasks.named<Jar>("sourcesJar").configure {
    dependsOn("jar") // A bit of overkill, but will do for the sake of example
    archiveClassifier = "sources"
    // main source set is already there
    from(sourceSets.named("generated").get().allSource)
}

这甚至按预期工作:所有源都在 JAR 中,但是当我将项目加载到 IntelliJ IDEA 中时,它显示以下警告:

Duplicate content roots detected
Path [C:/Users/gagar/IdeaProjects/example/example-module/build/generated/source/kaptKotlin/main] of module [example.example-module.generated] was removed from modules [example.example-module.main]

这让我想到生成的源已经在

main
sourceSet 上。但是,当我尝试从
sourcesJar
源集生成
main
时,没有生成源。使用
println
调试构建不会给我任何东西:对于主源集,没有生成的文件夹,并且除了
test
之外没有其他源集。

我想知道,是否有更好的方法从构建脚本中获取生成的源集?

kotlin gradle intellij-idea kapt
1个回答
0
投票

事实证明,将生成的目录添加到主源集中毕竟是正确的方法。您还需要声明

kaptKotlin
sourcesJar
任务的依赖:

kapt {
    annotationProcessor("com.example.MyGenerator")
}

sourceSets {
    main {
        kotlin.srcDir("${layout.buildDirectory.get()}/generated/source/kaptKotlin/main")
    }
}

tasks.named<Jar>("sourcesJar").configure {
    dependsOn("kaptKotlin")
}
© www.soinside.com 2019 - 2024. All rights reserved.