1use 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_JSON_STRINGIFY.contains(&name) {
15 return FileFormatKind::JsonStringify;
16 }
17 if FMT_NAME_YAML.contains(&name) {
18 return FileFormatKind::Yaml;
19 }
20 if FMT_NAME_PRESERVE_TABS.contains(&name) {
21 return FileFormatKind::PlainTextPreserveTabs;
22 }
23 if FMT_NAME_PLAIN_TEXT.contains(&name)
24 || name.starts_with(FMT_PREFIX_DOCKERFILE)
25 || name.starts_with(FMT_PREFIX_DOTENV)
26 {
27 return FileFormatKind::PlainText;
28 }
29 }
30 let ext_lower: String = match path.extension().and_then(OsStr::to_str) {
31 Some(ext) => ext.to_ascii_lowercase(),
32 None => return FileFormatKind::Unsupported,
33 };
34 let ext: &str = ext_lower.as_str();
35 if ext == FMT_EXT_RUST {
36 return FileFormatKind::Rust;
37 }
38 if FMT_EXT_MARKDOWN.contains(&ext) {
39 return FileFormatKind::Markdown;
40 }
41 if FMT_EXT_YAML.contains(&ext) {
42 return FileFormatKind::Yaml;
43 }
44 if FMT_EXT_JSONC.contains(&ext) {
45 return FileFormatKind::Jsonc;
46 }
47 if FMT_EXT_JSON.contains(&ext) {
48 return FileFormatKind::Json;
49 }
50 if FMT_EXT_TOML.contains(&ext) {
51 return FileFormatKind::Toml;
52 }
53 if FMT_EXT_JAVASCRIPT.contains(&ext) {
54 return FileFormatKind::JavaScript;
55 }
56 if FMT_EXT_TYPESCRIPT.contains(&ext) {
57 return FileFormatKind::TypeScript;
58 }
59 if FMT_EXT_TSX.contains(&ext) {
60 return FileFormatKind::TypeScriptReact;
61 }
62 if FMT_EXT_CSS.contains(&ext) {
63 return FileFormatKind::Css;
64 }
65 if FMT_EXT_SCSS.contains(&ext) {
66 return FileFormatKind::Scss;
67 }
68 if FMT_EXT_LESS.contains(&ext) {
69 return FileFormatKind::Less;
70 }
71 if FMT_EXT_HTML.contains(&ext) {
72 return FileFormatKind::Html;
73 }
74 if FMT_EXT_VUE.contains(&ext) {
75 return FileFormatKind::Vue;
76 }
77 if FMT_EXT_PLAIN_TEXT.contains(&ext) {
78 return FileFormatKind::PlainText;
79 }
80 FileFormatKind::Unsupported
81}
82
83pub fn format_text_by_path(path: &Path, input: &str) -> String {
94 match detect_format_kind(path) {
95 FileFormatKind::Markdown => format_markdown(input),
96 FileFormatKind::Yaml => format_yaml_with_path(input, path),
97 FileFormatKind::Json => format_json(input).unwrap_or_else(|_: io::Error| input.to_string()),
98 FileFormatKind::JsonStringify => {
99 format_json_stringify(input).unwrap_or_else(|_: io::Error| input.to_string())
100 }
101 FileFormatKind::Jsonc => format_jsonc(input),
102 FileFormatKind::Toml => format_toml(input),
103 FileFormatKind::JavaScript => format_javascript_with_path(input, path),
104 FileFormatKind::TypeScript => format_typescript_with_path(input, path),
105 FileFormatKind::TypeScriptReact => format_tsx_with_path(input, path),
106 FileFormatKind::Css => format_css(input),
107 FileFormatKind::Scss => format_scss(input),
108 FileFormatKind::Less => format_less(input),
109 FileFormatKind::Html => format_html_with_path(input, path),
110 FileFormatKind::Vue => format_vue_with_path(input, path),
111 FileFormatKind::PlainText
112 | FileFormatKind::PlainTextPreserveTabs
113 | FileFormatKind::Rust
114 | FileFormatKind::Unsupported => input.to_string(),
115 }
116}
117
118pub fn format_workspace_text_files(
129 root: &Path,
130 check: bool,
131) -> Result<UnifiedFmtReport, io::Error> {
132 let ignore_rules: Vec<PrettierIgnoreRule> = if root.is_dir() {
133 load_prettier_ignore(root)
134 } else {
135 Vec::new()
136 };
137 let mut files: Vec<PathBuf> = Vec::new();
138 collect_text_files(root, root, true, &ignore_rules, &mut files)?;
139 files.sort();
140 let mut report: UnifiedFmtReport = UnifiedFmtReport::new(files.len(), 0, check, Vec::new());
141 for file_path in files {
142 let original: String = match fs::read_to_string(&file_path) {
143 Ok(text) => text,
144 Err(_) => continue,
145 };
146 let formatted: String = format_text_by_path(&file_path, &original);
147 if formatted != original {
148 let next_count: usize = report.get_files_formatted() + 1;
149 let _: &mut UnifiedFmtReport = report.set_files_formatted(next_count);
150 report
151 .get_mut_changed_files()
152 .push(file_path.display().to_string());
153 if !check {
154 fs::write(&file_path, formatted)?;
155 }
156 }
157 }
158 if check && report.get_files_formatted() > 0 {
159 return Err(io::Error::other(format!(
160 "{ERROR_TEXT_FMT_CHECK_FAILED}: {}",
161 report.get_changed_files().join(", ")
162 )));
163 }
164 Ok(report)
165}
166
167pub async fn execute_unified_fmt(root: &Path, check: bool) -> Result<UnifiedFmtReport, io::Error> {
180 let (workspace_root, manifest_path): (PathBuf, PathBuf) = if root.is_file() {
181 let parent: PathBuf = root
182 .parent()
183 .filter(|p: &&Path| !p.as_os_str().is_empty())
184 .map(Path::to_path_buf)
185 .unwrap_or_else(|| PathBuf::from("."));
186 (parent, root.to_path_buf())
187 } else {
188 (root.to_path_buf(), root.join(CARGO_TOML))
189 };
190 let report: UnifiedFmtReport = format_workspace_text_files(&workspace_root, check)?;
191 if manifest_path.exists() {
192 let manifest_str: String = manifest_path.display().to_string();
193 if !check {
194 format_derive_attributes(&manifest_str).await?;
195 }
196 run_cargo_fmt(Some(&manifest_str), check).await?;
197 }
198 Ok(report)
199}
200
201fn is_active_text_format(kind: FileFormatKind) -> bool {
211 !matches!(
212 kind,
213 FileFormatKind::Rust
214 | FileFormatKind::PlainText
215 | FileFormatKind::PlainTextPreserveTabs
216 | FileFormatKind::Unsupported
217 )
218}
219
220fn collect_text_files(
234 root: &Path,
235 path: &Path,
236 is_root: bool,
237 ignore_rules: &[PrettierIgnoreRule],
238 out: &mut Vec<PathBuf>,
239) -> Result<(), io::Error> {
240 if path.is_file() {
241 let kind: FileFormatKind = detect_format_kind(path);
242 if is_active_text_format(kind) {
243 out.push(path.to_path_buf());
244 }
245 return Ok(());
246 }
247 if !path.is_dir() {
248 return Ok(());
249 }
250 if !is_root
251 && let Some(name) = path.file_name().and_then(OsStr::to_str)
252 && FMT_SKIP_DIRS.contains(&name)
253 {
254 return Ok(());
255 }
256 for entry_res in fs::read_dir(path)? {
257 let entry: DirEntry = entry_res?;
258 let file_type: FileType = entry.file_type()?;
259 if file_type.is_symlink() {
260 continue;
261 }
262 let child: PathBuf = entry.path();
263 let rel_posix: String = to_relative_posix(root, &child);
264 if file_type.is_dir() {
265 if is_prettier_ignored(&rel_posix, true, ignore_rules) {
266 continue;
267 }
268 collect_text_files(root, &child, false, ignore_rules, out)?;
269 } else if file_type.is_file() {
270 if is_prettier_ignored(&rel_posix, false, ignore_rules) {
271 continue;
272 }
273 let kind: FileFormatKind = detect_format_kind(&child);
274 if is_active_text_format(kind) {
275 out.push(child);
276 }
277 }
278 }
279 Ok(())
280}
281
282fn load_prettier_ignore(root: &Path) -> Vec<PrettierIgnoreRule> {
292 let ignore_path: PathBuf = root.join(FMT_PRETTIER_IGNORE_FILE);
293 let content: String = match fs::read_to_string(&ignore_path) {
294 Ok(text) => text,
295 Err(_) => return Vec::new(),
296 };
297 let mut rules: Vec<PrettierIgnoreRule> = Vec::new();
298 for raw_line in normalize_line_endings(&content).split(TEXT_LF) {
299 let trimmed: &str = raw_line.trim();
300 if trimmed.is_empty() || trimmed.starts_with('#') {
301 continue;
302 }
303 let (negated, after_bang): (bool, &str) = match trimmed.strip_prefix('!') {
304 Some(rest) => (true, rest),
305 None => (false, trimmed),
306 };
307 let (dir_only, after_slash): (bool, &str) = match after_bang.strip_suffix('/') {
308 Some(rest) => (true, rest),
309 None => (false, after_bang),
310 };
311 let (leading_slash, body): (bool, &str) = match after_slash.strip_prefix('/') {
312 Some(rest) => (true, rest),
313 None => (false, after_slash),
314 };
315 if body.is_empty() {
316 continue;
317 }
318 let anchored: bool = leading_slash || body.contains('/');
319 rules.push(PrettierIgnoreRule::new(
320 body.to_string(),
321 negated,
322 dir_only,
323 anchored,
324 ));
325 }
326 rules
327}
328
329fn to_relative_posix(root: &Path, child: &Path) -> String {
340 let rel: &Path = child.strip_prefix(root).unwrap_or(child);
341 rel.to_string_lossy().replace('\\', "/")
342}
343
344fn is_prettier_ignored(rel_path: &str, is_dir: bool, rules: &[PrettierIgnoreRule]) -> bool {
356 if rules.is_empty() || rel_path.is_empty() {
357 return false;
358 }
359 let mut ignored: bool = false;
360 for rule in rules {
361 if rule_matches_path(rule, rel_path, is_dir) {
362 ignored = !rule.get_negated();
363 }
364 }
365 ignored
366}
367
368fn rule_matches_path(rule: &PrettierIgnoreRule, rel_path: &str, is_dir: bool) -> bool {
380 let pattern: &str = rule.get_pattern();
381 let anchored: bool = rule.get_anchored();
382 if rule.get_negated() {
383 if rule.get_dir_only() && !is_dir {
384 return false;
385 }
386 return match_pattern_against(pattern, anchored, rel_path);
387 }
388 if (!rule.get_dir_only() || is_dir) && match_pattern_against(pattern, anchored, rel_path) {
389 return true;
390 }
391 let mut cursor: usize = 0;
392 while let Some(pos) = rel_path[cursor..].find('/') {
393 let dir_prefix: &str = &rel_path[..(cursor + pos)];
394 if match_pattern_against(pattern, anchored, dir_prefix) {
395 return true;
396 }
397 cursor += pos + 1;
398 }
399 false
400}
401
402fn match_pattern_against(pattern: &str, anchored: bool, rel_path: &str) -> bool {
414 if anchored {
415 return glob_match_path(pattern.as_bytes(), rel_path.as_bytes());
416 }
417 let base: &str = rel_path.rsplit('/').next().unwrap_or(rel_path);
418 glob_match_path(pattern.as_bytes(), base.as_bytes())
419}
420
421fn glob_match_path(pat: &[u8], text: &[u8]) -> bool {
432 let plen: usize = pat.len();
433 let tlen: usize = text.len();
434 let mut prev: Vec<bool> = vec![false; tlen + 1];
435 let mut curr: Vec<bool> = vec![false; tlen + 1];
436 prev[0] = true;
437 let mut pi: usize = 0;
438 while pi < plen {
439 curr.fill(false);
440 if (pi == 0 || pat[pi - 1] == b'/')
441 && pi + 2 < plen
442 && pat[pi] == b'*'
443 && pat[pi + 1] == b'*'
444 && pat[pi + 2] == b'/'
445 {
446 let mut seen: bool = false;
447 for ti in 0..=tlen {
448 if prev[ti] {
449 curr[ti] = true;
450 seen = true;
451 }
452 if seen && ti < tlen && text[ti] == b'/' {
453 curr[ti + 1] = true;
454 }
455 }
456 pi += 3;
457 } else if pat[pi] == b'*' && pi + 1 < plen && pat[pi + 1] == b'*' {
458 let mut seen: bool = false;
459 for ti in 0..=tlen {
460 if prev[ti] {
461 seen = true;
462 }
463 curr[ti] = seen;
464 }
465 pi += 2;
466 } else if pat[pi] == b'*' {
467 for ti in 0..=tlen {
468 if prev[ti] || (ti > 0 && curr[ti - 1] && text[ti - 1] != b'/') {
469 curr[ti] = true;
470 }
471 }
472 pi += 1;
473 } else if pat[pi] == b'?' {
474 for ti in 1..=tlen {
475 if prev[ti - 1] && text[ti - 1] != b'/' {
476 curr[ti] = true;
477 }
478 }
479 pi += 1;
480 } else {
481 let expected: u8 = pat[pi];
482 for ti in 1..=tlen {
483 if prev[ti - 1] && text[ti - 1] == expected {
484 curr[ti] = true;
485 }
486 }
487 pi += 1;
488 }
489 prev.clone_from(&curr);
490 }
491 prev[tlen]
492}
493
494fn sort_derive_in_line(line: &str) -> Option<String> {
504 let captures: Captures<'_> = DERIVE_REGEX.captures(line)?;
505 let derive_content: &str = captures.get(1)?.as_str();
506 let mut traits: Vec<String> = derive_content
507 .split(',')
508 .map(|s: &str| s.trim().to_string())
509 .filter(|s: &String| !s.is_empty())
510 .collect();
511 traits.sort_by_key(|a: &String| a.to_lowercase());
512 let sorted_traits: String = traits.join(", ");
513 let result: String = line.replace(derive_content, &sorted_traits);
514 Some(result)
515}
516
517async fn format_derive_in_file(file_path: &Path) -> Result<bool, io::Error> {
527 let content: String = read_to_string(file_path).await?;
528 let lines: Lines<'_> = content.lines();
529 let mut modified: bool = false;
530 let mut new_content: String = String::new();
531 for line in lines {
532 let trimmed: &str = line.trim();
533 let new_line: String = if trimmed.starts_with(DERIVE_PREFIX) {
534 if let Some(sorted) = sort_derive_in_line(line) {
535 if sorted != line {
536 modified = true;
537 }
538 sorted
539 } else {
540 line.to_string()
541 }
542 } else {
543 line.to_string()
544 };
545 new_content.push_str(&new_line);
546 new_content.push('\n');
547 }
548 if modified {
549 write(file_path, new_content).await?;
550 }
551 Ok(modified)
552}
553
554async fn find_rust_files(manifest_path: &Path) -> Result<Vec<PathBuf>, io::Error> {
564 let mut files: Vec<PathBuf> = Vec::new();
565 let workspace_root: &Path = manifest_path.parent().unwrap_or(Path::new("."));
566 let src_dir: PathBuf = workspace_root.join("src");
567 if src_dir.exists() {
568 find_rust_files_in_dir(&src_dir, &mut files).await?;
569 }
570 let content: String = read_to_string(manifest_path).await?;
571 if let Ok(doc) = from_str::<Value>(&content)
572 && let Some(workspace) = doc.get(TOML_WORKSPACE)
573 && let Some(members) = workspace
574 .get(TOML_MEMBERS)
575 .and_then(|m: &Value| m.as_array())
576 {
577 for member in members {
578 if let Some(pattern) = member.as_str() {
579 let member_src: PathBuf = workspace_root.join(pattern).join("src");
580 if member_src.exists() {
581 find_rust_files_in_dir(&member_src, &mut files).await?;
582 }
583 }
584 }
585 }
586 Ok(files)
587}
588
589async fn find_rust_files_in_dir(dir: &Path, files: &mut Vec<PathBuf>) -> Result<(), io::Error> {
600 let mut entries: ReadDir = read_dir(dir).await?;
601 while let Some(entry) = entries.next_entry().await? {
602 let path: PathBuf = entry.path();
603 if path.is_file()
604 && path
605 .extension()
606 .is_some_and(|ext: &OsStr| ext == FMT_EXT_RUST)
607 {
608 files.push(path);
609 } else if path.is_dir() {
610 Box::pin(find_rust_files_in_dir(&path, files)).await?;
611 }
612 }
613 Ok(())
614}
615
616async fn format_derive_attributes(manifest_path: &str) -> Result<(), io::Error> {
626 let path: &Path = Path::new(manifest_path);
627 let files: Vec<PathBuf> = find_rust_files(path).await?;
628 let modified_count: Arc<Mutex<usize>> = Arc::new(Mutex::new(0));
629 let mut handles: Vec<JoinHandle<Result<(), io::Error>>> = Vec::new();
630 for file in files {
631 let counter: Arc<Mutex<usize>> = Arc::clone(&modified_count);
632 let handle: JoinHandle<Result<(), io::Error>> = spawn(async move {
633 if format_derive_in_file(&file).await? {
634 let mut count: MutexGuard<'_, usize> = counter.lock().await;
635 *count += 1;
636 }
637 Ok(())
638 });
639 handles.push(handle);
640 }
641 for handle in handles {
642 handle.await??;
643 }
644 let count: usize = *modified_count.lock().await;
645 if count > 0 {
646 log::info!("Sorted derive attributes in {count} files");
647 }
648 Ok(())
649}
650
651async fn run_cargo_fmt(manifest_path: Option<&str>, check: bool) -> Result<(), io::Error> {
662 let mut cmd: Command = Command::new(CARGO);
663 cmd.arg(CARGO_FMT);
664 if check {
665 cmd.arg(CLI_FLAG_CHECK);
666 }
667 if let Some(manifest) = manifest_path {
668 cmd.arg(CLI_FLAG_MANIFEST_PATH).arg(manifest);
669 }
670 cmd.stdout(Stdio::piped()).stderr(Stdio::piped());
671 let output: Output = cmd.output().await?;
672 let stdout: String = String::from_utf8_lossy(&output.stdout).trim().to_string();
673 let stderr: String = String::from_utf8_lossy(&output.stderr).trim().to_string();
674 if !stdout.is_empty() {
675 for line in stdout.lines() {
676 log::info!("{line}");
677 }
678 }
679 if !stderr.is_empty() {
680 if output.status.success() {
681 for line in stderr.lines() {
682 if line.is_empty() {
683 continue;
684 }
685 log::info!("{line}");
686 }
687 } else {
688 for line in stderr.lines() {
689 if line.is_empty() {
690 continue;
691 }
692 log::error!("{line}");
693 }
694 }
695 }
696 if !output.status.success() {
697 return Err(io::Error::other(ERROR_FMT_FAILED));
698 }
699 Ok(())
700}
701
702fn is_cargo_clippy_installed() -> bool {
708 which(CARGO_CLIPPY).is_ok()
709}
710
711async fn install_cargo_clippy() -> Result<(), io::Error> {
717 log::warn!("cargo-clippy not found, installing...");
718 let output: Output = Command::new(RUSTUP)
719 .arg(RUSTUP_COMPONENT)
720 .arg("add")
721 .arg(CLIPPY)
722 .stdout(Stdio::piped())
723 .stderr(Stdio::piped())
724 .output()
725 .await?;
726 let stdout: String = String::from_utf8_lossy(&output.stdout).trim().to_string();
727 let stderr: String = String::from_utf8_lossy(&output.stderr).trim().to_string();
728 if !stdout.is_empty() {
729 for line in stdout.lines() {
730 log::info!("{line}");
731 }
732 }
733 if !stderr.is_empty() {
734 if output.status.success() {
735 for line in stderr.lines() {
736 if line.is_empty() {
737 continue;
738 }
739 log::info!("{line}");
740 }
741 } else {
742 for line in stderr.lines() {
743 if line.is_empty() {
744 continue;
745 }
746 log::error!("{line}");
747 }
748 }
749 }
750 if !output.status.success() {
751 return Err(io::Error::other(ERROR_CLIPPY_INSTALL_FAILED));
752 }
753 Ok(())
754}
755
756async fn execute_clippy_fix(args: &Args) -> Result<(), io::Error> {
766 if !is_cargo_clippy_installed() {
767 install_cargo_clippy().await?;
768 }
769 let mut cmd: Command = Command::new(CARGO);
770 cmd.arg(CLIPPY)
771 .arg(CLI_FLAG_FIX)
772 .arg(CLI_FLAG_WORKSPACE)
773 .arg(CLI_FLAG_ALL_TARGETS)
774 .arg(CLI_FLAG_ALLOW_DIRTY);
775 if let Some(ref manifest_path) = args.manifest_path {
776 cmd.arg(CLI_FLAG_MANIFEST_PATH).arg(manifest_path);
777 }
778 cmd.stdout(Stdio::piped()).stderr(Stdio::piped());
779 let output: Output = cmd.output().await?;
780 let stdout: String = String::from_utf8_lossy(&output.stdout).trim().to_string();
781 let stderr: String = String::from_utf8_lossy(&output.stderr).trim().to_string();
782 if !stdout.is_empty() {
783 for line in stdout.lines() {
784 log::info!("{line}");
785 }
786 }
787 if !stderr.is_empty() {
788 if output.status.success() {
789 for line in stderr.lines() {
790 if line.is_empty() {
791 continue;
792 }
793 log::info!("{line}");
794 }
795 } else {
796 for line in stderr.lines() {
797 if line.is_empty() {
798 continue;
799 }
800 log::error!("{line}");
801 }
802 }
803 }
804 if !output.status.success() {
805 return Err(io::Error::other(ERROR_CLIPPY_FIX_FAILED));
806 }
807 Ok(())
808}
809
810pub async fn execute_fmt(args: &Args) -> Result<(), io::Error> {
820 let manifest_path: String = args
821 .manifest_path
822 .clone()
823 .unwrap_or_else(|| CARGO_TOML.to_string());
824 let manifest: &Path = Path::new(&manifest_path);
825 let workspace_root: &Path = manifest
826 .parent()
827 .filter(|p: &&Path| !p.as_os_str().is_empty())
828 .unwrap_or(Path::new("."));
829 let report: UnifiedFmtReport = format_workspace_text_files(workspace_root, args.check)?;
830 if report.get_files_formatted() > 0 {
831 log::info!(
832 "Formatted {} text files (scanned {})",
833 report.get_files_formatted(),
834 report.get_files_scanned()
835 );
836 }
837 if !args.check {
838 format_derive_attributes(&manifest_path).await?;
839 }
840 run_cargo_fmt(args.manifest_path.as_deref(), args.check).await?;
841 if !args.check {
842 execute_clippy_fix(args).await?;
843 }
844 Ok(())
845}
846
847pub async fn format_path(path: &Path) -> Result<(), io::Error> {
857 let kind: FileFormatKind = detect_format_kind(path);
858 if path.is_file() && kind != FileFormatKind::Rust {
859 if is_active_text_format(kind) {
860 let _: UnifiedFmtReport = format_workspace_text_files(path, false)?;
861 }
862 return Ok(());
863 }
864 if path.is_dir() {
865 let _: UnifiedFmtReport = format_workspace_text_files(path, false)?;
866 }
867 let mut cmd: Command = Command::new(CARGO);
868 cmd.arg(CARGO_FMT).arg("--").arg(path);
869 cmd.stdout(Stdio::null()).stderr(Stdio::null());
870 let _: ExitStatus = cmd.status().await?;
871 Ok(())
872}