]> git.lizzy.rs Git - rust.git/blob - clippy_dev/src/fmt.rs
Rollup merge of #88782 - asquared31415:issue-79559, r=cjgillot
[rust.git] / clippy_dev / src / fmt.rs
1 use crate::clippy_project_root;
2 use shell_escape::escape;
3 use std::ffi::OsStr;
4 use std::path::Path;
5 use std::process::{self, Command};
6 use std::{fs, io};
7 use walkdir::WalkDir;
8
9 #[derive(Debug)]
10 pub enum CliError {
11     CommandFailed(String, String),
12     IoError(io::Error),
13     RustfmtNotInstalled,
14     WalkDirError(walkdir::Error),
15     RaSetupActive,
16 }
17
18 impl From<io::Error> for CliError {
19     fn from(error: io::Error) -> Self {
20         Self::IoError(error)
21     }
22 }
23
24 impl From<walkdir::Error> for CliError {
25     fn from(error: walkdir::Error) -> Self {
26         Self::WalkDirError(error)
27     }
28 }
29
30 struct FmtContext {
31     check: bool,
32     verbose: bool,
33 }
34
35 // the "main" function of cargo dev fmt
36 pub fn run(check: bool, verbose: bool) {
37     fn try_run(context: &FmtContext) -> Result<bool, CliError> {
38         let mut success = true;
39
40         let project_root = clippy_project_root();
41
42         // if we added a local rustc repo as path dependency to clippy for rust analyzer, we do NOT want to
43         // format because rustfmt would also format the entire rustc repo as it is a local
44         // dependency
45         if fs::read_to_string(project_root.join("Cargo.toml"))
46             .expect("Failed to read clippy Cargo.toml")
47             .contains(&"[target.'cfg(NOT_A_PLATFORM)'.dependencies]")
48         {
49             return Err(CliError::RaSetupActive);
50         }
51
52         rustfmt_test(context)?;
53
54         success &= cargo_fmt(context, project_root.as_path())?;
55         success &= cargo_fmt(context, &project_root.join("clippy_dev"))?;
56         success &= cargo_fmt(context, &project_root.join("rustc_tools_util"))?;
57         success &= cargo_fmt(context, &project_root.join("lintcheck"))?;
58
59         for entry in WalkDir::new(project_root.join("tests")) {
60             let entry = entry?;
61             let path = entry.path();
62
63             if path.extension() != Some("rs".as_ref()) || entry.file_name() == "ice-3891.rs" {
64                 continue;
65             }
66
67             success &= rustfmt(context, path)?;
68         }
69
70         Ok(success)
71     }
72
73     fn output_err(err: CliError) {
74         match err {
75             CliError::CommandFailed(command, stderr) => {
76                 eprintln!("error: A command failed! `{}`\nstderr: {}", command, stderr);
77             },
78             CliError::IoError(err) => {
79                 eprintln!("error: {}", err);
80             },
81             CliError::RustfmtNotInstalled => {
82                 eprintln!("error: rustfmt nightly is not installed.");
83             },
84             CliError::WalkDirError(err) => {
85                 eprintln!("error: {}", err);
86             },
87             CliError::RaSetupActive => {
88                 eprintln!(
89                     "error: a local rustc repo is enabled as path dependency via `cargo dev setup intellij`.
90 Not formatting because that would format the local repo as well!
91 Please revert the changes to Cargo.tomls first."
92                 );
93             },
94         }
95     }
96
97     let context = FmtContext { check, verbose };
98     let result = try_run(&context);
99     let code = match result {
100         Ok(true) => 0,
101         Ok(false) => {
102             eprintln!();
103             eprintln!("Formatting check failed.");
104             eprintln!("Run `cargo dev fmt` to update formatting.");
105             1
106         },
107         Err(err) => {
108             output_err(err);
109             1
110         },
111     };
112     process::exit(code);
113 }
114
115 fn format_command(program: impl AsRef<OsStr>, dir: impl AsRef<Path>, args: &[impl AsRef<OsStr>]) -> String {
116     let arg_display: Vec<_> = args.iter().map(|a| escape(a.as_ref().to_string_lossy())).collect();
117
118     format!(
119         "cd {} && {} {}",
120         escape(dir.as_ref().to_string_lossy()),
121         escape(program.as_ref().to_string_lossy()),
122         arg_display.join(" ")
123     )
124 }
125
126 fn exec(
127     context: &FmtContext,
128     program: impl AsRef<OsStr>,
129     dir: impl AsRef<Path>,
130     args: &[impl AsRef<OsStr>],
131 ) -> Result<bool, CliError> {
132     if context.verbose {
133         println!("{}", format_command(&program, &dir, args));
134     }
135
136     let child = Command::new(&program).current_dir(&dir).args(args.iter()).spawn()?;
137     let output = child.wait_with_output()?;
138     let success = output.status.success();
139
140     if !context.check && !success {
141         let stderr = std::str::from_utf8(&output.stderr).unwrap_or("");
142         return Err(CliError::CommandFailed(
143             format_command(&program, &dir, args),
144             String::from(stderr),
145         ));
146     }
147
148     Ok(success)
149 }
150
151 fn cargo_fmt(context: &FmtContext, path: &Path) -> Result<bool, CliError> {
152     let mut args = vec!["+nightly", "fmt", "--all"];
153     if context.check {
154         args.push("--");
155         args.push("--check");
156     }
157     let success = exec(context, "cargo", path, &args)?;
158
159     Ok(success)
160 }
161
162 fn rustfmt_test(context: &FmtContext) -> Result<(), CliError> {
163     let program = "rustfmt";
164     let dir = std::env::current_dir()?;
165     let args = &["+nightly", "--version"];
166
167     if context.verbose {
168         println!("{}", format_command(&program, &dir, args));
169     }
170
171     let output = Command::new(&program).current_dir(&dir).args(args.iter()).output()?;
172
173     if output.status.success() {
174         Ok(())
175     } else if std::str::from_utf8(&output.stderr)
176         .unwrap_or("")
177         .starts_with("error: 'rustfmt' is not installed")
178     {
179         Err(CliError::RustfmtNotInstalled)
180     } else {
181         Err(CliError::CommandFailed(
182             format_command(&program, &dir, args),
183             std::str::from_utf8(&output.stderr).unwrap_or("").to_string(),
184         ))
185     }
186 }
187
188 fn rustfmt(context: &FmtContext, path: &Path) -> Result<bool, CliError> {
189     let mut args = vec!["+nightly".as_ref(), path.as_os_str()];
190     if context.check {
191         args.push("--check".as_ref());
192     }
193     let success = exec(context, "rustfmt", std::env::current_dir()?, &args)?;
194     if !success {
195         eprintln!("rustfmt failed on {}", path.display());
196     }
197     Ok(success)
198 }