How to force gradle build the project before task execution?


I have the gradle task, but I want that gradle build the project before every time this task is executed. It sounds simple, but sorry, I didn’t find how to do it(

Depending on what you mean by “build the project”, it could be something like ‘myTask.dependsOn(build)’.

To build the project I use the following command: “gradle build”, and the project successfully builds. Which is default gradle task, I think. When I am trying myTask.dependsOn(build), I go the error that there is no task ‘buid’ in my project.

More details would help (e.g. whether your build is single project or multi project, what the concrete use case is, etc.), but try ‘myTask.dependsOn(“build”)’.

Lets consider that my project is just one file build.gradle and it looks like this:

apply plugin: 'java'
  task mysTask << {
 println "myTask"

I can call the following commands: “gradle build”; “gradle myTask”. The “gradle build” task creates jar with the name of the folder where the build.gradle lies.

I want that always I am calling “gradle myTask”, “gradle build” invoked automatically.

In this case, ‘myTask.dependsOn(build)’ will work, although you might want something more narrow such as ‘myTask.dependsOn(jar)’.

Thank you for you help Peter! I think, we not far from solving this trouble.

When I do as you recommended: everything works nice, but if I have the subproject:

apply plugin: 'java'
  task innerTask << {
 println "InnerTask"

and the root project:

task outerTask << {

and when I am calling the ‘outerTask’ the inner project isn’t build, it just prints “InnerTask”. If there is way to force the inner project task build the inner project, when I calling the inner task from the outer task?

‘TaskInternal#execute’ is an internal method that should never be called from user code (or bad things will happen). Instead, use ‘outerTask.dependsOn(":inner:innerTask")’.

Thanks, I changed outerTask.dependsOn(":inner:innerTask"), but nothing changed. Still the inner task is called and prints “InnerTask”, but it isn’t call build of the inner project.

It’s due to wrong usage of << above (task dependencies can’t be declared when the task is already running; I’d expect recent Gradle version to give an error here). I recommend to study the first several chapters of the Gradle User Guide.