1 use crate::clippy_project_root;
2 use itertools::Itertools;
3 use shell_escape::escape;
4 use std::ffi::{OsStr, OsString};
6 use std::process::{self, Command};
12 CommandFailed(String, String),
15 WalkDirError(walkdir::Error),
19 impl From<io::Error> for CliError {
20 fn from(error: io::Error) -> Self {
25 impl From<walkdir::Error> for CliError {
26 fn from(error: walkdir::Error) -> Self {
27 Self::WalkDirError(error)
36 // the "main" function of cargo dev fmt
37 pub fn run(check: bool, verbose: bool) {
38 fn try_run(context: &FmtContext) -> Result<bool, CliError> {
39 let mut success = true;
41 let project_root = clippy_project_root();
43 // if we added a local rustc repo as path dependency to clippy for rust analyzer, we do NOT want to
44 // format because rustfmt would also format the entire rustc repo as it is a local
46 if fs::read_to_string(project_root.join("Cargo.toml"))
47 .expect("Failed to read clippy Cargo.toml")
48 .contains(&"[target.'cfg(NOT_A_PLATFORM)'.dependencies]")
50 return Err(CliError::RaSetupActive);
53 rustfmt_test(context)?;
55 success &= cargo_fmt(context, project_root.as_path())?;
56 success &= cargo_fmt(context, &project_root.join("clippy_dev"))?;
57 success &= cargo_fmt(context, &project_root.join("rustc_tools_util"))?;
58 success &= cargo_fmt(context, &project_root.join("lintcheck"))?;
60 let chunks = WalkDir::new(project_root.join("tests"))
63 let entry = entry.expect("failed to find tests");
64 let path = entry.path();
66 if path.extension() != Some("rs".as_ref()) || entry.file_name() == "ice-3891.rs" {
69 Some(entry.into_path().into_os_string())
74 for chunk in &chunks {
75 success &= rustfmt(context, chunk)?;
81 fn output_err(err: CliError) {
83 CliError::CommandFailed(command, stderr) => {
84 eprintln!("error: A command failed! `{}`\nstderr: {}", command, stderr);
86 CliError::IoError(err) => {
87 eprintln!("error: {}", err);
89 CliError::RustfmtNotInstalled => {
90 eprintln!("error: rustfmt nightly is not installed.");
92 CliError::WalkDirError(err) => {
93 eprintln!("error: {}", err);
95 CliError::RaSetupActive => {
97 "error: a local rustc repo is enabled as path dependency via `cargo dev setup intellij`.
98 Not formatting because that would format the local repo as well!
99 Please revert the changes to Cargo.tomls first."
105 let context = FmtContext { check, verbose };
106 let result = try_run(&context);
107 let code = match result {
111 eprintln!("Formatting check failed.");
112 eprintln!("Run `cargo dev fmt` to update formatting.");
123 fn format_command(program: impl AsRef<OsStr>, dir: impl AsRef<Path>, args: &[impl AsRef<OsStr>]) -> String {
124 let arg_display: Vec<_> = args.iter().map(|a| escape(a.as_ref().to_string_lossy())).collect();
128 escape(dir.as_ref().to_string_lossy()),
129 escape(program.as_ref().to_string_lossy()),
130 arg_display.join(" ")
135 context: &FmtContext,
136 program: impl AsRef<OsStr>,
137 dir: impl AsRef<Path>,
138 args: &[impl AsRef<OsStr>],
139 ) -> Result<bool, CliError> {
141 println!("{}", format_command(&program, &dir, args));
144 let child = Command::new(&program).current_dir(&dir).args(args.iter()).spawn()?;
145 let output = child.wait_with_output()?;
146 let success = output.status.success();
148 if !context.check && !success {
149 let stderr = std::str::from_utf8(&output.stderr).unwrap_or("");
150 return Err(CliError::CommandFailed(
151 format_command(&program, &dir, args),
152 String::from(stderr),
159 fn cargo_fmt(context: &FmtContext, path: &Path) -> Result<bool, CliError> {
160 let mut args = vec!["fmt", "--all"];
163 args.push("--check");
165 let success = exec(context, "cargo", path, &args)?;
170 fn rustfmt_test(context: &FmtContext) -> Result<(), CliError> {
171 let program = "rustfmt";
172 let dir = std::env::current_dir()?;
173 let args = &["--version"];
176 println!("{}", format_command(&program, &dir, args));
179 let output = Command::new(&program).current_dir(&dir).args(args.iter()).output()?;
181 if output.status.success() {
183 } else if std::str::from_utf8(&output.stderr)
185 .starts_with("error: 'rustfmt' is not installed")
187 Err(CliError::RustfmtNotInstalled)
189 Err(CliError::CommandFailed(
190 format_command(&program, &dir, args),
191 std::str::from_utf8(&output.stderr).unwrap_or("").to_string(),
196 fn rustfmt(context: &FmtContext, paths: impl Iterator<Item = OsString>) -> Result<bool, CliError> {
197 let mut args = Vec::new();
199 args.push(OsString::from("--check"));
203 let success = exec(context, "rustfmt", std::env::current_dir()?, &args)?;