]> git.lizzy.rs Git - rust.git/blob - build.rs
Merge pull request #3317 from fyrchik/fix/edition
[rust.git] / build.rs
1 // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use std::env;
12 use std::fs::File;
13 use std::io::Write;
14 use std::path::{Path, PathBuf};
15 use std::process::Command;
16
17 fn main() {
18     // Only check .git/HEAD dirty status if it exists - doing so when
19     // building dependent crates may lead to false positives and rebuilds
20     if Path::new(".git/HEAD").exists() {
21         println!("cargo:rerun-if-changed=.git/HEAD");
22     }
23
24     println!("cargo:rerun-if-env-changed=CFG_RELEASE_CHANNEL");
25
26     let out_dir = PathBuf::from(env::var_os("OUT_DIR").unwrap());
27
28     File::create(out_dir.join("commit-info.txt"))
29         .unwrap()
30         .write_all(commit_info().as_bytes())
31         .unwrap();
32 }
33
34 // Try to get hash and date of the last commit on a best effort basis. If anything goes wrong
35 // (git not installed or if this is not a git repository) just return an empty string.
36 fn commit_info() -> String {
37     match (channel(), commit_hash(), commit_date()) {
38         (channel, Some(hash), Some(date)) => format!("{} ({} {})", channel, hash.trim_end(), date),
39         _ => String::new(),
40     }
41 }
42
43 fn channel() -> String {
44     if let Ok(channel) = env::var("CFG_RELEASE_CHANNEL") {
45         channel
46     } else {
47         "nightly".to_owned()
48     }
49 }
50
51 fn commit_hash() -> Option<String> {
52     Command::new("git")
53         .args(&["rev-parse", "--short", "HEAD"])
54         .output()
55         .ok()
56         .and_then(|r| String::from_utf8(r.stdout).ok())
57 }
58
59 fn commit_date() -> Option<String> {
60     Command::new("git")
61         .args(&["log", "-1", "--date=short", "--pretty=format:%cd"])
62         .output()
63         .ok()
64         .and_then(|r| String::from_utf8(r.stdout).ok())
65 }