bootstrap/utils/
channel.rs

1//! Build configuration for Rust's release channels.
2//!
3//! Implements the stable/beta/nightly channel distinctions by setting various
4//! flags like the `unstable_features`, calculating variables like `release` and
5//! `package_vers`, and otherwise indicating to the compiler what it should
6//! print out as part of its version information.
7
8use std::fs;
9use std::path::Path;
10
11use super::execution_context::ExecutionContext;
12use super::helpers;
13use crate::Build;
14use crate::utils::helpers::t;
15
16#[derive(Clone, Default)]
17pub enum GitInfo {
18    /// This is not a git repository.
19    #[default]
20    Absent,
21    /// This is a git repository.
22    /// If the info should be used (`omit_git_hash` is false), this will be
23    /// `Some`, otherwise it will be `None`.
24    Present(Option<Info>),
25    /// This is not a git repository, but the info can be fetched from the
26    /// `git-commit-info` file.
27    RecordedForTarball(Info),
28}
29
30#[derive(Clone)]
31pub struct Info {
32    pub commit_date: String,
33    pub sha: String,
34    pub short_sha: String,
35}
36
37impl GitInfo {
38    pub fn new(omit_git_hash: bool, dir: &Path, exec_ctx: impl AsRef<ExecutionContext>) -> GitInfo {
39        // See if this even begins to look like a git dir
40        if !dir.join(".git").exists() {
41            match read_commit_info_file(dir) {
42                Some(info) => return GitInfo::RecordedForTarball(info),
43                None => return GitInfo::Absent,
44            }
45        }
46
47        let mut git_command = helpers::git(Some(dir));
48        git_command.arg("rev-parse");
49        let output = git_command.allow_failure().run_capture(&exec_ctx);
50
51        if output.is_failure() {
52            return GitInfo::Absent;
53        }
54
55        // If we're ignoring the git info, we don't actually need to collect it, just make sure this
56        // was a git repo in the first place.
57        if omit_git_hash {
58            return GitInfo::Present(None);
59        }
60
61        // Ok, let's scrape some info
62        // We use the command's spawn API to execute these commands concurrently, which leads to performance improvements.
63        let mut git_log_cmd = helpers::git(Some(dir));
64        let ver_date = git_log_cmd
65            .arg("log")
66            .arg("-1")
67            .arg("--date=short")
68            .arg("--pretty=format:%cd")
69            .run_always()
70            .start_capture_stdout(&exec_ctx);
71
72        let mut git_hash_cmd = helpers::git(Some(dir));
73        let ver_hash =
74            git_hash_cmd.arg("rev-parse").arg("HEAD").run_always().start_capture_stdout(&exec_ctx);
75
76        let mut git_short_hash_cmd = helpers::git(Some(dir));
77        let short_ver_hash = git_short_hash_cmd
78            .arg("rev-parse")
79            .arg("--short=9")
80            .arg("HEAD")
81            .run_always()
82            .start_capture_stdout(&exec_ctx);
83
84        GitInfo::Present(Some(Info {
85            commit_date: ver_date.wait_for_output(&exec_ctx).stdout().trim().to_string(),
86            sha: ver_hash.wait_for_output(&exec_ctx).stdout().trim().to_string(),
87            short_sha: short_ver_hash.wait_for_output(&exec_ctx).stdout().trim().to_string(),
88        }))
89    }
90
91    pub fn info(&self) -> Option<&Info> {
92        match self {
93            GitInfo::Absent => None,
94            GitInfo::Present(info) => info.as_ref(),
95            GitInfo::RecordedForTarball(info) => Some(info),
96        }
97    }
98
99    pub fn sha(&self) -> Option<&str> {
100        self.info().map(|s| &s.sha[..])
101    }
102
103    pub fn sha_short(&self) -> Option<&str> {
104        self.info().map(|s| &s.short_sha[..])
105    }
106
107    pub fn commit_date(&self) -> Option<&str> {
108        self.info().map(|s| &s.commit_date[..])
109    }
110
111    pub fn version(&self, build: &Build, num: &str) -> String {
112        let mut version = build.release(num);
113        if let Some(inner) = self.info() {
114            version.push_str(" (");
115            version.push_str(&inner.short_sha);
116            version.push(' ');
117            version.push_str(&inner.commit_date);
118            version.push(')');
119        }
120        version
121    }
122
123    /// Returns whether this directory has a `.git` directory which should be managed by bootstrap.
124    pub fn is_managed_git_subrepository(&self) -> bool {
125        match self {
126            GitInfo::Absent | GitInfo::RecordedForTarball(_) => false,
127            GitInfo::Present(_) => true,
128        }
129    }
130
131    /// Returns whether this is being built from a tarball.
132    pub fn is_from_tarball(&self) -> bool {
133        match self {
134            GitInfo::Absent | GitInfo::Present(_) => false,
135            GitInfo::RecordedForTarball(_) => true,
136        }
137    }
138}
139
140/// Read the commit information from the `git-commit-info` file given the
141/// project root.
142pub fn read_commit_info_file(root: &Path) -> Option<Info> {
143    if let Ok(contents) = fs::read_to_string(root.join("git-commit-info")) {
144        let mut lines = contents.lines();
145        let sha = lines.next();
146        let short_sha = lines.next();
147        let commit_date = lines.next();
148        let info = match (commit_date, sha, short_sha) {
149            (Some(commit_date), Some(sha), Some(short_sha)) => Info {
150                commit_date: commit_date.to_owned(),
151                sha: sha.to_owned(),
152                short_sha: short_sha.to_owned(),
153            },
154            _ => panic!("the `git-commit-info` file is malformed"),
155        };
156        Some(info)
157    } else {
158        None
159    }
160}
161
162/// Write the commit information to the `git-commit-info` file given the project
163/// root.
164pub fn write_commit_info_file(root: &Path, info: &Info) {
165    let commit_info = format!("{}\n{}\n{}\n", info.sha, info.short_sha, info.commit_date);
166    t!(fs::write(root.join("git-commit-info"), commit_info));
167}
168
169/// Write the commit hash to the `git-commit-hash` file given the project root.
170pub fn write_commit_hash_file(root: &Path, sha: &str) {
171    t!(fs::write(root.join("git-commit-hash"), sha));
172}