Как мне опубликовать вторую библиотеку из другого набора исходных текстов в gradle?

#gradle #kotlin #gradle-kotlin-dsl

#gradle #kotlin #gradle-kotlin-dsl

Вопрос:

У меня есть этот tlib набор исходных текстов

 sourceSets {
    val main by getting
    val tlib by creating {
        compileClasspath  = main.output
        runtimeClasspath  = main.output
    }
    val test by getting {
        compileClasspath  = tlib.output
        runtimeClasspath  = tlib.output
    }
}

configurations {
    val tlibCompile by getting {
        extendsFrom(configurations["implementation"])
    }
}
  

Я представляю что-то подобное, но это не завершено

 publishing {
    publications {
        val tlibSourcesJar by tasks.registering(Jar::class) {
            classifier = "sources"
            from(sourceSets["tlib"].allSource)
        }

        register("mavenTLib", MavenPublication::class) {
            from(components["tlib"])
            artifact(tlibSourcesJar.get())
        }
    }
}
  

но я получаю

 Could not create domain object 'mavenTLib' (MavenPublication)
> SoftwareComponentInternal with name 'tlib' not found.
  

Как я могу опубликовать мою тестовую библиотеку отдельно от моей основной библиотеки?

Ответ №1:

до некоторой степени это работает, но, вероятно, не лучший способ сделать это

 sourceSets {
    val main by getting
    val tlib by creating {
        compileClasspath  = main.output
        runtimeClasspath  = main.output
    }
    val test by getting {
        compileClasspath  = tlib.output
        runtimeClasspath  = tlib.output
    }
}

configurations {
    val tlibCompile by getting {
        extendsFrom(configurations["implementation"])
    }
}

publishing {
    publications {
        val tlibJar by tasks.registering(Jar::class) {
            from(sourceSets["tlib"].output)
        }

        val tlibSourcesJar by tasks.registering(Jar::class) {
            archiveClassifier.set("sources")
            from(sourceSets["tlib"].allSource)
        }

        register("mavenTLib", MavenPublication::class) {
            artifactId = "phg-entity-tlib"
            artifact(tlibJar.get())
            artifact(tlibSourcesJar.get())
        }
    }
}
  

Ответ №2:

Здесь у меня есть пример, к сожалению, он написан на Groovy, и я еще не знаком со способом Kotlin сделать это.
Может быть, это все еще помогает: https://github.com/thokari/gradle-workshop/blob/master/examples/09-multiple-artifacts/build.gradle
Вероятно, наиболее важная часть заключается в следующем:

 outputArchives.each { outputArchive ->
    String logicalName = outputArchive.camelCase()

    // Add archiving tasks.
    // These could be anything with type AbstractArchiveTask (e.g. War, Zip).
    task("${logicalName}Jar", type: Jar) { from configurations."${logicalName}Compile" }
    task("${logicalName}SourceJar", type: Jar) { from sourceSets."${logicalName}".java }

    // Configure the publishing extension added by the 'maven-publish' plugin.
    // For every combination of publication and repository, a task with name
    // publish<publicationName>PublicationTo<repositoryName>Repository is created.
    // The task 'publish' is a shortcut, depending on each one of them.
    publishing {
        publications {

            // Create a publication by calling its name and type.
            "${logicalName}"(MavenPublication) {

                // Override the artifact id, which defaults to the project name.
                artifactId = outputArchive.dashSeparated()

                // Publish the artifacts created by the archiving tasks.
                artifact tasks."${logicalName}Jar"
                artifact(tasks."${logicalName}SourceJar") { classifier 'source' }
            }
        }
    }
}
  

Я также так и не понял, как использовать эту SoftwareComponent концепцию. Я решил это, вызвав artifact метод для задач архивирования, которые я создал, вместо использования from(component) , я думаю, это также можно было бы сделать в Kotlin.