crosvm/protos/build.rs

79 lines
2.4 KiB
Rust
Raw Normal View History

// Copyright 2019 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use std::env;
use std::error::Error;
use std::fs::File;
use std::io::Write;
use std::path::PathBuf;
type Result<T> = std::result::Result<T, Box<dyn Error>>;
struct Proto {
// Where to find protos during builds within cros_sdk. Relative to $SYSROOT
// environment variable set by emerge builds.
dir_relative_to_sysroot: &'static str,
// Where to find protos during "cargo build" in a local developer
// environment. Relative to the platform/crosvm/protos directory.
dir_relative_to_us: &'static str,
// *.proto file expected to exist in both of the above directories.
proto_file_name: &'static str,
// Code generated by proto compiler will be exported under
// protos::$module_name.
name_for_module: &'static str,
}
static PROTOS: &[Proto] = &[Proto {
dir_relative_to_sysroot: "usr/include/chromeos/dbus/trunks",
dir_relative_to_us: "../../../platform2/trunks",
proto_file_name: "interface.proto",
name_for_module: "trunks",
}];
fn paths_to_strs(paths: &[PathBuf]) -> Vec<&str> {
paths
.iter()
.map(|p| p.as_os_str().to_str().unwrap())
.collect()
}
fn main() -> Result<()> {
let out_dir = env::var("OUT_DIR")?;
let sysroot = env::var_os("SYSROOT");
// Write out a Rust module that imports the modules generated by protoc.
let protos_rs = PathBuf::from(&out_dir).join("protos.rs");
let mut out = File::create(protos_rs)?;
let mut input_files = Vec::new();
let mut include_dirs = Vec::new();
for proto in PROTOS {
let dir = match &sysroot {
Some(dir) => PathBuf::from(dir).join(proto.dir_relative_to_sysroot),
None => PathBuf::from(proto.dir_relative_to_us),
};
input_files.push(dir.join(proto.proto_file_name));
include_dirs.push(dir);
let generated_module = proto.proto_file_name.replace(".proto", "");
writeln!(out, "#[path = \"{}/{}.rs\"]", out_dir, generated_module)?;
writeln!(out, "pub mod {};", proto.name_for_module)?;
}
// Invoke proto compiler.
protoc_rust::run(protoc_rust::Args {
out_dir: &out_dir,
input: &paths_to_strs(&input_files),
includes: &paths_to_strs(&include_dirs),
..Default::default()
})?;
Ok(())
}