tschumann
tschumann

Reputation: 3256

Gradle task lines always getting executed

I have the following Gradle task:

task deploy(type: Exec) {
    doFirst {
        println 'Performing deployment'
    }

    final Map properties = project.getProperties()

    if (!properties['tag']) {
        throw new StopExecutionException("Need to pass a tag parameter")
    }

    commandLine "command", tag
}

If I run another task I get an error because properties['tag'] is undefined, I guess because Gradle is executing everything in the task except commandLine. Is there a better way to do this or a way to stop Gradle from executing parts of the task even when I'm running another task?

Using Gradle 6.6.1

Upvotes: 1

Views: 128

Answers (1)

Bjørn Vester
Bjørn Vester

Reputation: 7598

I use this pattern:

// Groovy DSL
tasks.register("exec1", Exec) {
    def tag = project.findProperty("tag") ?: ""
    commandLine "echo", tag

    doFirst {
        if (!tag) {
            throw new GradleException("Need to pass a tag parameter")
        }
    }
}

It adds the tag property if it exists.

If it does not exist, it adds an empty string but checks for this before it actually runs.

It would be great if the Exec task accepted providers as arguments so you could just give it providers.gradleProperty("tag"), but unfortunately it doesn't.

Upvotes: 1

Related Questions