What's the most appropriate way to reuse the Exec task in gradle for common command line operations?
gradle, plugins
Solution
To see which method is executed for a task you can check the sources of `Exec` and search for a method marked with `@TaskAction`. It turns out that it's the `exec()` method but in general you don't want to be calling task actions manually but let Gradle do it for you. The best idea in my opinion is to add methods/setters to your custom tasks. It might look like that:
task addUser(type: AddUser) {
username = 'fromGradle'
}
class SudoExec extends Exec {
void sudoCommand(Object... arguments) {
executable 'sudo'
args = arguments.toList()
}
}
class AddUser extends SudoExec {
void setUsername(String username) {
sudoCommand('useradd', username)
}
}
Problem
I'm writing a gradle build file that will install a basic development domain for our product. Essentially all of the real code is going to be in custom plugins and custom tasks. Several of the steps involved are fairly repetitive (multiple sudo calls, multiple user adds) and I would like to encapsulate the common stuff into a task. For example: ``` task('addDBUser', type:AddUser) { username = joeUser } task('startService', type:SudoExec) { workingDir = "not/too/relevant" commandLine = "/etc/init.d/coolService start" } ``` I'd like to reuse the various functionality that Exec gets me (stdin, stdout, etc.) as tidily as possible, while supplying the boilerplate ("sudo ...") automatically. I'm pretty sure I can just extend Exec instead of DefaultTask, but I don't know a standard way of triggering actual action. It seems easy to modify the commandLine property with what I need, but there's no generic "run()" or the like to use when I want Exec to actually go. Do I open up Exec to identify which method is it's work method and then invoke it directly? Or is there a more generic way of accomplishing my goal?