返回 CodeWhale
rust_format.rs
根目录 / crates / engine / src / tools / rust_format.rs
1 //! Post-edit formatting normalization for Rust files (#6205).
2 //!
3 //! Model-generated edits rarely match `rustfmt` output exactly. Once an
4 //! unformatted edit lands, the *next* turn's `old_string` or patch context was
5 //! written against text that `cargo fmt` is about to move, so anchors drift and
6 //! the follow-up edit fails to match. Normalizing at edit time keeps anchors
7 //! stable for the rest of the session, and the tool result returns the
8 //! normalized text, so what the model remembers writing is what is on disk.
9 //!
10 //! `rustfmt` is the formatter, not `prettyplease`: `cargo fmt --check` is this
11 //! repository's actual gate, and a second formatter with its own opinions would
12 //! produce files that pass the edit path and fail the gate. Shelling out also
13 //! picks up the project's own `rustfmt.toml` — an in-process pretty-printer
14 //! cannot.
15 //!
16 //! # Policy
17 //!
18 //! Normalization applies to the whole edited file, and **only when that file
19 //! was already `rustfmt`-clean before the edit**. A file whose formatting the
20 //! author has not handed to `rustfmt` is never rewritten. Because a clean file
21 //! is a formatting fixpoint, reformatting it after an edit can only change the
22 //! edited region — so "whole file" and "edited region" coincide, without
23 //! needing span arithmetic to prove it.
24 //!
25 //! # Known limitations
26 //!
27 //! - **Non-fatal, always.** A missing `rustfmt`, a parse failure, a timeout, or
28 //! a non-zero exit skips normalization; the edit still lands. Nothing here
29 //! can fail an edit.
30 //! - **Silent when skipped.** Only an applied normalization is announced. A
31 //! "formatting skipped" note on every edit in a project without `rustfmt`
32 //! would be noise the model cannot act on, and "skipped" is indistinguishable
33 //! from "would have changed nothing" without running the formatter anyway.
34 //! - **Edition 2024 is assumed.** A file that `rustfmt` cannot parse under that
35 //! edition fails the clean-before check and is skipped, so the assumption
36 //! degrades to "no normalization", never to a mangled file.
37 //! - **CRLF files are skipped.** `rustfmt` emits LF; rewriting every line
38 //! ending is exactly the unrelated-churn this policy exists to avoid.
39
40 use std::path::{Path, PathBuf};
41 use std::process::Stdio;
42 use std::time::Duration;
43
44 use tokio::io::AsyncWriteExt;
45 use tokio::process::Command;
46
47 /// Files larger than this are not normalized. Two formatter runs on a
48 /// multi-megabyte file cost more interactive latency than stable anchors are
49 /// worth.
50 const MAX_FORMATTED_BYTES: usize = 1024 * 1024;
51
52 /// Wall-clock budget for one `rustfmt` run.
53 #[cfg(not(any(test, feature = "test-support")))]
54 const FORMAT_TIMEOUT: Duration = Duration::from_secs(5);
55 /// Unit tests assert that normalization *happens*, not how fast. A loaded
56 /// Windows CI runner has taken over five seconds to start the rustup
57 /// `rustfmt` proxy, which silently skipped normalization and failed the
58 /// assertion. The skip-on-timeout path is unchanged; only the budget is.
59 #[cfg(any(test, feature = "test-support"))]
60 const FORMAT_TIMEOUT: Duration = Duration::from_secs(60);
61
62 /// Suffix appended to an edit summary when the content was normalized, so the
63 /// model knows the returned text is not byte-identical to what it sent.
64 pub(super) const NORMALIZED_NOTE: &str = " (rustfmt-normalized)";
65
66 /// Normalize `after` when the edit landed in an already-`rustfmt`-clean file.
67 ///
68 /// Returns the formatted text to write instead of `after`, or `None` to leave
69 /// `after` exactly as the caller produced it. Every failure path returns
70 /// `None`: normalization is a convenience and may never break an edit.
71 pub(super) async fn normalize_edit(path: &Path, before: &str, after: &str) -> Option<String> {
72 if path.extension()?.to_str()? != "rs" {
73 return None;
74 }
75 if after.len() > MAX_FORMATTED_BYTES || before.len() > MAX_FORMATTED_BYTES {
76 return None;
77 }
78 // Preserving a CRLF file's line endings outranks normalizing its layout.
79 if after.contains('\r') || before.contains('\r') {
80 return None;
81 }
82
83 let formatted = rustfmt(path, after).await?;
84 if formatted == after {
85 // Already canonical. The common case, and it costs one run, not two.
86 return None;
87 }
88 // Only now is the second run worth paying for: was this file the author's
89 // to format, or `rustfmt`'s?
90 if rustfmt(path, before).await? != before {
91 return None;
92 }
93 Some(formatted)
94 }
95
96 /// Find the `rustfmt.toml` governing `path`, walking up to the filesystem root.
97 ///
98 /// `None` means no config file exists, which is the signal to omit
99 /// `--config-path` entirely and let `rustfmt` use its defaults.
100 async fn nearest_config(path: &Path) -> Option<PathBuf> {
101 let mut directory = path.parent()?;
102 loop {
103 for name in ["rustfmt.toml", ".rustfmt.toml"] {
104 let candidate = directory.join(name);
105 if tokio::fs::try_exists(&candidate).await.unwrap_or(false) {
106 return Some(candidate);
107 }
108 }
109 directory = directory.parent()?;
110 }
111 }
112
113 /// Run `rustfmt` over `source`, returning its output, or `None` on any failure.
114 async fn rustfmt(path: &Path, source: &str) -> Option<String> {
115 let path = std::path::absolute(path).ok()?;
116 let mut command = Command::from(codewhale_dependencies::rustup_command(
117 "rustfmt",
118 path.parent(),
119 )?);
120 command
121 .arg("--emit")
122 .arg("stdout")
123 .arg("--edition")
124 .arg("2024")
125 .arg("--quiet");
126 // Pick up the project's own `rustfmt.toml`: with stdin input there is no
127 // file path for `rustfmt` to search upward from. The flag must name a
128 // config file that actually exists — pointed at a directory without one,
129 // `rustfmt` exits 1 with "unable to find a config file", which would
130 // silently disable normalization everywhere.
131 if let Some(config) = nearest_config(&path).await {
132 command.arg("--config-path").arg(config);
133 }
134 let mut child = command
135 .stdin(Stdio::piped())
136 .stdout(Stdio::piped())
137 .stderr(Stdio::null())
138 // A hung formatter must not outlive the edit that spawned it.
139 .kill_on_drop(true)
140 .spawn()
141 .ok()?;
142
143 let mut stdin = child.stdin.take()?;
144 let payload = source.to_string();
145 // Write and wait concurrently: `rustfmt` streams its output, so writing the
146 // whole input before reading can deadlock on a full pipe buffer.
147 let writer = tokio::spawn(async move {
148 let _ = stdin.write_all(payload.as_bytes()).await;
149 let _ = stdin.shutdown().await;
150 });
151
152 let output = match tokio::time::timeout(FORMAT_TIMEOUT, child.wait_with_output()).await {
153 Ok(Ok(output)) => output,
154 // A timed-out child is already killed by dropping the future's handle
155 // on the `wait_with_output` path; either way the edit proceeds.
156 Ok(Err(_)) | Err(_) => {
157 writer.abort();
158 return None;
159 }
160 };
161 writer.abort();
162
163 if !output.status.success() {
164 return None;
165 }
166 String::from_utf8(output.stdout).ok()
167 }
168
169 #[cfg(test)]
170 mod tests {
171 use super::*;
172 use std::path::PathBuf;
173
174 fn rust_path() -> PathBuf {
175 PathBuf::from("src/lib.rs")
176 }
177
178 /// `rustfmt` ships with the toolchain this repository pins (rustup's
179 /// default profile), and `cargo fmt --check` is a standing gate here, so
180 /// its absence is a broken environment, not a reason to skip. A test that
181 /// passes vacuously without the formatter proves nothing — that exact
182 /// hazard hid a `--config-path` bug which disabled normalization
183 /// everywhere while the suite stayed green.
184 async fn require_rustfmt() {
185 assert_eq!(
186 rustfmt(&rust_path(), "fn main( ) {}\n").await.as_deref(),
187 Some("fn main() {}\n"),
188 "rustfmt must be on PATH for the formatting tests"
189 );
190 }
191
192 #[tokio::test]
193 async fn misformatted_edit_in_a_clean_file_is_normalized() {
194 require_rustfmt().await;
195 let before = "fn main() {\n let x = 1;\n}\n";
196 let after = "fn main() {\n let x = 1;\n let y=2;\n}\n";
197 let normalized = normalize_edit(&rust_path(), before, after)
198 .await
199 .expect("a clean file must be renormalized after a sloppy edit");
200 assert_eq!(
201 normalized,
202 "fn main() {\n let x = 1;\n let y = 2;\n}\n"
203 );
204 }
205
206 #[tokio::test]
207 async fn a_file_the_author_formats_by_hand_is_left_alone() {
208 require_rustfmt().await;
209 // `rustfmt` would rewrite this file wholesale, so it was never its to
210 // format: the edit lands verbatim.
211 let before = "fn main() {\n let x = 1;\n}\n";
212 let after = "fn main() {\n let x = 1;\n let y=2;\n}\n";
213 assert!(normalize_edit(&rust_path(), before, after).await.is_none());
214 }
215
216 #[tokio::test]
217 async fn already_canonical_content_needs_no_rewrite() {
218 require_rustfmt().await;
219 let before = "fn main() {\n let x = 1;\n}\n";
220 let after = "fn main() {\n let x = 1;\n let y = 2;\n}\n";
221 assert!(normalize_edit(&rust_path(), before, after).await.is_none());
222 }
223
224 #[tokio::test]
225 async fn crlf_files_keep_their_line_endings() {
226 let before = "fn main() {\r\n let x = 1;\r\n}\r\n";
227 let after = "fn main() {\r\n let x = 1;\r\n}\r\n";
228 assert!(normalize_edit(&rust_path(), before, after).await.is_none());
229 }
230
231 #[tokio::test]
232 async fn non_rust_files_are_not_formatted() {
233 assert!(
234 normalize_edit(Path::new("data.json"), "{}", "{ }")
235 .await
236 .is_none()
237 );
238 }
239
240 #[tokio::test]
241 async fn unparseable_content_degrades_to_no_normalization() {
242 // `rustfmt` cannot parse this; the edit must still be allowed to land.
243 assert!(
244 normalize_edit(&rust_path(), "fn main() {}\n", "fn main( {\n")
245 .await
246 .is_none()
247 );
248 }
249
250 #[cfg(unix)]
251 #[tokio::test(flavor = "current_thread")]
252 async fn formatter_does_not_run_in_or_take_its_toolchain_from_the_workspace() {
253 use crate::test_support::{EnvVarGuard, SealedHome};
254 use std::os::unix::fs::PermissionsExt;
255 let _home = SealedHome::new();
256 let shims = tempfile::tempdir().expect("shims");
257 let seen = shims.path().join("seen");
258 let shim = shims.path().join("rustfmt");
259 std::fs::write(
260 &shim,
261 format!(
262 "#!/bin/sh\nprintf 'cwd=%s toolchain=%s auto=%s' \"$(pwd -P)\" \"${{RUSTUP_TOOLCHAIN-unset}}\" \"${{RUSTUP_AUTO_INSTALL-unset}}\" > '{}'\ncat\n",
263 seen.display()
264 ),
265 )
266 .expect("shim");
267 std::fs::set_permissions(&shim, std::fs::Permissions::from_mode(0o755)).expect("chmod");
268 let _path = EnvVarGuard::set("PATH", format!("{}:/usr/bin:/bin", shims.path().display()));
269 let _no_user_pin = EnvVarGuard::remove("RUSTUP_TOOLCHAIN");
270 let rustup_home = tempfile::tempdir().expect("rustup home");
271 let _rustup_home = EnvVarGuard::set("RUSTUP_HOME", rustup_home.path());
272 let workspace = tempfile::tempdir().expect("workspace");
273 let root = std::fs::canonicalize(workspace.path()).expect("canonical workspace");
274 let file = root.join("src/lib.rs");
275 let run = |pin: &str| {
276 std::fs::write(root.join("rust-toolchain.toml"), pin).expect("toolchain file");
277 let file = file.clone();
278 async move {
279 assert_eq!(
280 rustfmt(&file, "fn main() {}\n").await.as_deref(),
281 Some("fn main() {}\n")
282 );
283 }
284 };
285
286 run("[toolchain]\npath = \"/opt/elsewhere\"\n").await;
287 let recorded = std::fs::read_to_string(&seen).expect("shim ran");
288 assert!(recorded.ends_with("toolchain=unset auto=0"), "{recorded}");
289 assert!(!recorded.contains(root.to_str().unwrap()), "{recorded}");
290
291 run("[toolchain]\nchannel = \"nightly-2026-01-01\"\n").await;
292 let recorded = std::fs::read_to_string(&seen).expect("shim ran");
293 assert!(recorded.ends_with("toolchain=unset auto=0"), "{recorded}");
294
295 std::fs::create_dir_all(
296 rustup_home
297 .path()
298 .join("toolchains/nightly-2026-01-01-host"),
299 )
300 .expect("installed toolchain");
301 run("[toolchain]\nchannel = \"nightly-2026-01-01\"\n").await;
302 let recorded = std::fs::read_to_string(&seen).expect("shim ran");
303 assert!(
304 recorded.ends_with("toolchain=nightly-2026-01-01 auto=0"),
305 "{recorded}"
306 );
307 }
308 }
309
309 lines RUST