Skip to content

Instantly share code, notes, and snippets.

@dimfeld
Last active January 10, 2018 02:33
Show Gist options
  • Save dimfeld/74e66b2d099a06615c3ea6567983761a to your computer and use it in GitHub Desktop.
Save dimfeld/74e66b2d099a06615c3ea6567983761a to your computer and use it in GitHub Desktop.
A build.rs script that filters out directives for building capnp files with non-Rust targets.
/*
Go's Cap'n Proto code generator needs some extra directives, but I don't want to require that
my Rust build environment has the relevant Go include files available. The script below filters
out the Go directives before sending the resulting files to the compiler to make this work.
*/
extern crate capnpc;
use std::env;
use std::path::PathBuf;
use std::fs::File;
use std::io::{BufReader, BufWriter, BufRead, Write};
fn main() {
let capnp_dir = "src";
let out_dir = env::var("OUT_DIR").unwrap();
let files = vec![
"filenames_here.capnp",
];
let filtered_file_paths = files
.into_iter()
.map(|filename| {
let input_path = [&capnp_dir, filename].iter().collect::<PathBuf>();
let output_path = [&out_dir, filename].iter().collect::<PathBuf>();
let input_file = File::open(input_path.as_path()).map_err(|e| format!("{}: {}", filename, e.to_string()))?;
let output_file = File::create(output_path.as_path()).map_err(|e| format!("{}: {}", filename, e.to_string()))?;
let reader = BufReader::new(input_file);
let mut writer = BufWriter::new(output_file);
for line_result in reader.lines() {
let line = line_result.map_err(|e| format!("{}: {}", filename, e.to_string()))?;
if line.starts_with("using Go") || line.starts_with("$Go") {
continue
}
writer.write_all(line.as_bytes()).map_err(|e| format!("{}: {}", filename, e.to_string()))?;
writer.write_all(b"\n").map_err(|e| format!("{}: {}", filename, e.to_string()))?;
}
Ok(output_path)
})
.collect::<Result<Vec<_>, String>>()
.expect("Filtering capnp files");
let mut capnp_cmd = capnpc::CompilerCommand::new();
for filepath in filtered_file_paths {
capnp_cmd.file(filepath);
}
capnp_cmd
.src_prefix(out_dir)
.run().expect("schema compiler command");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment