| 1 | use std::fs::File; |
| 2 | use std::io::{stderr, Write}; |
| 3 | use std::process::{Command, Output}; |
| 4 | use std::path::Path; |
| 5 | use std::env; |
| 6 | |
| 7 | fn run_cmd(command: &mut Command) -> Output { |
| 8 | let stream = stderr(); |
| 9 | let mut f = stream.lock(); |
| 10 | let res = command.output(); |
| 11 | match res { |
| 12 | Ok(output) => if !output.status.success() { |
| 13 | write!(&mut f, "Command `{:?}` failed", command).unwrap(); |
| 14 | panic!("{}", String::from_utf8_lossy(&output.stderr[..])) |
| 15 | } else { |
| 16 | output |
| 17 | }, |
| 18 | Err(err) => { |
| 19 | write!(&mut f, "Command `{:?}` failed", command).unwrap(); |
| 20 | panic!("{}", err) |
| 21 | } |
| 22 | } |
| 23 | } |
| 24 | |
| 25 | fn main() |
| 26 | { |
| 27 | let source_file = Path::new("src/codegen/type_size.c"); |
| 28 | if !source_file.exists() { |
| 29 | panic!("Could not find file: {}", source_file.to_string_lossy()); |
| 30 | } |
| 31 | |
| 32 | let out_dir_var = match env::var("OUT_DIR") { |
| 33 | Ok(dir) => dir, |
| 34 | Err(e) => panic!("Could not get env value OUT_DIR: {}", e) |
| 35 | }; |
| 36 | let out_dir = Path::new(&out_dir_var); |
| 37 | if !out_dir.exists() { |
| 38 | panic!("Could not find directory: {}", out_dir.to_string_lossy()); |
| 39 | } |
| 40 | |
| 41 | let out_file = out_dir.join("codegen"); |
| 42 | |
| 43 | let mut gcc_cmd = Command::new("gcc"); |
| 44 | gcc_cmd.arg(source_file) |
| 45 | .arg("-o").arg(&out_file); |
| 46 | |
| 47 | match env::var("LIBYAML_CFLAGS") { |
| 48 | Ok(compile_flags) => { gcc_cmd.arg(&compile_flags); }, |
| 49 | Err(_) => () |
| 50 | } |
| 51 | |
| 52 | run_cmd(&mut gcc_cmd); |
| 53 | |
| 54 | let mut codegen_cmd = Command::new(&out_file); |
| 55 | let output = run_cmd(&mut codegen_cmd); |
| 56 | |
| 57 | let generated_file = out_dir.join("type_size.rs"); |
| 58 | let mut f = match File::create(generated_file) { |
| 59 | Ok(f) => f, |
| 60 | Err(e) => panic!("Could not open file $OUT_DIR/type_size.rs: {}", e) |
| 61 | }; |
| 62 | |
| 63 | match f.write_all(&output.stdout[..]) { |
| 64 | Err(e) => panic!("Could not write to $OUT_DIR/type_size.rs: {}", e), |
| 65 | Ok(_) => () |
| 66 | } |
| 67 | } |