如何将 gradle 中的 groovy 任务转换为 Gradle Kotlin DSL 以生成 pom.xml?

Posted

技术标签:

【中文标题】如何将 gradle 中的 groovy 任务转换为 Gradle Kotlin DSL 以生成 pom.xml?【英文标题】:How can I convert a groovy task in gradle into Gradle Kotlin DSL to generate a pom.xml? 【发布时间】:2018-07-08 21:48:32 【问题描述】:

以下 Gradle 脚本的 build.gradle.kts 版本是什么?

apply plugin: 'maven'
apply plugin: 'java'

sourceCompatibility = 7
targetCompatibility = 7

dependencies 
    compile            'com.google.guava:guava:13.0.1'
    compile            'joda-time:joda-time:2.1'

    testCompile        'junit:junit:4.11'
    testCompile        'org.mockito:mockito-core:1.9.5'


task writeNewPom << 
    pom 
        project 
            groupId 'org.example'
            artifactId 'test'
            version '1.0.0'

            inceptionYear '2008'
            licenses 
                license 
                    name 'The Apache Software License, Version 2.0'
                    url 'http://www.apache.org/licenses/LICENSE-2.0.txt'
                    distribution 'repo'
                
            
        
    .writeTo("$buildDir/newpom.xml")

参考文献

1- Gradle 示例为 here。

【问题讨论】:

【参考方案1】:

我相信这与build.gradle.kts 文件相同:

plugins 
    java
    maven


java 
    sourceCompatibility = JavaVersion.VERSION_1_7
    targetCompatibility = JavaVersion.VERSION_1_7


repositories 
    jcenter()


dependencies 
    compile("com.google.guava:guava:13.0.1")
    compile("joda-time:joda-time:2.1")

    testCompile("junit:junit:4.11")
    testCompile("org.mockito:mockito-core:1.9.5")


tasks 
    "writeNewPom" 
        doLast 
            project.the<MavenPluginConvention>().pom 
                project 
                    groupId = "org.example"
                    artifactId = "test"
                    version = "1.0.0"
                    withGroovyBuilder 
                        "inceptionYear"("2008")
                        "licenses" 
                            "license" 
                                "name"("The Apache Software License, Version 2.0")
                                "url"("http://www.apache.org/licenses/LICENSE-2.0.txt")
                                "distribution"("repo")
                            
                        
                    
                
            .writeTo("$buildDir/newPom.xml")
        
    

您必须使用withGroovyBuilder 方法将无类型属性添加到模型中

【讨论】:

感谢@tim_yates,非常有帮助!我相信如果没有我们的开源社区,我们会落后几个世纪。

以上是关于如何将 gradle 中的 groovy 任务转换为 Gradle Kotlin DSL 以生成 pom.xml?的主要内容,如果未能解决你的问题,请参考以下文章

将 maven 代码生成转换为 gradle 任务

理解 gradle 任务定义中的 groovy 语法

Android Gradle 插件将自定义 Gradle 插件上传到自建 Maven 仓库 ② ( java 和 groovy 插件自带文档任务 | 自定义文档打包任务 | 生成文档包 )

如何将 Maven 构建转换为 Gradle?

在android studio中构建groovy时,gradle错误“任务':app:compileDebugJava'执行失败”

gradle:自定义任务task