Diwakar Bhatt
Diwakar Bhatt

Reputation: 515

how to execute 'gradle build' command from gradle.build script

I want to execute a gradle build command from build.gradle file.

build.gradle file

apply plugin: 'java'
apply plugin: 'application'
task me{
   //Can we perform gradle build command here.
       }

Question: Can we perform gradle build command inside task me, similarly like we do from command prompt(screenshot attached)..?

Note : I am using windows env, please assume I am providing all other statements in build.gradle file. I am able to build from command prompt by executing

gradle build file.

I want to execute this task me from command prompt and it should be responsible to call gradle build command.(attached screenshot)

enter image description here

Upvotes: 6

Views: 17387

Answers (3)

Skillter
Skillter

Reputation: 71

What approach I used was directly executing a Gradle console command. I prefer it because it's more versatile. You can do so like this:

task me{
    var command = "\"" + System.getProperty("user.dir") + "\\gradlew.bat\" build"
    command.execute()
}

Another way is to use finalizedBy() method, which will execute specific task after the first one finishes. You can use it like this:

task me{
}
me.finalizedBy(build)

Upvotes: 0

Patrik Schalin
Patrik Schalin

Reputation: 86

Yes, if you make the task me to a task of type GradleBuild

https://docs.gradle.org/current/dsl/org.gradle.api.tasks.GradleBuild.html

E.g.

task me(type: GradleBuild){
    buildFile 'mybuild.gradle' //defaults to build.gradle so not needed
    dir 'someDir'
    tasks 'clean', 'build'
}

Upvotes: 4

Vampire
Vampire

Reputation: 38734

You cannot "call" a Gradle task in a Gradle build.

You might stumble upon the method execute() that each Gradle task has, but this is a purely internal method that must not be used by any build script. Using it will not work properly. It will not ensure the task is run only once, it will not ensure dependency tasks are run before and so on and so on, just don't use it.

Your code snippet is too big for me wanting to interpret it right now to understand what you want to do exactly, but if you want to "call" a Gradle task from another Gradle task, your logic is bogus and should be changed. If you want to run a Gradle task before or after another Gradle task is run, the only supported way is to use dependsOn (before) or finalizedBy (after) and you can not set these properties during execution phase of a task but only during configuration phase.

Well, there is one other way to call a Gradle task from a build script, but this is by using a task of type GradleBuild which would start a complete new and separate build of the project you specify which is most often not the action you really want to do.

Upvotes: 2

Related Questions