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