blob: b0b101095811a30438b2b94f3735cf2cc98c705f [file] [log] [blame]
Chih-Hung Hsiehcfc3a232020-06-10 20:13:05 -07001use std::env;
2use std::fs::File;
3use std::io::{Read, Write};
4use std::path::{Path, PathBuf};
5use std::process;
6
7// % rustc +stable --version
8// rustc 1.26.0 (a77568041 2018-05-07)
9// % rustc +beta --version
10// rustc 1.27.0-beta.1 (03fb2f447 2018-05-09)
11// % rustc +nightly --version
12// rustc 1.27.0-nightly (acd3871ba 2018-05-10)
13fn version_is_nightly(version: &str) -> bool {
14 version.contains("nightly")
15}
16
17fn main() {
18 let rustc = env::var("RUSTC").expect("RUSTC unset");
19
20 let mut child = process::Command::new(rustc)
21 .args(&["--version"])
22 .stdin(process::Stdio::null())
23 .stdout(process::Stdio::piped())
24 .spawn()
25 .expect("spawn rustc");
26
27 let mut rustc_version = String::new();
28
29 child
30 .stdout
31 .as_mut()
32 .expect("stdout")
33 .read_to_string(&mut rustc_version)
34 .expect("read_to_string");
35 assert!(child.wait().expect("wait").success());
36
37 if version_is_nightly(&rustc_version) {
38 println!("cargo:rustc-cfg=rustc_nightly");
39 }
40
41 write_version();
42}
43
44fn out_dir() -> PathBuf {
45 PathBuf::from(env::var("OUT_DIR").expect("OUT_DIR"))
46}
47
48fn version() -> String {
49 env::var("CARGO_PKG_VERSION").expect("CARGO_PKG_VERSION")
50}
51
52fn write_version() {
53 let version = version();
54 let version_ident = format!(
55 "VERSION_{}",
56 version.replace(".", "_").replace("-", "_").to_uppercase()
57 );
58 let mut file = File::create(Path::join(&out_dir(), "version.rs")).expect("open");
59 writeln!(file, "/// protobuf crate version").unwrap();
60 writeln!(file, "pub const VERSION: &'static str = \"{}\";", version).unwrap();
61 writeln!(file, "/// This symbol is used by codegen").unwrap();
62 writeln!(file, "#[doc(hidden)]").unwrap();
63 writeln!(
64 file,
65 "pub const VERSION_IDENT: &'static str = \"{}\";",
66 version_ident
67 )
68 .unwrap();
69 writeln!(
70 file,
71 "/// This symbol can be referenced to assert that proper version of crate is used"
72 )
73 .unwrap();
74 writeln!(file, "pub const {}: () = ();", version_ident).unwrap();
75 file.flush().unwrap();
76}