simple protobuf compilation with gradle

前端 未结 1 887
半阙折子戏
半阙折子戏 2021-01-31 18:23

If you\'re looking for sample gradle protobuf project look here.

I\'m having hard time with gradle and protobuf, i want to create a simple gradle project that will take

1条回答
  •  清酒与你
    2021-01-31 18:46

    If I don't misunderstand your question it's quite simple to solve. If you don't want to distinguish between your own and the generated sources you just have to add set the generatedFileBaseDir like this generateProtoTasks.generatedFilesBaseDir = 'src'

    So the entire build file looks like:

    // ...
    
    protobuf {
    // Configure the protoc executable
    protoc {
        // Download from repositories
        artifact = 'com.google.protobuf:protoc:3.0.0-alpha-3'
    }
    
    generateProtoTasks.generatedFilesBaseDir = 'src' // <- that line 
    
    generateProtoTasks {
        // all() returns the collection of all protoc tasks
        all().each { task ->
            // Here you can configure the task
        }
    

    Than your folder looks like:

    • src/main/java/com/vach/tryout/AddressBookProtos.java
    • src/main/java/com/vach/tryout/protobuf/Main.java

    BUT: That might not be the best idea to mix generate with handcrafted source code. So my suggestion would be to generate the source code into an own directory like generatedSources and add this directory to the java sourceSet. The build file would look like this:

    sourceSets {
        main {
            proto {
                srcDir 'src/main/proto'
            }
            java {
                // include self written and generated code
                srcDirs 'src/main/java', 'generated-sources/main/java'            
            }
        }
        // remove the test configuration - at least in your example you don't have a special test proto file
    }
    
    protobuf {
        // Configure the protoc executable
        protoc {
            // Download from repositories
            artifact = 'com.google.protobuf:protoc:3.0.0-alpha-3'
        }
    
        generateProtoTasks.generatedFilesBaseDir = 'generated-sources'
    
        generateProtoTasks {
            // all() returns the collection of all protoc tasks
            all().each { task ->
                // Here you can configure the task
            }
    
            // In addition to all(), you may get the task collection by various
            // criteria:
    
            // (Java only) returns tasks for a sourceSet
            ofSourceSet('main')
    
        }   
    }
    

    Your directory will look like this

    • src/main/proto/dtos.proto
    • src/main/java/com/vach/tryout/protobuf/Main.java
    • generated-sources/main/java/com/vach/tryout/AddressBookProtos.java

    A nice side effect is that you can ignore this generated-sources dir in your git configuration. That's always a good idea not to publish generated source code.

    0 讨论(0)
提交回复
热议问题