pepuch
pepuch

Reputation: 6516

Gradle - publish artifacts

I want to publish artifacts to ivy repository but it doesn't work. I read this article and after read created this sample build:

task ivyPublishTest << {
    def buildDir = new File("build")
    buildDir.mkdirs()
    def fileToPublish = new File("build/file.abc")
    fileToPublish.write("asdasdasd")
}

artifacts {
    archives(ivyPublishTest.fileToPublish) {
        name 'gradle-test-artifact'
        builtBy ivyPublishTest
    }
}

uploadArchives {
    repositories {
        ivy {
            url "http://my.ivy.repo/ivyrep/shared"
        }
    }
}

Of course the problem is that it doesn't work. I get this error Could not find property 'fileToPublish' on task ':ivyPublishTest'

Upvotes: 1

Views: 1638

Answers (1)

Peter Niederwieser
Peter Niederwieser

Reputation: 123890

In Groovy, def creates a local variable, which is lexically scoped. Therefore, fileToPublish is not visible outside the task action. Additionally, configuration has to be done in the configuration phase (i.e. the declaration and assignment of fileToPublish in your task action would come too late). Here is a correct solution:

task ivyPublishTest {
    // configuration (always evaluated)
    def buildDir = new File("build")
    ext.fileToPublish = new File("build/file.abc")
    doLast {
        // execution (only evaluated if and when the task executes)
        buildDir.mkdirs()
        fileToPublish.write("asdasdasd")
    }
}

artifacts {
    // configuration (always evaluated)
    archives(ivyPublishTest.fileToPublish) {
        name 'gradle-test-artifact'
        builtBy ivyPublishTest
    }
}

ext.fileToPublish = ... declares an extra property, a new property attached to an existing object that's visible everywhere the object (task in this case) is visible. You can read more about extra properties here in the Gradle User Guide.

Upvotes: 1

Related Questions