1 //! Runs rustfmt on the repository.
3 use crate::builder::Builder;
4 use crate::util::{output, program_out_of_date, t};
5 use ignore::WalkBuilder;
6 use std::collections::VecDeque;
7 use std::path::{Path, PathBuf};
8 use std::process::{Command, Stdio};
9 use std::sync::mpsc::SyncSender;
11 fn rustfmt(src: &Path, rustfmt: &Path, paths: &[PathBuf], check: bool) -> impl FnMut(bool) -> bool {
12 let mut cmd = Command::new(&rustfmt);
13 // avoid the submodule config paths from coming into play,
14 // we only allow a single global config for the workspace for now
15 cmd.arg("--config-path").arg(&src.canonicalize().unwrap());
16 cmd.arg("--edition").arg("2021");
17 cmd.arg("--unstable-features");
18 cmd.arg("--skip-children");
23 let cmd_debug = format!("{:?}", cmd);
24 let mut cmd = cmd.spawn().expect("running rustfmt");
25 // poor man's async: return a closure that'll wait for rustfmt's completion
26 move |block: bool| -> bool {
28 match cmd.try_wait() {
33 let status = cmd.wait().unwrap();
34 if !status.success() {
36 "Running `{}` failed.\nIf you're running `tidy`, \
37 try again with `--bless`. Or, if you just want to format \
38 code, run `./x.py fmt` instead.",
41 crate::detail_exit(1);
47 fn get_rustfmt_version(build: &Builder<'_>) -> Option<(String, PathBuf)> {
48 let stamp_file = build.out.join("rustfmt.stamp");
50 let mut cmd = Command::new(match build.initial_rustfmt() {
55 let output = match cmd.output() {
57 Err(_) => return None,
59 if !output.status.success() {
62 Some((String::from_utf8(output.stdout).unwrap(), stamp_file))
65 /// Return whether the format cache can be reused.
66 fn verify_rustfmt_version(build: &Builder<'_>) -> bool {
67 let Some((version, stamp_file)) = get_rustfmt_version(build) else {return false;};
68 !program_out_of_date(&stamp_file, &version)
71 /// Updates the last rustfmt version used
72 fn update_rustfmt_version(build: &Builder<'_>) {
73 let Some((version, stamp_file)) = get_rustfmt_version(build) else {return;};
74 t!(std::fs::write(stamp_file, version))
77 /// Returns the files modified between the `merge-base` of HEAD and
78 /// rust-lang/master and what is now on the disk.
80 /// Returns `None` if all files should be formatted.
81 fn get_modified_files(build: &Builder<'_>) -> Option<Vec<String>> {
82 let Ok(remote) = get_rust_lang_rust_remote() else {return None;};
83 if !verify_rustfmt_version(build) {
94 .arg(&format!("{remote}/master")),
97 .map(|s| s.trim().to_owned())
102 /// Finds the remote for rust-lang/rust.
103 /// For example for these remotes it will return `upstream`.
105 /// origin https://github.com/Nilstrieb/rust.git (fetch)
106 /// origin https://github.com/Nilstrieb/rust.git (push)
107 /// upstream https://github.com/rust-lang/rust (fetch)
108 /// upstream https://github.com/rust-lang/rust (push)
110 fn get_rust_lang_rust_remote() -> Result<String, String> {
111 let mut git = Command::new("git");
112 git.args(["config", "--local", "--get-regex", "remote\\..*\\.url"]);
114 let output = git.output().map_err(|err| format!("{err:?}"))?;
115 if !output.status.success() {
116 return Err("failed to execute git config command".to_owned());
119 let stdout = String::from_utf8(output.stdout).map_err(|err| format!("{err:?}"))?;
121 let rust_lang_remote = stdout
123 .find(|remote| remote.contains("rust-lang"))
124 .ok_or_else(|| "rust-lang/rust remote not found".to_owned())?;
127 rust_lang_remote.split('.').nth(1).ok_or_else(|| "remote name not found".to_owned())?;
128 Ok(remote_name.into())
131 #[derive(serde::Deserialize)]
132 struct RustfmtConfig {
136 pub fn format(build: &Builder<'_>, check: bool, paths: &[PathBuf]) {
137 if build.config.dry_run() {
140 let mut builder = ignore::types::TypesBuilder::new();
141 builder.add_defaults();
142 builder.select("rust");
143 let matcher = builder.build().unwrap();
144 let rustfmt_config = build.src.join("rustfmt.toml");
145 if !rustfmt_config.exists() {
146 eprintln!("Not running formatting checks; rustfmt.toml does not exist.");
147 eprintln!("This may happen in distributed tarballs.");
150 let rustfmt_config = t!(std::fs::read_to_string(&rustfmt_config));
151 let rustfmt_config: RustfmtConfig = t!(toml::from_str(&rustfmt_config));
152 let mut ignore_fmt = ignore::overrides::OverrideBuilder::new(&build.src);
153 for ignore in rustfmt_config.ignore {
154 ignore_fmt.add(&format!("!{}", ignore)).expect(&ignore);
156 let git_available = match Command::new("git")
158 .stdout(Stdio::null())
159 .stderr(Stdio::null())
162 Ok(status) => status.success(),
166 let in_working_tree = match build
170 .arg("--is-inside-work-tree")
171 .stdout(Stdio::null())
172 .stderr(Stdio::null())
175 Ok(status) => status.success(),
179 let untracked_paths_output = output(
180 build.config.git().arg("status").arg("--porcelain").arg("--untracked-files=normal"),
182 let untracked_paths = untracked_paths_output
184 .filter(|entry| entry.starts_with("??"))
186 entry.split(' ').nth(1).expect("every git status entry should list a path")
188 for untracked_path in untracked_paths {
189 println!("skip untracked path {} during rustfmt invocations", untracked_path);
190 // The leading `/` makes it an exact match against the
191 // repository root, rather than a glob. Without that, if you
192 // have `foo.rs` in the repository root it will also match
193 // against anything like `compiler/rustc_foo/src/foo.rs`,
194 // preventing the latter from being formatted.
195 ignore_fmt.add(&format!("!/{}", untracked_path)).expect(&untracked_path);
197 if !check && paths.is_empty() {
198 if let Some(files) = get_modified_files(build) {
200 println!("formatting modified file {file}");
201 ignore_fmt.add(&format!("/{file}")).expect(&file);
206 println!("Not in git tree. Skipping git-aware format checks");
209 println!("Could not find usable git. Skipping git-aware format checks");
211 let ignore_fmt = ignore_fmt.build().unwrap();
213 let rustfmt_path = build.initial_rustfmt().unwrap_or_else(|| {
214 eprintln!("./x.py fmt is not supported on this channel");
215 crate::detail_exit(1);
217 assert!(rustfmt_path.exists(), "{}", rustfmt_path.display());
218 let src = build.src.clone();
219 let (tx, rx): (SyncSender<PathBuf>, _) = std::sync::mpsc::sync_channel(128);
220 let walker = match paths.get(0) {
222 let mut walker = WalkBuilder::new(first);
223 for path in &paths[1..] {
228 None => WalkBuilder::new(src.clone()),
231 .overrides(ignore_fmt)
234 // there is a lot of blocking involved in spawning a child process and reading files to format.
235 // spawn more processes than available concurrency to keep the CPU busy
236 let max_processes = build.jobs() as usize * 2;
238 // spawn child processes on a separate thread so we can batch entries we have received from ignore
239 let thread = std::thread::spawn(move || {
240 let mut children = VecDeque::new();
241 while let Ok(path) = rx.recv() {
242 // try getting a few more paths from the channel to amortize the overhead of spawning processes
243 let paths: Vec<_> = rx.try_iter().take(7).chain(std::iter::once(path)).collect();
245 let child = rustfmt(&src, &rustfmt_path, paths.as_slice(), check);
246 children.push_back(child);
248 // poll completion before waiting
249 for i in (0..children.len()).rev() {
250 if children[i](false) {
251 children.swap_remove_back(i);
256 if children.len() >= max_processes {
257 // await oldest child
258 children.pop_front().unwrap()(true);
262 // await remaining children
263 for mut child in children {
270 Box::new(move |entry| {
271 let entry = t!(entry);
272 if entry.file_type().map_or(false, |t| t.is_file()) {
273 t!(tx.send(entry.into_path()));
275 ignore::WalkState::Continue
281 thread.join().unwrap();
283 update_rustfmt_version(build);