elset george
elset george

Reputation: 53

Gradle custom task extends Exec is throwing error

My intention is to run a docker save command by creating a custom task in Gradle:

Below is my build.gradle file:

class SaveTask extends Exec {
    @TaskAction
    void saveImage() {
        commandLine "bash","-c","docker save someimage:latest | gzip > someimage.tar.gz"
    }
}

// Create a task using the task type
task save(type: SaveTask)

When I run the task it is giving me the below error:

Execution failed for task ':save'.
> execCommand == null!

Can someone suggest me where I am going wrong?

Upvotes: 1

Views: 726

Answers (2)

elset george
elset george

Reputation: 53

I modified the above code as below and it's working for me

class SaveTask extends Exec {
     

    SaveTask() {

            commandLine "bash", "-c", "someimage:latest | gzip > someimage.tar.gz"

    }
}

task saveImageA(type: SaveTask)

Upvotes: 0

Lukas Körfer
Lukas Körfer

Reputation: 14503

You probably don't need to create a custom task type at all, just use the regular Exec task type for your task save:

task save(type: Exec) {
    commandLine "bash", "-c", "docker save someimage:latest | gzip > someimage.tar.gz"
}

The problem why your approach fails is that the Exec task type defines a @TaskAction internally. This @TaskAction runs the command defined by commandLine. In your SaveTask task type, another @TaskAction is defined, but it will run after the original @TaskAction. This is the reason why the commandLine is still null / empty for the original @TaskAction.

If you still want to create a custom task type, e.g. because you want to define a configuration interface that will be used by multiple tasks, use a doFirst closure to define the commandLine, as it will be executed before any task action:

class SaveTask extends Exec {
    String image

    SaveTask() {
        doFirst {
            commandLine "bash", "-c", "docker save ${image} | gzip > someimage.tar.gz"
        }
    }
}

task saveImageA(type: SaveTask) {
    image = 'imageA:latest'
}

task saveImageB(type: SaveTask) {
    image = 'imageB:latest'
}

Upvotes: 2

Related Questions