use std::error::Error;
#[cfg(feature = "generate-protobuf")]
use std::{
env, fs,
path::{Path, PathBuf},
};
#[cfg(feature = "generate-protobuf")]
const HEADER: &str = "// Copyright 2023-Present Datadog, Inc. https://www.datadoghq.com/
// SPDX-License-Identifier: Apache-2.0
";
fn main() -> Result<(), Box<dyn Error>> {
#[cfg(feature = "generate-protobuf")]
{
unsafe {
std::env::set_var("PROTOC", protoc_bin_vendored::protoc_bin_path().unwrap());
}
let mut config = prost_build::Config::new();
let staging_dir = PathBuf::from(env::var("OUT_DIR")?);
config.out_dir(&staging_dir);
println!("cargo:rerun-if-changed=src/pb/DDSketch.proto");
config.compile_protos(&["src/pb/DDSketch.proto"], &["src/"])?;
let generated = [
HEADER.as_bytes(),
fs::read(staging_dir.join("pb.rs"))?.as_slice(),
]
.concat();
let dest = Path::new(&env::var("CARGO_MANIFEST_DIR")?)
.join("src")
.join("pb.rs");
write_if_changed(&dest, &generated)?;
}
#[cfg(not(feature = "generate-protobuf"))]
{
println!("cargo:rerun-if-changed=build.rs");
}
Ok(())
}
#[cfg(feature = "generate-protobuf")]
fn write_if_changed(dest: &Path, contents: &[u8]) -> Result<(), Box<dyn Error>> {
if fs::read(dest)
.map(|existing| strip_cr(&existing) == strip_cr(contents))
.unwrap_or(false)
{
return Ok(());
}
fs::write(dest, contents)?;
Ok(())
}
#[cfg(feature = "generate-protobuf")]
fn strip_cr(bytes: &[u8]) -> Vec<u8> {
bytes.iter().copied().filter(|&b| b != b'\r').collect()
}