1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
use sha2::{Digest, Sha256};
use std::{
    collections::HashMap,
    fmt::Display,
    fs,
    fs::File,
    io,
    path::{Path, PathBuf},
    process::Command,
};

/// Runs rustfmt on the generated files - this is lifted from tonic-build
fn fmt<P>(out_dir: P)
where P: AsRef<Path> + Display {
    let dir = walk_files(&out_dir.as_ref().to_path_buf(), "rs");

    for entry in dir {
        let out = Command::new("rustfmt")
            .arg("--emit")
            .arg("files")
            .arg("--edition")
            .arg("2018")
            .arg(entry.to_str().unwrap())
            .output()
            .unwrap();

        if !out.status.success() {
            panic!("status: {} - {}", out.status, String::from_utf8_lossy(&out.stderr));
        }
    }
}

fn walk_files<P: AsRef<Path>>(search_path: P, search_ext: &str) -> Vec<PathBuf> {
    let mut protos = Vec::new();
    let paths_iter = search_path
        .as_ref()
        .read_dir()
        .unwrap()
        .filter_map(Result::ok)
        .map(|dir| dir.path());

    for path in paths_iter {
        if path.is_file() && path.extension().filter(|ext| ext == &search_ext).is_some() {
            protos.push(path)
        } else if path.is_dir() {
            protos.extend(walk_files(&path, search_ext));
        }
    }

    protos
}

pub struct ProtoCompiler {
    out_dir: Option<PathBuf>,
    type_attributes: HashMap<&'static str, &'static str>,
    field_attributes: HashMap<&'static str, &'static str>,
    proto_paths: Vec<PathBuf>,
    include_paths: Vec<PathBuf>,
}

impl ProtoCompiler {
    pub fn new() -> Self {
        Self {
            out_dir: None,
            type_attributes: HashMap::new(),
            field_attributes: HashMap::new(),
            proto_paths: Vec::new(),
            include_paths: Vec::new(),
        }
    }

    pub fn out_dir<P>(&mut self, out_dir: P) -> &mut Self
    where P: AsRef<Path> {
        self.out_dir = Some(out_dir.as_ref().to_path_buf());
        self
    }

    pub fn add_type_attribute(&mut self, path: &'static str, attr: &'static str) -> &mut Self {
        self.type_attributes.insert(path, attr);
        self
    }

    pub fn add_field_attribute(&mut self, path: &'static str, attr: &'static str) -> &mut Self {
        self.field_attributes.insert(path, attr);
        self
    }

    pub fn proto_paths<P: AsRef<Path>>(&mut self, proto_paths: &[P]) -> &mut Self {
        self.proto_paths
            .extend(proto_paths.into_iter().map(|p| p.as_ref().to_path_buf()));
        self
    }

    pub fn include_paths<P: AsRef<Path>>(&mut self, include_paths: &[P]) -> &mut Self {
        self.include_paths
            .extend(include_paths.into_iter().map(|p| p.as_ref().to_path_buf()));
        self
    }

    fn hash_file_contents<P: AsRef<Path>>(&self, file_path: P) -> Result<Vec<u8>, String> {
        let mut file = File::open(file_path).unwrap();
        let mut file_hash = Sha256::default();
        io::copy(&mut file, &mut file_hash).map_err(|err| format!("Failed to hash file: '{}'", err))?;
        Ok(file_hash.result().to_vec())
    }

    fn compare_and_move<P: AsRef<Path>>(&self, tmp_out_dir: P, out_dir: P) {
        let tmp_files = walk_files(tmp_out_dir, "rs");
        for tmp_file in tmp_files {
            let target_file = out_dir.as_ref().join(tmp_file.file_name().unwrap());
            if target_file.exists() {
                let tmp_hash = self.hash_file_contents(&tmp_file).unwrap();
                let target_hash = self.hash_file_contents(&target_file).unwrap();
                if tmp_hash != target_hash {
                    fs::rename(tmp_file, target_file).unwrap();
                }
            } else {
                fs::rename(tmp_file, target_file).unwrap();
            }
        }
    }

    pub fn compile(&mut self) -> Result<(), String> {
        if self.proto_paths.is_empty() {
            return Err("proto_path not specified".to_string());
        }

        self.include_paths.extend(self.proto_paths.clone());

        let protos = self.proto_paths.iter().fold(Vec::new(), |mut protos, path| {
            protos.extend(walk_files(&path, "proto"));
            protos
        });

        let mut config = prost_build::Config::new();

        for (k, v) in &self.type_attributes {
            config.type_attribute(k, v);
        }

        for (k, v) in &self.field_attributes {
            config.field_attribute(k, v);
        }

        let out_dir = self
            .out_dir
            .take()
            .unwrap_or_else(|| PathBuf::from(std::env::var("OUT_DIR").unwrap()));

        let tmp_out_dir = PathBuf::from(std::env::var("OUT_DIR").unwrap()).join("tmp_protos");
        fs::create_dir_all(&tmp_out_dir)
            .map_err(|err| format!("Failed to create temporary out dir because '{}'", err))?;

        config.out_dir(tmp_out_dir.clone());

        config.compile_protos(&protos, &self.include_paths).map_err(|err| {
            // Side effect - print the error to stderr
            eprintln!("\n{}", err);
            format!("{}", err)
        })?;

        fmt(tmp_out_dir.to_str().expect("out_dir must be utf8"));

        self.compare_and_move(&tmp_out_dir, &out_dir);

        fs::remove_dir_all(&tmp_out_dir).map_err(|err| format!("Failed to remove temporary dir: {}", err))?;

        Ok(())
    }
}