1use super::*;
2
3#[inline]
13pub fn detect_format_kind(path: &Path) -> FileFormatKind {
14 let Some(name) = path.file_name().and_then(OsStr::to_str) else {
15 return FileFormatKind::Unsupported;
16 };
17 if let Some(&first_byte) = name.as_bytes().first() {
18 match first_byte {
19 FMT_BYTE_DOT => {
20 if FMT_NAME_YAML.contains(&name) {
21 return FileFormatKind::Yaml;
22 }
23 if FMT_NAME_PRESERVE_TABS.contains(&name) {
24 return FileFormatKind::PlainTextPreserveTabs;
25 }
26 if FMT_NAME_PLAIN_TEXT.contains(&name) || name.starts_with(FMT_PREFIX_DOTENV) {
27 return FileFormatKind::PlainText;
28 }
29 }
30 FMT_BYTE_UPPER_D => {
31 if FMT_NAME_PLAIN_TEXT.contains(&name) || name.starts_with(FMT_PREFIX_DOCKERFILE) {
32 return FileFormatKind::PlainText;
33 }
34 }
35 FMT_BYTE_UPPER_L => {
36 if FMT_NAME_PLAIN_TEXT.contains(&name) {
37 return FileFormatKind::PlainText;
38 }
39 }
40 FMT_BYTE_UPPER_M | FMT_BYTE_LOWER_M => {
41 if FMT_NAME_PRESERVE_TABS.contains(&name) {
42 return FileFormatKind::PlainTextPreserveTabs;
43 }
44 }
45 FMT_BYTE_LOWER_C | FMT_BYTE_LOWER_P => {
46 if FMT_NAME_JSON_STRINGIFY.contains(&name) {
47 return FileFormatKind::JsonStringify;
48 }
49 if FMT_NAME_PLAIN_TEXT.contains(&name) {
50 return FileFormatKind::PlainText;
51 }
52 }
53 _ => {}
54 }
55 }
56 let raw_ext: &str = match name.rsplit_once('.') {
57 Some((stem, ext)) if !stem.is_empty() => ext,
58 _ => return FileFormatKind::Unsupported,
59 };
60 let ext_bytes: &[u8] = raw_ext.as_bytes();
61 if ext_bytes.is_empty() || ext_bytes.len() > FMT_EXT_MAX_LEN {
62 return FileFormatKind::Unsupported;
63 }
64 let mut stack_buf: [u8; FMT_EXT_MAX_LEN] = [0u8; FMT_EXT_MAX_LEN];
65 let ext_len: usize = ext_bytes.len();
66 for (dst, &src) in stack_buf[..ext_len].iter_mut().zip(ext_bytes.iter()) {
67 *dst = src.to_ascii_lowercase();
68 }
69 let ext: &str = match from_utf8(&stack_buf[..ext_len]) {
70 Ok(s) => s,
71 Err(_) => return FileFormatKind::Unsupported,
72 };
73 match stack_buf[0] {
74 FMT_BYTE_LOWER_R if ext == FMT_EXT_RUST => FileFormatKind::Rust,
75 FMT_BYTE_LOWER_M => {
76 if FMT_EXT_MARKDOWN.contains(&ext) {
77 FileFormatKind::Markdown
78 } else if FMT_EXT_JAVASCRIPT.contains(&ext) {
79 FileFormatKind::JavaScript
80 } else if FMT_EXT_TYPESCRIPT.contains(&ext) {
81 FileFormatKind::TypeScript
82 } else if FMT_EXT_PLAIN_TEXT.contains(&ext) {
83 FileFormatKind::PlainText
84 } else {
85 FileFormatKind::Unsupported
86 }
87 }
88 FMT_BYTE_LOWER_T => {
89 if FMT_EXT_TOML.contains(&ext) {
90 FileFormatKind::Toml
91 } else if FMT_EXT_TYPESCRIPT.contains(&ext) {
92 FileFormatKind::TypeScript
93 } else if FMT_EXT_TSX.contains(&ext) {
94 FileFormatKind::TypeScriptReact
95 } else if FMT_EXT_PLAIN_TEXT.contains(&ext) {
96 FileFormatKind::PlainText
97 } else {
98 FileFormatKind::Unsupported
99 }
100 }
101 FMT_BYTE_LOWER_Y if FMT_EXT_YAML.contains(&ext) => FileFormatKind::Yaml,
102 FMT_BYTE_LOWER_J => {
103 if FMT_EXT_JSON.contains(&ext) {
104 FileFormatKind::Json
105 } else if FMT_EXT_JSONC.contains(&ext) {
106 FileFormatKind::Jsonc
107 } else if FMT_EXT_JAVASCRIPT.contains(&ext) {
108 FileFormatKind::JavaScript
109 } else {
110 FileFormatKind::Unsupported
111 }
112 }
113 FMT_BYTE_LOWER_C => {
114 if FMT_EXT_CSS.contains(&ext) {
115 FileFormatKind::Css
116 } else if FMT_EXT_JAVASCRIPT.contains(&ext) {
117 FileFormatKind::JavaScript
118 } else if FMT_EXT_TYPESCRIPT.contains(&ext) {
119 FileFormatKind::TypeScript
120 } else if FMT_EXT_JSONC.contains(&ext) {
121 FileFormatKind::Jsonc
122 } else if FMT_EXT_PLAIN_TEXT.contains(&ext) {
123 FileFormatKind::PlainText
124 } else {
125 FileFormatKind::Unsupported
126 }
127 }
128 FMT_BYTE_LOWER_S => {
129 if FMT_EXT_SCSS.contains(&ext) {
130 FileFormatKind::Scss
131 } else if FMT_EXT_PLAIN_TEXT.contains(&ext) {
132 FileFormatKind::PlainText
133 } else {
134 FileFormatKind::Unsupported
135 }
136 }
137 FMT_BYTE_LOWER_L if FMT_EXT_LESS.contains(&ext) => FileFormatKind::Less,
138 FMT_BYTE_LOWER_H if FMT_EXT_HTML.contains(&ext) => FileFormatKind::Html,
139 FMT_BYTE_LOWER_V if FMT_EXT_VUE.contains(&ext) => FileFormatKind::Vue,
140 FMT_BYTE_LOWER_W => {
141 if FMT_EXT_JAVASCRIPT.contains(&ext) {
142 FileFormatKind::JavaScript
143 } else if FMT_EXT_CSS.contains(&ext) {
144 FileFormatKind::Css
145 } else {
146 FileFormatKind::Unsupported
147 }
148 }
149 _ => {
150 if FMT_PLAIN_TEXT_ONLY_FIRST_BYTES.contains(&stack_buf[0])
151 && FMT_EXT_PLAIN_TEXT.contains(&ext)
152 {
153 FileFormatKind::PlainText
154 } else {
155 FileFormatKind::Unsupported
156 }
157 }
158 }
159}
160
161pub fn format_text_by_path(path: &Path, input: &str) -> String {
172 match detect_format_kind(path) {
173 FileFormatKind::Markdown => format_markdown(input),
174 FileFormatKind::Yaml => format_yaml_with_path(input, path),
175 FileFormatKind::Json => format_json(input).unwrap_or_else(|_: io::Error| input.to_string()),
176 FileFormatKind::JsonStringify => {
177 format_json_stringify(input).unwrap_or_else(|_: io::Error| input.to_string())
178 }
179 FileFormatKind::Jsonc => format_jsonc(input),
180 FileFormatKind::Toml => format_toml(input),
181 FileFormatKind::JavaScript => format_javascript_with_path(input, path),
182 FileFormatKind::TypeScript => format_typescript_with_path(input, path),
183 FileFormatKind::TypeScriptReact => format_tsx_with_path(input, path),
184 FileFormatKind::Css => format_css(input),
185 FileFormatKind::Scss => format_scss(input),
186 FileFormatKind::Less => format_less(input),
187 FileFormatKind::Html => format_html_with_path(input, path),
188 FileFormatKind::Vue => format_vue_with_path(input, path),
189 FileFormatKind::PlainText
190 | FileFormatKind::PlainTextPreserveTabs
191 | FileFormatKind::Rust
192 | FileFormatKind::Unsupported => input.to_string(),
193 }
194}
195
196fn format_single_text_file(file_path: &Path, check: bool) -> Result<Option<String>, io::Error> {
207 let original: String = match fs::read_to_string(file_path) {
208 Ok(text) => text,
209 Err(_) => return Ok(None),
210 };
211 let formatted: String = format_text_by_path(file_path, &original);
212 if formatted != original {
213 if !check {
214 fs::write(file_path, formatted)?;
215 }
216 return Ok(Some(file_path.display().to_string()));
217 }
218 Ok(None)
219}
220
221pub fn format_workspace_text_files(
234 root: &Path,
235 check: bool,
236) -> Result<UnifiedFmtReport, io::Error> {
237 let ignore_rules: Vec<PrettierIgnoreRule> = if root.is_dir() {
238 load_prettier_ignore(root)
239 } else {
240 Vec::new()
241 };
242 let mut files: Vec<PathBuf> = Vec::new();
243 collect_text_files(root, root, &ignore_rules, &mut files)?;
244 files.sort();
245 let total_files: usize = files.len();
246 let worker_count: usize = if total_files < FMT_PARALLEL_THRESHOLD {
247 1
248 } else {
249 let scaled: usize = (total_files / FMT_FILES_PER_WORKER).max(1);
250 available_parallelism()
251 .map(|n: NonZeroUsize| n.get())
252 .unwrap_or(1)
253 .min(scaled)
254 .min(total_files)
255 };
256 let mut changed_files: Vec<String> = Vec::new();
257 if worker_count <= 1 {
258 for file_path in &files {
259 if let Some(changed) = format_single_text_file(file_path, check)? {
260 changed_files.push(changed);
261 }
262 }
263 } else {
264 let next_idx: AtomicUsize = AtomicUsize::new(0);
265 let worker_results: Vec<Vec<IndexedFmtOutcome>> = scope(|s: &Scope<'_, '_>| {
266 let mut handles: Vec<ScopedJoinHandle<'_, Vec<IndexedFmtOutcome>>> =
267 Vec::with_capacity(worker_count);
268 for _ in 0..worker_count {
269 let files_ref: &[PathBuf] = &files;
270 let next_ref: &AtomicUsize = &next_idx;
271 handles.push(s.spawn(move || {
272 let mut local: Vec<IndexedFmtOutcome> = Vec::new();
273 loop {
274 let idx: usize = next_ref.fetch_add(1, Ordering::Relaxed);
275 if idx >= files_ref.len() {
276 break;
277 }
278 let res: Result<Option<String>, io::Error> =
279 format_single_text_file(&files_ref[idx], check);
280 if !matches!(res, Ok(None)) {
281 local.push((idx, res));
282 }
283 }
284 local
285 }));
286 }
287 let mut collected: Vec<Vec<IndexedFmtOutcome>> = Vec::with_capacity(worker_count);
288 for handle in handles {
289 if let Ok(part) = handle.join() {
290 collected.push(part);
291 }
292 }
293 collected
294 });
295 let mut merged: Vec<IndexedFmtOutcome> = Vec::new();
296 for part in worker_results {
297 merged.extend(part);
298 }
299 merged.sort_by_key(|(idx, _): &IndexedFmtOutcome| *idx);
300 for (_, res) in merged {
301 if let Some(changed) = res? {
302 changed_files.push(changed);
303 }
304 }
305 }
306 let formatted_count: usize = changed_files.len();
307 let report: UnifiedFmtReport =
308 UnifiedFmtReport::new(total_files, formatted_count, check, changed_files);
309 if check && report.get_files_formatted() > 0 {
310 return Err(io::Error::other(format!(
311 "{ERROR_TEXT_FMT_CHECK_FAILED}: {}",
312 report.get_changed_files().join(", ")
313 )));
314 }
315 Ok(report)
316}
317
318pub async fn execute_unified_fmt(root: &Path, check: bool) -> Result<UnifiedFmtReport, io::Error> {
331 let (workspace_root, manifest_path): (PathBuf, PathBuf) = if root.is_file() {
332 let parent: PathBuf = root
333 .parent()
334 .filter(|p: &&Path| !p.as_os_str().is_empty())
335 .map(Path::to_path_buf)
336 .unwrap_or_else(|| PathBuf::from("."));
337 (parent, root.to_path_buf())
338 } else {
339 (root.to_path_buf(), root.join(CARGO_TOML))
340 };
341 let report: UnifiedFmtReport = format_workspace_text_files(&workspace_root, check)?;
342 if manifest_path.exists() {
343 let manifest_str: String = manifest_path.display().to_string();
344 if !check {
345 format_derive_attributes(&manifest_str).await?;
346 }
347 run_cargo_fmt(Some(&manifest_str), check).await?;
348 }
349 Ok(report)
350}
351
352#[inline(always)]
362fn is_active_text_format(kind: FileFormatKind) -> bool {
363 !matches!(
364 kind,
365 FileFormatKind::Rust
366 | FileFormatKind::PlainText
367 | FileFormatKind::PlainTextPreserveTabs
368 | FileFormatKind::Unsupported
369 )
370}
371
372fn collect_text_files(
385 root: &Path,
386 path: &Path,
387 ignore_rules: &[PrettierIgnoreRule],
388 out: &mut Vec<PathBuf>,
389) -> Result<(), io::Error> {
390 if path.is_file() {
391 let kind: FileFormatKind = detect_format_kind(path);
392 if is_active_text_format(kind) {
393 out.push(path.to_path_buf());
394 }
395 return Ok(());
396 }
397 if !path.is_dir() {
398 return Ok(());
399 }
400 collect_text_files_in_dir(root, path, ignore_rules, out)
401}
402
403fn collect_text_files_in_dir(
416 root: &Path,
417 dir: &Path,
418 ignore_rules: &[PrettierIgnoreRule],
419 out: &mut Vec<PathBuf>,
420) -> Result<(), io::Error> {
421 let has_ignore: bool = !ignore_rules.is_empty();
422 for entry_res in fs::read_dir(dir)? {
423 let entry: DirEntry = entry_res?;
424 let file_type: FileType = entry.file_type()?;
425 if file_type.is_symlink() {
426 continue;
427 }
428 if file_type.is_dir() {
429 let name_os: OsString = entry.file_name();
430 if let Some(name) = name_os.to_str()
431 && FMT_SKIP_DIRS.contains(&name)
432 {
433 continue;
434 }
435 let child: PathBuf = entry.path();
436 if has_ignore {
437 let rel_posix: Cow<'_, str> = to_relative_posix(root, &child);
438 if is_prettier_ignored(&rel_posix, true, ignore_rules) {
439 continue;
440 }
441 }
442 collect_text_files_in_dir(root, &child, ignore_rules, out)?;
443 } else if file_type.is_file() {
444 let child: PathBuf = entry.path();
445 let kind: FileFormatKind = detect_format_kind(&child);
446 if !is_active_text_format(kind) {
447 continue;
448 }
449 if has_ignore {
450 let rel_posix: Cow<'_, str> = to_relative_posix(root, &child);
451 if is_prettier_ignored(&rel_posix, false, ignore_rules) {
452 continue;
453 }
454 }
455 out.push(child);
456 }
457 }
458 Ok(())
459}
460
461fn load_prettier_ignore(root: &Path) -> Vec<PrettierIgnoreRule> {
471 let ignore_path: PathBuf = root.join(FMT_PRETTIER_IGNORE_FILE);
472 let content: String = match fs::read_to_string(&ignore_path) {
473 Ok(text) => text,
474 Err(_) => return Vec::new(),
475 };
476 let mut rules: Vec<PrettierIgnoreRule> = Vec::new();
477 for raw_line in normalize_line_endings(&content).split(TEXT_LF) {
478 let trimmed: &str = raw_line.trim();
479 if trimmed.is_empty() || trimmed.starts_with('#') {
480 continue;
481 }
482 let (negated, after_bang): (bool, &str) = match trimmed.strip_prefix('!') {
483 Some(rest) => (true, rest),
484 None => (false, trimmed),
485 };
486 let (dir_only, after_slash): (bool, &str) = match after_bang.strip_suffix('/') {
487 Some(rest) => (true, rest),
488 None => (false, after_bang),
489 };
490 let (leading_slash, body): (bool, &str) = match after_slash.strip_prefix('/') {
491 Some(rest) => (true, rest),
492 None => (false, after_slash),
493 };
494 if body.is_empty() {
495 continue;
496 }
497 let anchored: bool = leading_slash || body.contains('/');
498 rules.push(PrettierIgnoreRule::new(
499 body.to_string(),
500 negated,
501 dir_only,
502 anchored,
503 ));
504 }
505 rules
506}
507
508#[inline(always)]
519fn to_relative_posix<'a>(root: &Path, child: &'a Path) -> Cow<'a, str> {
520 let rel: &'a Path = child.strip_prefix(root).unwrap_or(child);
521 let lossy: Cow<'a, str> = rel.to_string_lossy();
522 if lossy.contains('\\') {
523 Cow::Owned(lossy.replace('\\', "/"))
524 } else {
525 lossy
526 }
527}
528
529fn is_prettier_ignored(rel_path: &str, is_dir: bool, rules: &[PrettierIgnoreRule]) -> bool {
541 if rules.is_empty() || rel_path.is_empty() {
542 return false;
543 }
544 let mut ignored: bool = false;
545 for rule in rules {
546 if rule_matches_path(rule, rel_path, is_dir) {
547 ignored = !rule.get_negated();
548 }
549 }
550 ignored
551}
552
553fn rule_matches_path(rule: &PrettierIgnoreRule, rel_path: &str, is_dir: bool) -> bool {
565 let pattern: &str = rule.get_pattern();
566 let anchored: bool = rule.get_anchored();
567 if rule.get_negated() {
568 if rule.get_dir_only() && !is_dir {
569 return false;
570 }
571 return match_pattern_against(pattern, anchored, rel_path);
572 }
573 if (!rule.get_dir_only() || is_dir) && match_pattern_against(pattern, anchored, rel_path) {
574 return true;
575 }
576 let mut cursor: usize = 0;
577 while let Some(pos) = rel_path[cursor..].find('/') {
578 let dir_prefix: &str = &rel_path[..(cursor + pos)];
579 if match_pattern_against(pattern, anchored, dir_prefix) {
580 return true;
581 }
582 cursor += pos + 1;
583 }
584 false
585}
586
587#[inline(always)]
599fn match_pattern_against(pattern: &str, anchored: bool, rel_path: &str) -> bool {
600 if anchored {
601 return glob_match_path(pattern.as_bytes(), rel_path.as_bytes());
602 }
603 let base: &str = rel_path.rsplit('/').next().unwrap_or(rel_path);
604 glob_match_path(pattern.as_bytes(), base.as_bytes())
605}
606
607fn glob_match_dp(pat: &[u8], text: &[u8], prev: &mut [bool], curr: &mut [bool]) -> bool {
620 let plen: usize = pat.len();
621 let tlen: usize = text.len();
622 prev[0] = true;
623 let mut pi: usize = 0;
624 let mut use_prev: bool = true;
625 while pi < plen {
626 let (src, dst): (&[bool], &mut [bool]) = if use_prev {
627 (&prev[..=tlen], &mut curr[..=tlen])
628 } else {
629 (&curr[..=tlen], &mut prev[..=tlen])
630 };
631 dst.fill(false);
632 if (pi == 0 || pat[pi - 1] == FMT_GLOB_SLASH)
633 && pi + 2 < plen
634 && pat[pi] == FMT_GLOB_STAR
635 && pat[pi + 1] == FMT_GLOB_STAR
636 && pat[pi + 2] == FMT_GLOB_SLASH
637 {
638 let mut seen: bool = false;
639 for ti in 0..=tlen {
640 if src[ti] {
641 dst[ti] = true;
642 seen = true;
643 }
644 if seen && ti < tlen && text[ti] == FMT_GLOB_SLASH {
645 dst[ti + 1] = true;
646 }
647 }
648 pi += 3;
649 } else if pat[pi] == FMT_GLOB_STAR && pi + 1 < plen && pat[pi + 1] == FMT_GLOB_STAR {
650 let mut seen: bool = false;
651 for ti in 0..=tlen {
652 if src[ti] {
653 seen = true;
654 }
655 dst[ti] = seen;
656 }
657 pi += 2;
658 } else if pat[pi] == FMT_GLOB_STAR {
659 for ti in 0..=tlen {
660 if src[ti] || (ti > 0 && dst[ti - 1] && text[ti - 1] != FMT_GLOB_SLASH) {
661 dst[ti] = true;
662 }
663 }
664 pi += 1;
665 } else if pat[pi] == FMT_GLOB_QUESTION {
666 for ti in 1..=tlen {
667 if src[ti - 1] && text[ti - 1] != FMT_GLOB_SLASH {
668 dst[ti] = true;
669 }
670 }
671 pi += 1;
672 } else {
673 let expected: u8 = pat[pi];
674 for ti in 1..=tlen {
675 if src[ti - 1] && text[ti - 1] == expected {
676 dst[ti] = true;
677 }
678 }
679 pi += 1;
680 }
681 use_prev = !use_prev;
682 }
683 if use_prev { prev[tlen] } else { curr[tlen] }
684}
685
686fn glob_match_path(pat: &[u8], text: &[u8]) -> bool {
697 if !pat.contains(&FMT_GLOB_STAR) && !pat.contains(&FMT_GLOB_QUESTION) {
698 return pat == text;
699 }
700 let tlen: usize = text.len();
701 if tlen < FMT_GLOB_STACK_CAP {
702 let mut prev: [bool; FMT_GLOB_STACK_CAP] = [false; FMT_GLOB_STACK_CAP];
703 let mut curr: [bool; FMT_GLOB_STACK_CAP] = [false; FMT_GLOB_STACK_CAP];
704 return glob_match_dp(pat, text, &mut prev[..=tlen], &mut curr[..=tlen]);
705 }
706 let mut prev: Vec<bool> = vec![false; tlen + 1];
707 let mut curr: Vec<bool> = vec![false; tlen + 1];
708 glob_match_dp(pat, text, &mut prev, &mut curr)
709}
710
711#[inline(always)]
722fn cmp_trait_lowercase(a: &str, b: &str) -> cmp::Ordering {
723 if a.is_ascii() && b.is_ascii() {
724 let ab: &[u8] = a.as_bytes();
725 let bb: &[u8] = b.as_bytes();
726 let min_len: usize = ab.len().min(bb.len());
727 for i in 0..min_len {
728 let ord: cmp::Ordering = ab[i].to_ascii_lowercase().cmp(&bb[i].to_ascii_lowercase());
729 if ord != cmp::Ordering::Equal {
730 return ord;
731 }
732 }
733 return ab.len().cmp(&bb.len());
734 }
735 a.chars()
736 .flat_map(char::to_lowercase)
737 .cmp(b.chars().flat_map(char::to_lowercase))
738}
739
740fn sort_derive_in_line(line: &str) -> Option<String> {
750 let captures: Captures<'_> = DERIVE_REGEX.captures(line)?;
751 let content_match: Match<'_> = captures.get(1)?;
752 let derive_content: &str = content_match.as_str();
753 let mut traits: Vec<&str> = derive_content
754 .split(',')
755 .map(str::trim)
756 .filter(|s: &&str| !s.is_empty())
757 .collect();
758 traits.sort_by(|a: &&str, b: &&str| cmp_trait_lowercase(a, b));
759 let mut sorted_traits: String = String::with_capacity(derive_content.len());
760 for (idx, tr) in traits.iter().enumerate() {
761 if idx > 0 {
762 sorted_traits.push_str(", ");
763 }
764 sorted_traits.push_str(tr);
765 }
766 if sorted_traits == derive_content {
767 return None;
768 }
769 let mut result: String = String::with_capacity(line.len() + sorted_traits.len());
770 result.push_str(&line[..content_match.start()]);
771 result.push_str(&sorted_traits);
772 result.push_str(&line[content_match.end()..]);
773 Some(result)
774}
775
776async fn format_derive_in_file(file_path: &Path) -> Result<bool, io::Error> {
786 let content: String = read_to_string(file_path).await?;
787 if !content.contains(DERIVE_PREFIX) {
788 return Ok(false);
789 }
790 let mut modified: bool = false;
791 let mut new_content: Option<String> = None;
792 let mut seen_lines: Vec<&str> = Vec::new();
793 for line in content.lines() {
794 let trimmed: &str = line.trim();
795 if trimmed.starts_with(DERIVE_PREFIX)
796 && let Some(sorted) = sort_derive_in_line(line)
797 {
798 modified = true;
799 let buf: &mut String = new_content.get_or_insert_with(|| {
800 let mut s: String = String::with_capacity(content.len() + 16);
801 for prev in &seen_lines {
802 s.push_str(prev);
803 s.push(TEXT_LF);
804 }
805 s
806 });
807 buf.push_str(&sorted);
808 buf.push(TEXT_LF);
809 continue;
810 }
811 if let Some(ref mut buf) = new_content {
812 buf.push_str(line);
813 buf.push(TEXT_LF);
814 } else {
815 seen_lines.push(line);
816 }
817 }
818 if modified && let Some(updated) = new_content {
819 write(file_path, updated).await?;
820 }
821 Ok(modified)
822}
823
824async fn find_rust_files(manifest_path: &Path) -> Result<Vec<PathBuf>, io::Error> {
834 let mut files: Vec<PathBuf> = Vec::new();
835 let workspace_root: &Path = manifest_path.parent().unwrap_or(Path::new("."));
836 let src_dir: PathBuf = workspace_root.join("src");
837 if src_dir.exists() {
838 find_rust_files_in_dir(&src_dir, &mut files).await?;
839 }
840 let content: String = read_to_string(manifest_path).await?;
841 if let Ok(doc) = from_str::<Value>(&content)
842 && let Some(workspace) = doc.get(TOML_WORKSPACE)
843 && let Some(members) = workspace
844 .get(TOML_MEMBERS)
845 .and_then(|m: &Value| m.as_array())
846 {
847 for member in members {
848 if let Some(pattern) = member.as_str() {
849 let member_src: PathBuf = workspace_root.join(pattern).join("src");
850 if member_src.exists() {
851 find_rust_files_in_dir(&member_src, &mut files).await?;
852 }
853 }
854 }
855 }
856 Ok(files)
857}
858
859async fn find_rust_files_in_dir(dir: &Path, files: &mut Vec<PathBuf>) -> Result<(), io::Error> {
870 let mut entries: ReadDir = read_dir(dir).await?;
871 while let Some(entry) = entries.next_entry().await? {
872 let file_type: FileType = entry.file_type().await?;
873 let path: PathBuf = entry.path();
874 if file_type.is_file()
875 && path
876 .extension()
877 .is_some_and(|ext: &OsStr| ext == FMT_EXT_RUST)
878 {
879 files.push(path);
880 } else if file_type.is_dir() {
881 Box::pin(find_rust_files_in_dir(&path, files)).await?;
882 }
883 }
884 Ok(())
885}
886
887async fn format_derive_attributes(manifest_path: &str) -> Result<(), io::Error> {
897 let path: &Path = Path::new(manifest_path);
898 let files: Vec<PathBuf> = find_rust_files(path).await?;
899 let modified_count: Arc<AtomicUsize> = Arc::new(AtomicUsize::new(0));
900 let mut handles: Vec<JoinHandle<Result<(), io::Error>>> = Vec::with_capacity(files.len());
901 for file in files {
902 let counter: Arc<AtomicUsize> = Arc::clone(&modified_count);
903 let handle: JoinHandle<Result<(), io::Error>> = spawn(async move {
904 if format_derive_in_file(&file).await? {
905 counter.fetch_add(1, Ordering::Relaxed);
906 }
907 Ok(())
908 });
909 handles.push(handle);
910 }
911 for handle in handles {
912 handle.await??;
913 }
914 let count: usize = modified_count.load(Ordering::Relaxed);
915 if count > 0 {
916 log::info!("Sorted derive attributes in {count} files");
917 }
918 Ok(())
919}
920
921async fn run_cargo_fmt(manifest_path: Option<&str>, check: bool) -> Result<(), io::Error> {
932 let mut cmd: Command = Command::new(CARGO);
933 cmd.arg(CARGO_FMT);
934 if check {
935 cmd.arg(CLI_FLAG_CHECK);
936 }
937 if let Some(manifest) = manifest_path {
938 cmd.arg(CLI_FLAG_MANIFEST_PATH).arg(manifest);
939 }
940 cmd.stdout(Stdio::piped()).stderr(Stdio::piped());
941 let output: Output = cmd.output().await?;
942 let stdout: String = String::from_utf8_lossy(&output.stdout).trim().to_string();
943 let stderr: String = String::from_utf8_lossy(&output.stderr).trim().to_string();
944 if !stdout.is_empty() {
945 for line in stdout.lines() {
946 log::info!("{line}");
947 }
948 }
949 if !stderr.is_empty() {
950 if output.status.success() {
951 for line in stderr.lines() {
952 if line.is_empty() {
953 continue;
954 }
955 log::info!("{line}");
956 }
957 } else {
958 for line in stderr.lines() {
959 if line.is_empty() {
960 continue;
961 }
962 log::error!("{line}");
963 }
964 }
965 }
966 if !output.status.success() {
967 return Err(io::Error::other(ERROR_FMT_FAILED));
968 }
969 Ok(())
970}
971
972fn is_cargo_clippy_installed() -> bool {
978 which(CARGO_CLIPPY).is_ok()
979}
980
981async fn install_cargo_clippy() -> Result<(), io::Error> {
987 log::warn!("cargo-clippy not found, installing...");
988 let output: Output = Command::new(RUSTUP)
989 .arg(RUSTUP_COMPONENT)
990 .arg("add")
991 .arg(CLIPPY)
992 .stdout(Stdio::piped())
993 .stderr(Stdio::piped())
994 .output()
995 .await?;
996 let stdout: String = String::from_utf8_lossy(&output.stdout).trim().to_string();
997 let stderr: String = String::from_utf8_lossy(&output.stderr).trim().to_string();
998 if !stdout.is_empty() {
999 for line in stdout.lines() {
1000 log::info!("{line}");
1001 }
1002 }
1003 if !stderr.is_empty() {
1004 if output.status.success() {
1005 for line in stderr.lines() {
1006 if line.is_empty() {
1007 continue;
1008 }
1009 log::info!("{line}");
1010 }
1011 } else {
1012 for line in stderr.lines() {
1013 if line.is_empty() {
1014 continue;
1015 }
1016 log::error!("{line}");
1017 }
1018 }
1019 }
1020 if !output.status.success() {
1021 return Err(io::Error::other(ERROR_CLIPPY_INSTALL_FAILED));
1022 }
1023 Ok(())
1024}
1025
1026async fn execute_clippy_fix(args: &Args) -> Result<(), io::Error> {
1036 if !is_cargo_clippy_installed() {
1037 install_cargo_clippy().await?;
1038 }
1039 let mut cmd: Command = Command::new(CARGO);
1040 cmd.arg(CLIPPY)
1041 .arg(CLI_FLAG_FIX)
1042 .arg(CLI_FLAG_WORKSPACE)
1043 .arg(CLI_FLAG_ALL_TARGETS)
1044 .arg(CLI_FLAG_ALLOW_DIRTY);
1045 if let Some(ref manifest_path) = args.manifest_path {
1046 cmd.arg(CLI_FLAG_MANIFEST_PATH).arg(manifest_path);
1047 }
1048 cmd.stdout(Stdio::piped()).stderr(Stdio::piped());
1049 let output: Output = cmd.output().await?;
1050 let stdout: String = String::from_utf8_lossy(&output.stdout).trim().to_string();
1051 let stderr: String = String::from_utf8_lossy(&output.stderr).trim().to_string();
1052 if !stdout.is_empty() {
1053 for line in stdout.lines() {
1054 log::info!("{line}");
1055 }
1056 }
1057 if !stderr.is_empty() {
1058 if output.status.success() {
1059 for line in stderr.lines() {
1060 if line.is_empty() {
1061 continue;
1062 }
1063 log::info!("{line}");
1064 }
1065 } else {
1066 for line in stderr.lines() {
1067 if line.is_empty() {
1068 continue;
1069 }
1070 log::error!("{line}");
1071 }
1072 }
1073 }
1074 if !output.status.success() {
1075 return Err(io::Error::other(ERROR_CLIPPY_FIX_FAILED));
1076 }
1077 Ok(())
1078}
1079
1080pub async fn execute_fmt(args: &Args) -> Result<(), io::Error> {
1090 let manifest_path: String = args
1091 .manifest_path
1092 .clone()
1093 .unwrap_or_else(|| CARGO_TOML.to_string());
1094 let manifest: &Path = Path::new(&manifest_path);
1095 let workspace_root: &Path = manifest
1096 .parent()
1097 .filter(|p: &&Path| !p.as_os_str().is_empty())
1098 .unwrap_or(Path::new("."));
1099 let report: UnifiedFmtReport = format_workspace_text_files(workspace_root, args.check)?;
1100 if report.get_files_formatted() > 0 {
1101 log::info!(
1102 "Formatted {} text files (scanned {})",
1103 report.get_files_formatted(),
1104 report.get_files_scanned()
1105 );
1106 }
1107 if !args.check {
1108 format_derive_attributes(&manifest_path).await?;
1109 }
1110 run_cargo_fmt(args.manifest_path.as_deref(), args.check).await?;
1111 if !args.check {
1112 execute_clippy_fix(args).await?;
1113 }
1114 Ok(())
1115}
1116
1117pub async fn format_path(path: &Path) -> Result<(), io::Error> {
1127 let kind: FileFormatKind = detect_format_kind(path);
1128 if path.is_file() && kind != FileFormatKind::Rust {
1129 if is_active_text_format(kind) {
1130 let _: UnifiedFmtReport = format_workspace_text_files(path, false)?;
1131 }
1132 return Ok(());
1133 }
1134 if path.is_dir() {
1135 let _: UnifiedFmtReport = format_workspace_text_files(path, false)?;
1136 }
1137 let mut cmd: Command = Command::new(CARGO);
1138 cmd.arg(CARGO_FMT).arg("--").arg(path);
1139 cmd.stdout(Stdio::null()).stderr(Stdio::null());
1140 let _: ExitStatus = cmd.status().await?;
1141 Ok(())
1142}