1 use crate::builder::{Builder, RunConfig, ShouldRun, Step};
3 use serde::{Deserialize, Serialize};
4 use std::collections::HashMap;
8 use std::io::{Seek, SeekFrom};
9 use std::path::{Path, PathBuf};
10 use std::process::Command;
13 // Each cycle is 42 days long (6 weeks); the last week is 35..=42 then.
14 const BETA_WEEK_START: u64 = 35;
16 #[cfg(target_os = "linux")]
17 const OS: Option<&str> = Some("linux");
20 const OS: Option<&str> = Some("windows");
22 #[cfg(all(not(target_os = "linux"), not(windows)))]
23 const OS: Option<&str> = None;
25 type ToolstateData = HashMap<Box<str>, ToolState>;
27 #[derive(Copy, Clone, Debug, Deserialize, Serialize, PartialEq, Eq, PartialOrd)]
28 #[serde(rename_all = "kebab-case")]
29 /// Whether a tool can be compiled, tested or neither
31 /// The tool compiles successfully, but the test suite fails
33 /// The tool compiles successfully and its test suite passes
35 /// The tool can't even be compiled
39 impl fmt::Display for ToolState {
40 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
45 ToolState::TestFail => "test-fail",
46 ToolState::TestPass => "test-pass",
47 ToolState::BuildFail => "build-fail",
53 impl Default for ToolState {
54 fn default() -> Self {
55 // err on the safe side
60 /// Number of days after the last promotion of beta.
61 /// Its value is 41 on the Tuesday where "Promote master to beta (T-2)" happens.
62 /// The Wednesday after this has value 0.
63 /// We track this value to prevent regressing tools in the last week of the 6-week cycle.
64 fn days_since_beta_promotion() -> u64 {
65 let since_epoch = t!(time::SystemTime::UNIX_EPOCH.elapsed());
66 (since_epoch.as_secs() / 86400 - 20) % 42
69 // These tools must test-pass on the beta/stable channels.
71 // On the nightly channel, their build step must be attempted, but they may not
72 // be able to build successfully.
73 static STABLE_TOOLS: &[(&str, &str)] = &[
74 ("book", "src/doc/book"),
75 ("nomicon", "src/doc/nomicon"),
76 ("reference", "src/doc/reference"),
77 ("rust-by-example", "src/doc/rust-by-example"),
78 ("edition-guide", "src/doc/edition-guide"),
79 ("rls", "src/tools/rls"),
80 ("rustfmt", "src/tools/rustfmt"),
81 ("clippy-driver", "src/tools/clippy"),
84 // These tools are permitted to not build on the beta/stable channels.
86 // We do require that we checked whether they build or not on the tools builder,
87 // though, as otherwise we will be unable to file an issue if they start
89 static NIGHTLY_TOOLS: &[(&str, &str)] = &[
90 ("miri", "src/tools/miri"),
91 ("embedded-book", "src/doc/embedded-book"),
92 ("rustc-guide", "src/doc/rustc-guide"),
95 fn print_error(tool: &str, submodule: &str) {
97 eprintln!("We detected that this PR updated '{}', but its tests failed.", tool);
99 eprintln!("If you do intend to update '{}', please check the error messages above and", tool);
100 eprintln!("commit another update.");
102 eprintln!("If you do NOT intend to update '{}', please ensure you did not accidentally", tool);
103 eprintln!("change the submodule at '{}'. You may ask your reviewer for the", submodule);
104 eprintln!("proper steps.");
105 std::process::exit(3);
108 fn check_changed_files(toolstates: &HashMap<Box<str>, ToolState>) {
110 let output = std::process::Command::new("git")
112 .arg("--name-status")
116 let output = match output {
119 eprintln!("Failed to get changed files: {:?}", e);
120 std::process::exit(1);
124 let output = t!(String::from_utf8(output.stdout));
126 for (tool, submodule) in STABLE_TOOLS.iter().chain(NIGHTLY_TOOLS.iter()) {
127 let changed = output.lines().any(|l| l.starts_with('M') && l.ends_with(submodule));
128 eprintln!("Verifying status of {}...", tool);
133 eprintln!("This PR updated '{}', verifying if status is 'test-pass'...", submodule);
134 if toolstates[*tool] != ToolState::TestPass {
135 print_error(tool, submodule);
140 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
141 pub struct ToolStateCheck;
143 impl Step for ToolStateCheck {
146 /// Checks tool state status.
148 /// This is intended to be used in the `checktools.sh` script. To use
149 /// this, set `save-toolstates` in `config.toml` so that tool status will
150 /// be saved to a JSON file. Then, run `x.py test --no-fail-fast` for all
151 /// of the tools to populate the JSON file. After that is done, this
152 /// command can be run to check for any status failures, and exits with an
153 /// error if there are any.
155 /// This also handles publishing the results to the `history` directory of
156 /// the toolstate repo https://github.com/rust-lang-nursery/rust-toolstate
157 /// if the env var `TOOLSTATE_PUBLISH` is set. Note that there is a
158 /// *separate* step of updating the `latest.json` file and creating GitHub
159 /// issues and comments in `src/ci/publish_toolstate.sh`, which is only
160 /// performed on master. (The shell/python code is intended to be migrated
161 /// here eventually.)
163 /// The rules for failure are:
164 /// * If the PR modifies a tool, the status must be test-pass.
165 /// NOTE: There is intent to change this, see
166 /// https://github.com/rust-lang/rust/issues/65000.
167 /// * All "stable" tools must be test-pass on the stable or beta branches.
168 /// * During beta promotion week, a PR is not allowed to "regress" a
169 /// stable tool. That is, the status is not allowed to get worse
170 /// (test-pass to test-fail or build-fail).
171 fn run(self, builder: &Builder<'_>) {
172 if builder.config.dry_run {
176 let days_since_beta_promotion = days_since_beta_promotion();
177 let in_beta_week = days_since_beta_promotion >= BETA_WEEK_START;
178 let is_nightly = !(builder.config.channel == "beta" || builder.config.channel == "stable");
179 let toolstates = builder.toolstates();
181 let mut did_error = false;
183 for (tool, _) in STABLE_TOOLS.iter().chain(NIGHTLY_TOOLS.iter()) {
184 if !toolstates.contains_key(*tool) {
186 eprintln!("error: Tool `{}` was not recorded in tool state.", tool);
191 std::process::exit(1);
194 check_changed_files(&toolstates);
195 checkout_toolstate_repo();
196 let old_toolstate = read_old_toolstate();
198 for (tool, _) in STABLE_TOOLS.iter() {
199 let state = toolstates[*tool];
201 if state != ToolState::TestPass {
204 eprintln!("error: Tool `{}` should be test-pass but is {}", tool, state);
205 } else if in_beta_week {
206 let old_state = old_toolstate
208 .find(|ts| ts.tool == *tool)
209 .expect("latest.json missing tool")
211 if state < old_state {
214 "error: Tool `{}` has regressed from {} to {} during beta week.",
215 tool, old_state, state
219 "warning: Tool `{}` is not test-pass (is `{}`), \
220 this should be fixed before beta is branched.",
229 std::process::exit(1);
232 if builder.config.channel == "nightly" && env::var_os("TOOLSTATE_PUBLISH").is_some() {
233 commit_toolstate_change(&toolstates, in_beta_week);
237 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
238 run.path("check-tools")
241 fn make_run(run: RunConfig<'_>) {
242 run.builder.ensure(ToolStateCheck);
247 fn toolstates(&self) -> HashMap<Box<str>, ToolState> {
248 if let Some(ref path) = self.config.save_toolstates {
249 if let Some(parent) = path.parent() {
250 // Ensure the parent directory always exists
251 t!(std::fs::create_dir_all(parent));
254 t!(fs::OpenOptions::new().create(true).write(true).read(true).open(path));
256 serde_json::from_reader(&mut file).unwrap_or_default()
262 /// Updates the actual toolstate of a tool.
264 /// The toolstates are saved to the file specified by the key
265 /// `rust.save-toolstates` in `config.toml`. If unspecified, nothing will be
266 /// done. The file is updated immediately after this function completes.
267 pub fn save_toolstate(&self, tool: &str, state: ToolState) {
268 if let Some(ref path) = self.config.save_toolstates {
269 if let Some(parent) = path.parent() {
270 // Ensure the parent directory always exists
271 t!(std::fs::create_dir_all(parent));
274 t!(fs::OpenOptions::new().create(true).read(true).write(true).open(path));
276 let mut current_toolstates: HashMap<Box<str>, ToolState> =
277 serde_json::from_reader(&mut file).unwrap_or_default();
278 current_toolstates.insert(tool.into(), state);
279 t!(file.seek(SeekFrom::Start(0)));
281 t!(serde_json::to_writer(file, ¤t_toolstates));
286 fn toolstate_repo() -> String {
287 env::var("TOOLSTATE_REPO")
288 .unwrap_or_else(|_| "https://github.com/rust-lang-nursery/rust-toolstate.git".to_string())
291 /// Directory where the toolstate repo is checked out.
292 const TOOLSTATE_DIR: &str = "rust-toolstate";
294 /// Checks out the toolstate repo into `TOOLSTATE_DIR`.
295 fn checkout_toolstate_repo() {
296 if let Ok(token) = env::var("TOOLSTATE_REPO_ACCESS_TOKEN") {
297 prepare_toolstate_config(&token);
299 if Path::new(TOOLSTATE_DIR).exists() {
300 eprintln!("Cleaning old toolstate directory...");
301 t!(fs::remove_dir_all(TOOLSTATE_DIR));
304 let status = Command::new("git")
307 .arg(toolstate_repo())
310 let success = match status {
311 Ok(s) => s.success(),
315 panic!("git clone unsuccessful (status: {:?})", status);
319 /// Sets up config and authentication for modifying the toolstate repo.
320 fn prepare_toolstate_config(token: &str) {
321 fn git_config(key: &str, value: &str) {
322 let status = Command::new("git").arg("config").arg("--global").arg(key).arg(value).status();
323 let success = match status {
324 Ok(s) => s.success(),
328 panic!("git config key={} value={} successful (status: {:?})", key, value, status);
332 // If changing anything here, then please check that src/ci/publish_toolstate.sh is up to date
334 git_config("user.email", "7378925+rust-toolstate-update@users.noreply.github.com");
335 git_config("user.name", "Rust Toolstate Update");
336 git_config("credential.helper", "store");
338 let credential = format!("https://{}:x-oauth-basic@github.com\n", token,);
339 let git_credential_path = PathBuf::from(t!(env::var("HOME"))).join(".git-credentials");
340 t!(fs::write(&git_credential_path, credential));
343 /// Reads the latest toolstate from the toolstate repo.
344 fn read_old_toolstate() -> Vec<RepoState> {
345 let latest_path = Path::new(TOOLSTATE_DIR).join("_data").join("latest.json");
346 let old_toolstate = t!(fs::read(latest_path));
347 t!(serde_json::from_slice(&old_toolstate))
350 /// This function `commit_toolstate_change` provides functionality for pushing a change
351 /// to the `rust-toolstate` repository.
353 /// The function relies on a GitHub bot user, which should have a Personal access
354 /// token defined in the environment variable $TOOLSTATE_REPO_ACCESS_TOKEN. If for
355 /// some reason you need to change the token, please update the Azure Pipelines
358 /// 1. Generate a new Personal access token:
360 /// * Login to the bot account, and go to Settings -> Developer settings ->
361 /// Personal access tokens
362 /// * Click "Generate new token"
363 /// * Enable the "public_repo" permission, then click "Generate token"
364 /// * Copy the generated token (should be a 40-digit hexadecimal number).
365 /// Save it somewhere secure, as the token would be gone once you leave
368 /// 2. Update the variable group in Azure Pipelines
370 /// * Ping a member of the infrastructure team to do this.
372 /// 4. Replace the email address below if the bot account identity is changed
374 /// * See <https://help.github.com/articles/about-commit-email-addresses/>
375 /// if a private email by GitHub is wanted.
376 fn commit_toolstate_change(current_toolstate: &ToolstateData, in_beta_week: bool) {
377 let old_toolstate = read_old_toolstate();
379 let message = format!("({} CI update)", OS.expect("linux/windows only"));
380 let mut success = false;
382 // Update the toolstate results (the new commit-to-toolstate mapping) in the toolstate repo.
383 change_toolstate(¤t_toolstate, &old_toolstate, in_beta_week);
385 // `git commit` failing means nothing to commit.
386 let status = t!(Command::new("git")
387 .current_dir(TOOLSTATE_DIR)
393 if !status.success() {
398 let status = t!(Command::new("git")
399 .current_dir(TOOLSTATE_DIR)
404 // If we successfully push, exit.
405 if status.success() {
409 eprintln!("Sleeping for 3 seconds before retrying push");
410 std::thread::sleep(std::time::Duration::from_secs(3));
411 let status = t!(Command::new("git")
412 .current_dir(TOOLSTATE_DIR)
417 assert!(status.success());
418 let status = t!(Command::new("git")
419 .current_dir(TOOLSTATE_DIR)
422 .arg("origin/master")
424 assert!(status.success());
428 panic!("Failed to update toolstate repository with new data");
433 current_toolstate: &ToolstateData,
434 old_toolstate: &[RepoState],
437 let mut regressed = false;
438 for repo_state in old_toolstate {
439 let tool = &repo_state.tool;
440 let state = repo_state.state();
441 let new_state = current_toolstate[tool.as_str()];
443 if new_state != state {
444 eprintln!("The state of `{}` has changed from `{}` to `{}`", tool, state, new_state);
445 if new_state < state {
446 if !NIGHTLY_TOOLS.iter().any(|(name, _path)| name == tool) {
453 if regressed && in_beta_week {
454 std::process::exit(1);
457 let commit = t!(std::process::Command::new("git").arg("rev-parse").arg("HEAD").output());
458 let commit = t!(String::from_utf8(commit.stdout));
460 let toolstate_serialized = t!(serde_json::to_string(¤t_toolstate));
462 let history_path = Path::new(TOOLSTATE_DIR)
464 .join(format!("{}.tsv", OS.expect("linux/windows only")));
465 let mut file = t!(fs::read_to_string(&history_path));
466 let end_of_first_line = file.find('\n').unwrap();
467 file.insert_str(end_of_first_line, &format!("\n{}\t{}", commit.trim(), toolstate_serialized));
468 t!(fs::write(&history_path, file));
471 #[derive(Debug, Serialize, Deserialize)]
481 fn state(&self) -> ToolState {
482 if cfg!(target_os = "linux") {
484 } else if cfg!(windows) {