Home > database >  accessing fields from non-root project in gradle
accessing fields from non-root project in gradle

Time:01-10

this seems like it should be very simple, but I'm stuck! I have a gradle task that zips some files and creates an archive. I want to suffix the name of the archive with the version string from the project I'm in (this is a subproject in a multi-project build)

there's another task in this same build.gradle file that accesses this version field, that I want to access too. it looks like this:

task releasePublishAuto(dependsOn: [tasks.cppApiVersion, rootProject.tasks.releasePublish]) {
    doLast {
        println("############################################################")
        println("# PUBLISHED CPP API WITH VERSION: $version")
        println("############################################################")
    }
}

you can see it accessing the version variable and printing it using $version. it prints something like # PUBLISHED CPP API WITH VERSION: 1.256.4-SNAPSHOT

now, my task is a zipping task, so it's a bit different:

task zipGeneratedCppClientApi(type: Zip, group: "code generator", dependsOn: [tasks.cppApiVersion, "generateCormorantCPP"]) {
    from(fileTree(dir: "$buildDir/generated/cormorant_cpp", include: "**/*"))
    archiveFileName = "$buildDir/distributions/generated-cpp-api-$version"
}

I would expect this to create a zipfile named generated-cpp-api-1.256.4-SNAPSHOT but instead i get one named generated-cpp-api-null. As far as I can tell this is because in the context of my zipping task, version refers to the version of the zipping library (or somesuch), not the version of the current project. I've tried instead accessing rootproject.version but that's also null - this isn't the root project but a subproject thereof!

How can I access the version field in this non-root project in gradle?

to clarify: if I remove type:zip from my task, version points to the correct value, but without type:zip it doesnt create a zipfile and so isnt very helpful.

CodePudding user response:

In the context of a Zip task, the version property refers to the AbstractArchiveTask.version property, as you have somehow guessed, and not to the current project version property. As you can see, this version property has been deprecated on AbstractArchiveTask class, maybe to avoid such confusion.

To use project version instead, simply use ${project.version} as in following example.

in your subproject build script:

version="1.0.0"
tasks.register('packageDistribution', Zip) {
    println("version from AbstractArchiveTask : $version") // => here, version will be null
    println("version from project: ${project.version}")   //  => here, version will be "1.0.0" as expected
    archiveFileName = "my-distribution-${project.version}.zip"  // => my-distribution-1.0.0.zip  as expected
    destinationDirectory = layout.buildDirectory.dir('dist')

    from layout.projectDirectory.dir("src/dist")
}
  • Related