]> git.lizzy.rs Git - rust.git/blob - src/tools/rustfmt/build.rs
Add 'src/tools/rustfmt/' from commit '7872306edf2e11a69aaffb9434088fd66b46a863'
[rust.git] / src / tools / rustfmt / build.rs
1 use std::env;
2 use std::fs::File;
3 use std::io::Write;
4 use std::path::{Path, PathBuf};
5 use std::process::Command;
6
7 fn main() {
8     // Only check .git/HEAD dirty status if it exists - doing so when
9     // building dependent crates may lead to false positives and rebuilds
10     if Path::new(".git/HEAD").exists() {
11         println!("cargo:rerun-if-changed=.git/HEAD");
12     }
13
14     println!("cargo:rerun-if-env-changed=CFG_RELEASE_CHANNEL");
15
16     let out_dir = PathBuf::from(env::var_os("OUT_DIR").unwrap());
17
18     File::create(out_dir.join("commit-info.txt"))
19         .unwrap()
20         .write_all(commit_info().as_bytes())
21         .unwrap();
22 }
23
24 // Try to get hash and date of the last commit on a best effort basis. If anything goes wrong
25 // (git not installed or if this is not a git repository) just return an empty string.
26 fn commit_info() -> String {
27     match (channel(), commit_hash(), commit_date()) {
28         (channel, Some(hash), Some(date)) => format!("{} ({} {})", channel, hash.trim_end(), date),
29         _ => String::new(),
30     }
31 }
32
33 fn channel() -> String {
34     if let Ok(channel) = env::var("CFG_RELEASE_CHANNEL") {
35         channel
36     } else {
37         "nightly".to_owned()
38     }
39 }
40
41 fn commit_hash() -> Option<String> {
42     Command::new("git")
43         .args(&["rev-parse", "--short", "HEAD"])
44         .output()
45         .ok()
46         .and_then(|r| String::from_utf8(r.stdout).ok())
47 }
48
49 fn commit_date() -> Option<String> {
50     Command::new("git")
51         .args(&["log", "-1", "--date=short", "--pretty=format:%cd"])
52         .output()
53         .ok()
54         .and_then(|r| String::from_utf8(r.stdout).ok())
55 }