George Karanikas
George Karanikas

Reputation: 1244

Gradle compile generated java file

I'm trying to convert a big project to use gradle from the current state which uses makefiles.

I have hit a wall though at some point. Suppose we have the following directory tree (a lot of stuff omitted for simplicity):

root
|-- src
|    +-- main
|         +-- java
|              +-- com
|                  +-- app
|                      |-- a
|                      |-- b
|                      +-- c
+-- build.gradle

Now lets suppose that in package com.app.c exists a java file with a main class which is being used to generate a new java file under the same directory which then should be compiled as well. Package com.app.c has dependencies on the other packages as well.

With a makefile you can do something like the following (a simple algorithm):

  1. Compile packages `com.app.a` and `com.app.c`.
  2. Move to the directory of package `com.app.b` and compile only the files required to create the generated file.
  3. Create the generated file by running the main function in the file used for generation.
  4. Compile the whole `com.app.b` package which now includes the generated file.

Using gradle though I cannot do something like that (or at least I don't think I can).

What I thought of doing was create a JavaExec task that will run the file that produces the generated java file and make it run after compileJava and also finalized with compileJava. But obviously that is a circular dependency between the tasks and a dead end.

Has anyone ever done or met something similar? If anyone could help I would appreciate it.

Note that I cannot easily move the file generation out of that file as it has some deep dependencies...

Upvotes: 3

Views: 2316

Answers (1)

George Karanikas
George Karanikas

Reputation: 1244

It looks like I didn't search that good.

Using this solution works in this case as well.

The difference is that you have to have the following configuration:

task generateFile(type: JavaExec) { ... }

task compileGeneratedFile(type: JavaCompile) { ... }

generateFile.mustRunAfter compileJava
generateFile.finalizedBy compileGeneratedFile
generateFile.onlyIf { !file("path/to/file").exists() }

This seems to do the trick! Just posting the answer so that anyone with the same issue would find it easier.

Upvotes: 2

Related Questions