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::exec::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_in_dry_run()
70            .start_capture_stdout(&exec_ctx);
71
72        let mut git_hash_cmd = helpers::git(Some(dir));
73        let ver_hash = git_hash_cmd
74            .arg("rev-parse")
75            .arg("HEAD")
76            .run_in_dry_run()
77            .start_capture_stdout(&exec_ctx);
78
79        let mut git_short_hash_cmd = helpers::git(Some(dir));
80        let short_ver_hash = git_short_hash_cmd
81            .arg("rev-parse")
82            .arg("--short=9")
83            .arg("HEAD")
84            .run_in_dry_run()
85            .start_capture_stdout(&exec_ctx);
86
87        GitInfo::Present(Some(Info {
88            commit_date: ver_date.wait_for_output(&exec_ctx).stdout().trim().to_string(),
89            sha: ver_hash.wait_for_output(&exec_ctx).stdout().trim().to_string(),
90            short_sha: short_ver_hash.wait_for_output(&exec_ctx).stdout().trim().to_string(),
91        }))
92    }
93
94    pub fn info(&self) -> Option<&Info> {
95        match self {
96            GitInfo::Absent => None,
97            GitInfo::Present(info) => info.as_ref(),
98            GitInfo::RecordedForTarball(info) => Some(info),
99        }
100    }
101
102    pub fn sha(&self) -> Option<&str> {
103        self.info().map(|s| &s.sha[..])
104    }
105
106    pub fn sha_short(&self) -> Option<&str> {
107        self.info().map(|s| &s.short_sha[..])
108    }
109
110    pub fn commit_date(&self) -> Option<&str> {
111        self.info().map(|s| &s.commit_date[..])
112    }
113
114    pub fn version(&self, build: &Build, num: &str) -> String {
115        let mut version = build.release(num);
116        if let Some(inner) = self.info() {
117            version.push_str(" (");
118            version.push_str(&inner.short_sha);
119            version.push(' ');
120            version.push_str(&inner.commit_date);
121            version.push(')');
122        }
123        version
124    }
125
126    /// Returns whether this directory has a `.git` directory which should be managed by bootstrap.
127    pub fn is_managed_git_subrepository(&self) -> bool {
128        match self {
129            GitInfo::Absent | GitInfo::RecordedForTarball(_) => false,
130            GitInfo::Present(_) => true,
131        }
132    }
133
134    /// Returns whether this is being built from a tarball.
135    pub fn is_from_tarball(&self) -> bool {
136        match self {
137            GitInfo::Absent | GitInfo::Present(_) => false,
138            GitInfo::RecordedForTarball(_) => true,
139        }
140    }
141}
142
143/// Read the commit information from the `git-commit-info` file given the
144/// project root.
145pub fn read_commit_info_file(root: &Path) -> Option<Info> {
146    if let Ok(contents) = fs::read_to_string(root.join("git-commit-info")) {
147        let mut lines = contents.lines();
148        let sha = lines.next();
149        let short_sha = lines.next();
150        let commit_date = lines.next();
151        let info = match (commit_date, sha, short_sha) {
152            (Some(commit_date), Some(sha), Some(short_sha)) => Info {
153                commit_date: commit_date.to_owned(),
154                sha: sha.to_owned(),
155                short_sha: short_sha.to_owned(),
156            },
157            _ => panic!("the `git-commit-info` file is malformed"),
158        };
159        Some(info)
160    } else {
161        None
162    }
163}
164
165/// Write the commit information to the `git-commit-info` file given the project
166/// root.
167pub fn write_commit_info_file(root: &Path, info: &Info) {
168    let commit_info = format!("{}\n{}\n{}\n", info.sha, info.short_sha, info.commit_date);
169    t!(fs::write(root.join("git-commit-info"), commit_info));
170}
171
172/// Write the commit hash to the `git-commit-hash` file given the project root.
173pub fn write_commit_hash_file(root: &Path, sha: &str) {
174    t!(fs::write(root.join("git-commit-hash"), sha));
175}