jotty/proto/
utils.rs

1use prost_build;
2use prost_build::Config;
3use walkdir::WalkDir;
4
5use crate::proto::ServiceTraitGenerator;
6use crate::HandlerResult;
7use std::ffi::OsStr;
8use std::path::PathBuf;
9use std::str::FromStr;
10
11/// Build all protobuf files in `search` directory. `include` needs to contain the search directory.
12/// If `search` is __src/proto__, then `include` will need to be __src__
13pub fn build_directory(search: &str, include: &str) {
14    let mut files = vec![];
15    for entry in WalkDir::new(search) {
16        let path = entry.unwrap().path().to_path_buf();
17        let ext = path.extension().and_then(OsStr::to_str);
18        if ext.is_some() && ext.unwrap() == "proto" {
19            files.push(path);
20        }
21    }
22
23    Config::new()
24        .protoc_arg("--experimental_allow_proto3_optional")
25        .service_generator(Box::new(ServiceTraitGenerator))
26        .type_attribute(".", "#[derive(Serialize, Deserialize)]")
27        .compile_protos(&*files, &[PathBuf::from_str(include).unwrap()])
28        .unwrap();
29}
30
31pub fn handle_result<T: prost::Message + serde::Serialize>(
32    message: crate::Result<T>,
33) -> HandlerResult {
34    fn err(error: anyhow::Error) -> HandlerResult {
35        HandlerResult::Failure(serde_json::Value::String(format!("{:?}", error)))
36    }
37    match message {
38        Ok(message) => match serde_json::to_value(message) {
39            Ok(value) => HandlerResult::Success(value),
40            Err(error) => err(error.into()),
41        },
42        Err(error) => err(error),
43    }
44}