]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/format.rs
Rollup merge of #67299 - christianpoveda:try_immty_from_int, r=RalfJung
[rust.git] / src / bootstrap / format.rs
1 //! Runs rustfmt on the repository.
2
3 use crate::Build;
4 use std::process::Command;
5 use ignore::WalkBuilder;
6 use std::path::Path;
7 use build_helper::t;
8
9 fn rustfmt(build: &Build, path: &Path, check: bool) {
10     let rustfmt_path = build.config.initial_rustfmt.as_ref().unwrap_or_else(|| {
11         eprintln!("./x.py fmt is not supported on this channel");
12         std::process::exit(1);
13     });
14
15     let mut cmd = Command::new(&rustfmt_path);
16     // avoid the submodule config paths from coming into play,
17     // we only allow a single global config for the workspace for now
18     cmd.arg("--config-path").arg(&build.src.canonicalize().unwrap());
19     cmd.arg("--unstable-features");
20     cmd.arg("--skip-children");
21     if check {
22         cmd.arg("--check");
23     }
24     cmd.arg(&path);
25     let cmd_debug = format!("{:?}", cmd);
26     let status = cmd.status().expect("executing rustfmt");
27     assert!(status.success(), "running {} successful", cmd_debug);
28 }
29
30 #[derive(serde::Deserialize)]
31 struct RustfmtConfig {
32     ignore: Vec<String>,
33 }
34
35 pub fn format(build: &Build, check: bool) {
36     let mut builder = ignore::types::TypesBuilder::new();
37     builder.add_defaults();
38     builder.select("rust");
39     let matcher = builder.build().unwrap();
40     let rustfmt_config = build.src.join("rustfmt.toml");
41     if !rustfmt_config.exists() {
42         eprintln!("Not running formatting checks; rustfmt.toml does not exist.");
43         eprintln!("This may happen in distributed tarballs.");
44         return;
45     }
46     let rustfmt_config = t!(std::fs::read_to_string(&rustfmt_config));
47     let rustfmt_config: RustfmtConfig = t!(toml::from_str(&rustfmt_config));
48     let mut ignore_fmt = ignore::overrides::OverrideBuilder::new(&build.src);
49     for ignore in rustfmt_config.ignore {
50         ignore_fmt.add(&format!("!{}", ignore)).expect(&ignore);
51     }
52     let ignore_fmt = ignore_fmt.build().unwrap();
53
54     let walker = WalkBuilder::new(&build.src)
55         .types(matcher)
56         .overrides(ignore_fmt)
57         .build();
58     for entry in walker {
59         let entry = t!(entry);
60         if entry.file_type().map_or(false, |t| t.is_file()) {
61             rustfmt(build, &entry.path(), check);
62         }
63     }
64 }