How to execute gradle task

1.8k Views Asked by At

I wanted to execute gradle task from my plugin code.

Any one can suggest me, how can I programmatically execute gradle task from code.

Thanks, Sumeet.

2

There are 2 best solutions below

1
On

The answer provided by Martin Linha does not work anymore with recent versions of Gradle, for instance Gradle 7. The Task class does not have an execute method anymore. Instead, the activities have to be executed. In addition, you might want to execute the dependencies as well:

void executeTask(Task task) {
    task.taskDependencies.getDependencies(task).each {
       subTask -> executeTask(subTask)
    }
    task.actions.each { it.execute(task) }
}

Note that this is still a hack and not guaranteed to work.

20
On

You can do it as follows

task a {
  doLast {
    println 'test'
  }
}

task b {
    doLast {
        a.execute()
    }
}

So in plugin code it might be something similar to

project.tasks.<taskname>.execute()

But this might be changed in the future. You should rely on the chaining of the tasks rather then invoking them directly.