Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate Protobuf java files with Square's Wire

I'm trying to generate .java files from the .proto files I have stored under my SRC folder in Android studio. I put the below code in my gradle file by it doesn't seem to work

apply plugin: 'com.squareup.wire'

buildscript {
  repositories {
    mavenCentral()
  }
  dependencies {
    classpath 'com.squareup.wire:wire-maven-plugin:2.1.1'
  }
}
like image 408
Tiensi Avatar asked Mar 14 '23 01:03

Tiensi


2 Answers

So instead of using a gradle plugin I just ended up using the square wire compiler jar. Here are the steps.

  1. Download compiler-jar-with-dependencies from http://search.maven.org/#artifactdetails%7Ccom.squareup.wire%7Cwire-compiler%7C2.1.1%7Cjar
  2. Put jar file into root directory of android app
  3. Go to the directory and paste this command

    java -jar wire-compiler-2.1.1-jar-with-dependencies.jar --proto_path=directory-of-protofile --java_out=app/src/main/java/ name-of-file.proto
    

Should work. Make sure to replace the directory-of-protofile and name-of-file with whatever you have.

like image 20
Tiensi Avatar answered Mar 15 '23 15:03

Tiensi


There is a gradle plugin for wire here: https://github.com/square/wire-gradle-plugin. However, it seems like it's not quite ready for primetime yet. I had some trouble getting it working.

But, here's a way to do it that automates generation of java code from the *.proto files using the wire compiler directly and a simple gradle task. I've provided a snippet below with the modifications to your build.gradle. Change the protoPath and wireGeneratedPath based on your source layout.

def protoPath = 'src/proto'
def wireGeneratedPath = 'build/generated/source/wire'

buildscript {
    repositories {
        mavenCentral()
    }

    dependencies {
        classpath 'com.squareup.wire:wire-compiler:2.2.0'
    }
}

android {
    sourceSets {
        main {
            java {
                include wireGeneratedPath
            }
        }
    }
}

dependencies {
    compile 'com.squareup.wire:wire-runtime:2.2.0'
    // Leave this out if you're not doing integration testing...
    androidTestCompile 'com.squareup.wire:wire-runtime:2.2.0'
}

// This handles the protocol buffer generation with wire
task generateWireClasses {
    description = 'Generate Java classes from protocol buffer (.proto) schema files for use with squareup\'s wire library'
    delete(wireGeneratedPath)
    fileTree(dir: protoPath, include: '**/*.proto').each { File file ->
        doLast {
            javaexec {
                main = 'com.squareup.wire.WireCompiler'
                classpath = buildscript.configurations.classpath
                args = ["--proto_path=${protoPath}", "--java_out=${wireGeneratedPath}", "${file}"]
            }
        }
    }
}

preBuild.dependsOn generateWireClasses
like image 158
stuckj Avatar answered Mar 15 '23 13:03

stuckj