Create module-info.java during build


(Sverre Moe) #1

A project that has no source code, just Google Protobuf proto files.
The directory src/main/java is created during protobuf generation.
The classes are placed there under the package name defined in the proto files.

What is the best way to modularize this project?
The Automatic-Module-Name is set, but it would be best to have the produced JAR to be fully modularized.
This JAR is used in an API, which will also be modularized, this in turn is used by a GUI client, which will also be modularized. I control all three so I can modularize them in turn.

I was thinking one way of doing this was to automatically create the module-info.java after the source has been generated by protoc command. The file will no not be particular large, just one requires on com.google.protobuf. Unfortunately the Google Protobuf has not yet been modularized.

A gradle task to generate this content to src/main/java/module-info.java, prior to compileJava.

module com.company.protobuf {
    requires com.google.protobuf;
}

This is what I ended up with when generating the Protobuf library.

task protobuf(type: Exec) {
    final def javaDir = "src/main/java"
    final def javaFile = "module-info.java"
    final def protoDir = "${projectDir}/server/protobuf"
    final def protoPaths = fileTree(dir: protoDir, include: '**/*.proto')
    final def protoFiles = protoPaths.each { it }.join(' ')

    doFirst {
        mkdir javaDir
        new File("${javaDir}/${javaFile}").text = """
module com.company.protobuf {
    requires com.google.protobuf;
}
"""
    }

    commandLine "protoc --proto_path=. --proto_path=/usr/include --java_out=${javaDir} -I${protoDir} ${protoFiles}".split(' ')
}

tasks.compileJava.dependsOn("protobuf")