5

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'
  }
}
Tiensi
  • 227
  • 3
  • 11

2 Answers2

5

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
stuckj
  • 977
  • 1
  • 13
  • 24
2

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.

muru
  • 4,723
  • 1
  • 34
  • 78
Tiensi
  • 227
  • 3
  • 11