neoeinstein / protoc-gen-prost

Apache License 2.0
150 stars 42 forks source link

Provide example with well-known-types #28

Open tatemz opened 2 years ago

tatemz commented 2 years ago

I am having trouble using google.protobuf.Timestamp in my project. Is there documentation or an example showing how to configure my project to properly handle this protobuf type?

ben-xD commented 2 years ago

Have you just tried installing prost-typesinstead of using the compile_well_known_types option?

This is based on my understanding of compile_well_known_types (docs):

Configures the code generator to not use the prost_types crate for Protobuf well-known types, and instead generate Protobuf well-known types from their .proto definitions.

bonitao commented 1 year ago

Here is a working example with well know protos, common protos and bufbuild:

// myproto.proto
syntax = "proto3";

package myproto;

import "google/protobuf/timestamp.proto";
import "google/type/money.proto";

message MyMessage {
  .google.protobuf.Timestamp ts = 4;
  .google.type.Money price = 7;
}
// build.rs
use std::error::Error;
use std::process::{exit, Command};

fn main() -> Result<(), Box<dyn Error>> {
    let buf = std::env::var("BUF_BINARY").unwrap_or("buf".to_string());
    let status = Command::new(buf)
        .arg("generate").arg("--template").arg("buf.gen.yaml")
        .arg("--include-imports").arg("--include-wkt")
        .current_dir(env!("CARGO_MANIFEST_DIR"))
        .status()
        .unwrap();

    if !status.success() {
        exit(status.code().unwrap_or(-1))
    }
    println!("cargo:rerun-if-changed=myproto.proto");
    println!("cargo:rerun-if-changed=buf.gen.yaml");
    Ok(())
}
# buf.gen.yaml
version: v1
managed:
  enabled: true
plugins:
  - plugin: buf.build/community/neoeinstein-prost:v0.2.3
    out: target/bufbuild/src
    opt:
      - bytes=.
      - compile_well_known_types
      - file_descriptor_set
// lib.rs
// Manually include all generated protos. Can be replaced by crate from
// https://github.com/neoeinstein/protoc-gen-prost/blob/main/protoc-gen-prost-crate/README.md
// but we avoid it for now to keep protoc dependencies away.
pub mod google {
    pub mod protobuf {
      include!(concat!(env!("CARGO_MANIFEST_DIR"), "/target/bufbuild/src/google.protobuf.rs"));
    }
    pub mod r#type {
      include!(concat!(env!("CARGO_MANIFEST_DIR"), "/target/bufbuild/src/google.type.rs"));
    }
}
pub mod myproto {
    include!(concat!(env!("CARGO_MANIFEST_DIR"), "/target/bufbuild/src/myproto.rs"));
}