crate_cli/fmt/driver/
fn.rs1use super::*;
2
3pub fn detect_format_kind(path: &Path) -> FileFormatKind {
13 if let Some(name) = path.file_name().and_then(OsStr::to_str) {
14 if FMT_NAME_PRESERVE_TABS.contains(&name) {
15 return FileFormatKind::PlainTextPreserveTabs;
16 }
17 if FMT_NAME_PLAIN_TEXT.contains(&name) {
18 return FileFormatKind::PlainText;
19 }
20 }
21 let ext_lower: String = match path.extension().and_then(OsStr::to_str) {
22 Some(ext) => ext.to_ascii_lowercase(),
23 None => return FileFormatKind::Unsupported,
24 };
25 let ext: &str = ext_lower.as_str();
26 if ext == FMT_EXT_RUST {
27 return FileFormatKind::Rust;
28 }
29 if FMT_EXT_MARKDOWN.contains(&ext) {
30 return FileFormatKind::Markdown;
31 }
32 if FMT_EXT_YAML.contains(&ext) {
33 return FileFormatKind::Yaml;
34 }
35 if FMT_EXT_JSON.contains(&ext) {
36 return FileFormatKind::Json;
37 }
38 if FMT_EXT_JSONC.contains(&ext) {
39 return FileFormatKind::Jsonc;
40 }
41 if FMT_EXT_TOML.contains(&ext) {
42 return FileFormatKind::Toml;
43 }
44 if FMT_EXT_PLAIN_TEXT.contains(&ext) {
45 return FileFormatKind::PlainText;
46 }
47 FileFormatKind::Unsupported
48}
49
50pub fn format_text_by_path(path: &Path, input: &str) -> String {
61 match detect_format_kind(path) {
62 FileFormatKind::Markdown => format_markdown(input),
63 FileFormatKind::Yaml => format_yaml(input),
64 FileFormatKind::Json => {
65 format_json(input).unwrap_or_else(|_: io::Error| format_jsonc(input))
66 }
67 FileFormatKind::Jsonc => format_jsonc(input),
68 FileFormatKind::Toml => format_toml(input),
69 FileFormatKind::PlainText => format_plain_text(input, false),
70 FileFormatKind::PlainTextPreserveTabs => format_plain_text(input, true),
71 FileFormatKind::Rust | FileFormatKind::Unsupported => input.to_string(),
72 }
73}
74
75pub fn format_workspace_text_files(
86 root: &Path,
87 check: bool,
88) -> Result<UnifiedFmtReport, io::Error> {
89 let mut files: Vec<PathBuf> = Vec::new();
90 collect_text_files(root, true, &mut files)?;
91 files.sort();
92 let mut report: UnifiedFmtReport = UnifiedFmtReport::new(files.len(), 0, check, Vec::new());
93 for file_path in files {
94 let original: String = match fs::read_to_string(&file_path) {
95 Ok(text) => text,
96 Err(_) => continue,
97 };
98 let formatted: String = format_text_by_path(&file_path, &original);
99 if formatted != original {
100 let next_count: usize = report.get_files_formatted() + 1;
101 let _: &mut UnifiedFmtReport = report.set_files_formatted(next_count);
102 report
103 .get_mut_changed_files()
104 .push(file_path.display().to_string());
105 if !check {
106 fs::write(&file_path, formatted)?;
107 }
108 }
109 }
110 if check && report.get_files_formatted() > 0 {
111 return Err(io::Error::other(format!(
112 "{ERROR_TEXT_FMT_CHECK_FAILED}: {}",
113 report.get_changed_files().join(", ")
114 )));
115 }
116 Ok(report)
117}
118
119pub async fn execute_unified_fmt(root: &Path, check: bool) -> Result<UnifiedFmtReport, io::Error> {
132 let (workspace_root, manifest_path): (PathBuf, PathBuf) = if root.is_file() {
133 let parent: PathBuf = root
134 .parent()
135 .map(Path::to_path_buf)
136 .unwrap_or_else(|| PathBuf::from("."));
137 (parent, root.to_path_buf())
138 } else {
139 (root.to_path_buf(), root.join(CARGO_TOML))
140 };
141 let report: UnifiedFmtReport = format_workspace_text_files(&workspace_root, check)?;
142 if manifest_path.exists() {
143 let manifest_str: String = manifest_path.display().to_string();
144 if !check {
145 format_derive_attributes(&manifest_str).await?;
146 }
147 run_cargo_fmt(Some(&manifest_str), check).await?;
148 }
149 Ok(report)
150}
151
152fn collect_text_files(path: &Path, is_root: bool, out: &mut Vec<PathBuf>) -> Result<(), io::Error> {
164 if path.is_file() {
165 let kind: FileFormatKind = detect_format_kind(path);
166 if !matches!(kind, FileFormatKind::Rust | FileFormatKind::Unsupported) {
167 out.push(path.to_path_buf());
168 }
169 return Ok(());
170 }
171 if !path.is_dir() {
172 return Ok(());
173 }
174 if !is_root
175 && let Some(name) = path.file_name().and_then(OsStr::to_str)
176 && FMT_SKIP_DIRS.contains(&name)
177 {
178 return Ok(());
179 }
180 for entry_res in fs::read_dir(path)? {
181 let entry: DirEntry = entry_res?;
182 let child: PathBuf = entry.path();
183 if child.is_dir() {
184 collect_text_files(&child, false, out)?;
185 } else if child.is_file() {
186 let kind: FileFormatKind = detect_format_kind(&child);
187 if !matches!(kind, FileFormatKind::Rust | FileFormatKind::Unsupported) {
188 out.push(child);
189 }
190 }
191 }
192 Ok(())
193}
194
195fn sort_derive_in_line(line: &str) -> Option<String> {
205 let captures: Captures<'_> = DERIVE_REGEX.captures(line)?;
206 let derive_content: &str = captures.get(1)?.as_str();
207 let mut traits: Vec<String> = derive_content
208 .split(',')
209 .map(|s: &str| s.trim().to_string())
210 .filter(|s: &String| !s.is_empty())
211 .collect();
212 traits.sort_by_key(|a: &String| a.to_lowercase());
213 let sorted_traits: String = traits.join(", ");
214 let result: String = line.replace(derive_content, &sorted_traits);
215 Some(result)
216}
217
218async fn format_derive_in_file(file_path: &Path) -> Result<bool, io::Error> {
228 let content: String = read_to_string(file_path).await?;
229 let lines: Lines<'_> = content.lines();
230 let mut modified: bool = false;
231 let mut new_content: String = String::new();
232 for line in lines {
233 let trimmed: &str = line.trim();
234 let new_line: String = if trimmed.starts_with(DERIVE_PREFIX) {
235 if let Some(sorted) = sort_derive_in_line(line) {
236 if sorted != line {
237 modified = true;
238 }
239 sorted
240 } else {
241 line.to_string()
242 }
243 } else {
244 line.to_string()
245 };
246 new_content.push_str(&new_line);
247 new_content.push('\n');
248 }
249 if modified {
250 write(file_path, new_content).await?;
251 }
252 Ok(modified)
253}
254
255async fn find_rust_files(manifest_path: &Path) -> Result<Vec<PathBuf>, io::Error> {
265 let mut files: Vec<PathBuf> = Vec::new();
266 let workspace_root: &Path = manifest_path.parent().unwrap_or(Path::new("."));
267 let src_dir: PathBuf = workspace_root.join("src");
268 if src_dir.exists() {
269 find_rust_files_in_dir(&src_dir, &mut files).await?;
270 }
271 let content: String = read_to_string(manifest_path).await?;
272 if let Ok(doc) = from_str::<Value>(&content)
273 && let Some(workspace) = doc.get(TOML_WORKSPACE)
274 && let Some(members) = workspace
275 .get(TOML_MEMBERS)
276 .and_then(|m: &Value| m.as_array())
277 {
278 for member in members {
279 if let Some(pattern) = member.as_str() {
280 let member_src: PathBuf = workspace_root.join(pattern).join("src");
281 if member_src.exists() {
282 find_rust_files_in_dir(&member_src, &mut files).await?;
283 }
284 }
285 }
286 }
287 Ok(files)
288}
289
290async fn find_rust_files_in_dir(dir: &Path, files: &mut Vec<PathBuf>) -> Result<(), io::Error> {
301 let mut entries: ReadDir = read_dir(dir).await?;
302 while let Some(entry) = entries.next_entry().await? {
303 let path: PathBuf = entry.path();
304 if path.is_file()
305 && path
306 .extension()
307 .is_some_and(|ext: &OsStr| ext == FMT_EXT_RUST)
308 {
309 files.push(path);
310 } else if path.is_dir() {
311 Box::pin(find_rust_files_in_dir(&path, files)).await?;
312 }
313 }
314 Ok(())
315}
316
317async fn format_derive_attributes(manifest_path: &str) -> Result<(), io::Error> {
327 let path: &Path = Path::new(manifest_path);
328 let files: Vec<PathBuf> = find_rust_files(path).await?;
329 let modified_count: Arc<Mutex<usize>> = Arc::new(Mutex::new(0));
330 let mut handles: Vec<JoinHandle<Result<(), io::Error>>> = Vec::new();
331 for file in files {
332 let counter: Arc<Mutex<usize>> = Arc::clone(&modified_count);
333 let handle: JoinHandle<Result<(), io::Error>> = spawn(async move {
334 if format_derive_in_file(&file).await? {
335 let mut count: MutexGuard<'_, usize> = counter.lock().await;
336 *count += 1;
337 }
338 Ok(())
339 });
340 handles.push(handle);
341 }
342 for handle in handles {
343 handle.await??;
344 }
345 let count: usize = *modified_count.lock().await;
346 if count > 0 {
347 log::info!("Sorted derive attributes in {count} files");
348 }
349 Ok(())
350}
351
352async fn run_cargo_fmt(manifest_path: Option<&str>, check: bool) -> Result<(), io::Error> {
363 let mut cmd: Command = Command::new(CARGO);
364 cmd.arg(CARGO_FMT);
365 if check {
366 cmd.arg(CLI_FLAG_CHECK);
367 }
368 if let Some(manifest) = manifest_path {
369 cmd.arg(CLI_FLAG_MANIFEST_PATH).arg(manifest);
370 }
371 cmd.stdout(Stdio::piped()).stderr(Stdio::piped());
372 let output: Output = cmd.output().await?;
373 let stdout: String = String::from_utf8_lossy(&output.stdout).trim().to_string();
374 let stderr: String = String::from_utf8_lossy(&output.stderr).trim().to_string();
375 if !stdout.is_empty() {
376 for line in stdout.lines() {
377 log::info!("{line}");
378 }
379 }
380 if !stderr.is_empty() {
381 if output.status.success() {
382 for line in stderr.lines() {
383 if line.is_empty() {
384 continue;
385 }
386 log::info!("{line}");
387 }
388 } else {
389 for line in stderr.lines() {
390 if line.is_empty() {
391 continue;
392 }
393 log::error!("{line}");
394 }
395 }
396 }
397 if !output.status.success() {
398 return Err(io::Error::other(ERROR_FMT_FAILED));
399 }
400 Ok(())
401}
402
403fn is_cargo_clippy_installed() -> bool {
409 which(CARGO_CLIPPY).is_ok()
410}
411
412async fn install_cargo_clippy() -> Result<(), io::Error> {
418 log::warn!("cargo-clippy not found, installing...");
419 let output: Output = Command::new(RUSTUP)
420 .arg(RUSTUP_COMPONENT)
421 .arg("add")
422 .arg(CLIPPY)
423 .stdout(Stdio::piped())
424 .stderr(Stdio::piped())
425 .output()
426 .await?;
427 let stdout: String = String::from_utf8_lossy(&output.stdout).trim().to_string();
428 let stderr: String = String::from_utf8_lossy(&output.stderr).trim().to_string();
429 if !stdout.is_empty() {
430 for line in stdout.lines() {
431 log::info!("{line}");
432 }
433 }
434 if !stderr.is_empty() {
435 if output.status.success() {
436 for line in stderr.lines() {
437 if line.is_empty() {
438 continue;
439 }
440 log::info!("{line}");
441 }
442 } else {
443 for line in stderr.lines() {
444 if line.is_empty() {
445 continue;
446 }
447 log::error!("{line}");
448 }
449 }
450 }
451 if !output.status.success() {
452 return Err(io::Error::other(ERROR_CLIPPY_INSTALL_FAILED));
453 }
454 Ok(())
455}
456
457async fn execute_clippy_fix(args: &Args) -> Result<(), io::Error> {
467 if !is_cargo_clippy_installed() {
468 install_cargo_clippy().await?;
469 }
470 let mut cmd: Command = Command::new(CARGO);
471 cmd.arg(CLIPPY)
472 .arg(CLI_FLAG_FIX)
473 .arg(CLI_FLAG_WORKSPACE)
474 .arg(CLI_FLAG_ALL_TARGETS)
475 .arg(CLI_FLAG_ALLOW_DIRTY);
476 if let Some(ref manifest_path) = args.manifest_path {
477 cmd.arg(CLI_FLAG_MANIFEST_PATH).arg(manifest_path);
478 }
479 cmd.stdout(Stdio::piped()).stderr(Stdio::piped());
480 let output: Output = cmd.output().await?;
481 let stdout: String = String::from_utf8_lossy(&output.stdout).trim().to_string();
482 let stderr: String = String::from_utf8_lossy(&output.stderr).trim().to_string();
483 if !stdout.is_empty() {
484 for line in stdout.lines() {
485 log::info!("{line}");
486 }
487 }
488 if !stderr.is_empty() {
489 if output.status.success() {
490 for line in stderr.lines() {
491 if line.is_empty() {
492 continue;
493 }
494 log::info!("{line}");
495 }
496 } else {
497 for line in stderr.lines() {
498 if line.is_empty() {
499 continue;
500 }
501 log::error!("{line}");
502 }
503 }
504 }
505 if !output.status.success() {
506 return Err(io::Error::other(ERROR_CLIPPY_FIX_FAILED));
507 }
508 Ok(())
509}
510
511pub async fn execute_fmt(args: &Args) -> Result<(), io::Error> {
521 let manifest_path: String = args
522 .manifest_path
523 .clone()
524 .unwrap_or_else(|| CARGO_TOML.to_string());
525 let manifest: &Path = Path::new(&manifest_path);
526 let workspace_root: &Path = manifest
527 .parent()
528 .filter(|p: &&Path| !p.as_os_str().is_empty())
529 .unwrap_or(Path::new("."));
530 let report: UnifiedFmtReport = format_workspace_text_files(workspace_root, args.check)?;
531 if report.get_files_formatted() > 0 {
532 log::info!(
533 "Formatted {} text files (scanned {})",
534 report.get_files_formatted(),
535 report.get_files_scanned()
536 );
537 }
538 if !args.check {
539 format_derive_attributes(&manifest_path).await?;
540 }
541 run_cargo_fmt(args.manifest_path.as_deref(), args.check).await?;
542 if !args.check {
543 execute_clippy_fix(args).await?;
544 }
545 Ok(())
546}
547
548pub async fn format_path(path: &Path) -> Result<(), io::Error> {
558 let kind: FileFormatKind = detect_format_kind(path);
559 if path.is_file() && !matches!(kind, FileFormatKind::Rust | FileFormatKind::Unsupported) {
560 let _: UnifiedFmtReport = format_workspace_text_files(path, false)?;
561 return Ok(());
562 }
563 if path.is_dir() {
564 let _: UnifiedFmtReport = format_workspace_text_files(path, false)?;
565 }
566 let mut cmd: Command = Command::new(CARGO);
567 cmd.arg(CARGO_FMT).arg("--").arg(path);
568 cmd.stdout(Stdio::null()).stderr(Stdio::null());
569 let _: ExitStatus = cmd.status().await?;
570 Ok(())
571}