protobuf_gen/
main.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5use clap::{App, Arg};
6use serde_derive::Deserialize;
7use std::{collections::HashMap, fs, path::PathBuf};
8
9#[derive(Deserialize, Debug)]
10struct ProtobufOpts {
11    dir: String,
12    out_dir: Option<String>,
13}
14
15fn main() {
16    let matches = App::new("Protobuf files generator")
17        .about("Generates Rust structs from protobuf files in the repository.")
18        .arg(
19            Arg::with_name("PROTOBUF_CONFIG")
20                .help("Absolute path to the protobuf configuration file.")
21                .required(true),
22        )
23        .get_matches();
24    let config_path = matches.value_of("PROTOBUF_CONFIG").unwrap();
25    let config_path = PathBuf::from(config_path);
26    let files_config = fs::read_to_string(&config_path).expect("unable to read protobuf_files");
27    let files: HashMap<String, ProtobufOpts> = toml::from_str(&files_config).unwrap();
28    let config_dir = config_path.parent().unwrap();
29
30    for (proto_file, opts) in files {
31        // Can't re-use Config because the out_dir is always different.
32        let mut config = prost_build::Config::new();
33        let out_dir = opts.out_dir.clone().unwrap_or_else(|| opts.dir.clone());
34        let out_dir_absolute = config_dir.join(out_dir).canonicalize().unwrap();
35        let out_dir_absolute = out_dir_absolute.to_str().unwrap();
36        let proto_path_absolute = config_dir
37            .join(&opts.dir)
38            .join(proto_file)
39            .canonicalize()
40            .unwrap();
41        let proto_path_absolute = proto_path_absolute.to_str().unwrap();
42        let include_dir_absolute = config_dir.join(&opts.dir).canonicalize().unwrap();
43        let include_dir_absolute = include_dir_absolute.to_str().unwrap();
44        config.out_dir(out_dir_absolute);
45        config
46            .compile_protos(&[proto_path_absolute], &[&include_dir_absolute])
47            .unwrap();
48    }
49}