Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate codes using prost in rust?

I don't know how to generate codes using prost_build

I have read the documents, but they don't give a detailed command of generating code. I type cargo build but no codes are generated.

my build.rs

extern crate prost_build;
fn main() {
    prost_build::compile_protos(&["src/items.proto"],
                                &["src/"]).unwrap();
}

my Cargo.toml

[package]
name = "snazzy"
version = "0.1.0"
authors = ["xxx <[email protected]>"]
edition = "2018"
build = "build.rs"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
bytes = "0.4"
prost = "0.5"

[build-dependencies]
prost-build = { version = "0.4"  }

my items.proto

syntax = "proto3";

package snazzy.items;

message Shirt {
    enum Size {
        SMALL = 0;
        MEDIUM = 1;
        LARGE = 2;
    }
    string color = 1;
    Size size = 2;
}

my file tree:

.
├── build.rs
├── Cargo.lock
├── Cargo.toml
└── src
    ├── items.proto
    └── main.rs

No build error but I can't see where the generated codes are. Any help will be appreciated!

like image 271
jl0x61 Avatar asked Sep 21 '19 12:09

jl0x61


1 Answers

You're right, this isn't very well explained in the docs, and this is because of the way build scripts work. Well, partly.

Your protobuf implementations are under target/{yourArch}/build/{yourCrateName}-{hash}/out.

This would be extremely hard to get to if it wasn't for environment variables. The important part of the documentation is the following snippet of code highlights the inclusion:

pub mod items {
    include!(concat!(env!("OUT_DIR"), "/snazzy.items.rs"));
}

This includes the file available at OUT_DIR (the directory specified above, filled in automatically during compilation) and the name of the protobuf implementation (your package name in the protobuf file), and makes all its content structs available under crate::items.

It makes sense for the files to reside in the build directory, as they are a build artefact. Code generation in the src folder of your crate would lead to chaos, both when it comes to version control and project sanity (you'd have a duplication of information, and the protobuf implementation, provided that it is sane, isn't that important to you. The functional blueprint is, however).

like image 82
Sébastien Renauld Avatar answered Oct 23 '22 14:10

Sébastien Renauld