Dynamically set Version for Maven publish


(Murple) #1

Hi,
I’m trying to set the version for maven publish dynamically based on the outcome of a task which takes the version from a file after increasing it.
Here is a build.gradle reduced to the core:

plugins {
    id "maven-publish"
}

import groovy.xml.*

task increaseVersion {
    doLast {
        def xml = new XmlSlurper().parse("${project.projectDir}/version.xml")
        def versionValueIdx = xml.application.childNodes().findIndexOf { it.text() == "Version" } + 1

        def currentVersionTag = xml.application.children()[versionValueIdx]

        def currentVersionParts = currentVersionTag.text().split("\\.")
        currentVersionParts[2] = currentVersionParts[2].toInteger() + 1
        def newVersion = currentVersionParts.join('.')
        currentVersionTag.replaceBody(newVersion)

        def writer = new FileWriter(fileName)
        XmlUtil.serialize(xml, writer)
        increaseVersion.ext.version = newVersion
    }
}

task createZip(type: Zip, dependsOn: increaseVersion) {
   from 'src/'
   include '*'
   include '*/*' 
   archiveName 'artefact.zip'
   destinationDir(file('build/'))
}

publishing {
    publications {
        Sample(MavenPublication) {
            groupId = 'net.Sample.project'
            artifactId = 'artefact'
            afterEvaluate {
                version = increaseVersion.version
            }

            artifact(file("${project.projectDir}/build/artefact.zip")) {
                builtBy createZip
            }
        }
    }
}

WiIth this, the version used for maven comes out as “unspecified”.

The problem seem to be that the version has not been increased and thus not set to the property of the task by the time the publish is evaluated.

Any hints what I should change to get this working?

thanks in advance
Mike


(Murple) #2

Found it :smiley:

After some search, I found that I can just do a
publishing.publications.Sample.version = newVersion

as the last statement of increaseVersion :slight_smile:

Maybe this will help someone at some point :wink:


(Chris Doré) #3

Bonus tip for you; Since the task creating the artifact is of type Zip, and therefore also of type AbstractArchiveTask, you can modify your publication such that you just need to call artifact( createZip ). The output file of the task will be published and the builtBy dependency will be automatically applied.