Skip to main content

crate_cli/fmt/driver/
fn.rs

1use super::*;
2
3/// Resolves the unified formatting strategy for `path` based on filename and extension matching VS Code `settings.json`.
4///
5/// # Arguments
6///
7/// - `&Path` - File path to classify.
8///
9/// # Returns
10///
11/// - `FileFormatKind` - Matched formatting strategy or `FileFormatKind::Unsupported`.
12#[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
161/// Formats text content in memory according to the file type inferred from `path` matching VS Code save behavior.
162///
163/// # Arguments
164///
165/// - `&Path` - File path used to determine the target formatter.
166/// - `&str` - Raw UTF-8 file content.
167///
168/// # Returns
169///
170/// - `String` - Formatted text content (or unchanged input when no-op, unsupported, or syntactically invalid).
171pub 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
196/// Formats a single file on disk (or checks it in `--check` mode) and returns its display path if changed.
197///
198/// # Arguments
199///
200/// - `&Path` - Target file path.
201/// - `bool` - When `true`, skips writing changes to disk.
202///
203/// # Returns
204///
205/// - `Result<Option<String>, io::Error>` - Changed display path if formatting differed, `None` if unchanged or unreadable as UTF-8, or write error.
206fn 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
221/// Recursively discovers and formats all supported non-Rust text files under `root` (or a single file).
222///
223/// Uses a work-stealing thread pool when scanning multiple files while preserving deterministic sorted output order.
224///
225/// # Arguments
226///
227/// - `&Path` - Root workspace directory or individual file path.
228/// - `bool` - When `true`, verifies formatting without modifying disk and returns an error if changes are needed.
229///
230/// # Returns
231///
232/// - `Result<UnifiedFmtReport, io::Error>` - Structured report of scanned and formatted files.
233pub 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
318/// Executes the unified text and Rust formatting pipeline (all text files, derive sorting, and `cargo fmt`) without clippy-fix.
319///
320/// Designed as the shared first pass called by both `crate fmt` and framework CLIs such as `euv fmt` and `hyperlane fmt`.
321///
322/// # Arguments
323///
324/// - `&Path` - Workspace root directory or Cargo.toml manifest path.
325/// - `bool` - When `true`, checks formatting without writing files.
326///
327/// # Returns
328///
329/// - `Result<UnifiedFmtReport, io::Error>` - Unified text formatting report or error.
330pub 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/// Returns `true` when `kind` has an active non-Rust formatter in VS Code and should be scanned and formatted.
353///
354/// # Arguments
355///
356/// - `FileFormatKind` - Classified file format kind.
357///
358/// # Returns
359///
360/// - `bool` - Whether the file is actively formatted by `format_workspace_text_files`.
361#[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
372/// Entry point collecting actively formatted non-Rust text files beneath `path` (file or directory).
373///
374/// # Arguments
375///
376/// - `&Path` - Workspace root used to compute relative paths for `.prettierignore`.
377/// - `&Path` - Target file or root directory.
378/// - `&[PrettierIgnoreRule]` - Parsed `.prettierignore` rules from the workspace root.
379/// - `&mut Vec<PathBuf>` - Output accumulator.
380///
381/// # Returns
382///
383/// - `Result<(), io::Error>` - Traversal status.
384fn 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
403/// Recursively walks a known directory without redundant `stat` syscalls or unnecessary path string allocations.
404///
405/// # Arguments
406///
407/// - `&Path` - Workspace root used to compute relative paths for `.prettierignore`.
408/// - `&Path` - Current directory to scan.
409/// - `&[PrettierIgnoreRule]` - Parsed `.prettierignore` rules from the workspace root.
410/// - `&mut Vec<PathBuf>` - Output accumulator.
411///
412/// # Returns
413///
414/// - `Result<(), io::Error>` - Traversal status.
415fn 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
461/// Parses `.prettierignore` at `root` if present into gitignore-style matching rules.
462///
463/// # Arguments
464///
465/// - `&Path` - Workspace root directory.
466///
467/// # Returns
468///
469/// - `Vec<PrettierIgnoreRule>` - Ordered list of parsed ignore rules.
470fn 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/// Converts `child` into a forward-slash relative path string rooted at `root` without allocating on Unix UTF-8 paths.
509///
510/// # Arguments
511///
512/// - `&Path` - Base directory path.
513/// - `&'a Path` - Descendant path.
514///
515/// # Returns
516///
517/// - `Cow<'a, str>` - Forward-slash relative path.
518#[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
529/// Evaluates `.prettierignore` rules in order for a relative POSIX path.
530///
531/// # Arguments
532///
533/// - `&str` - Forward-slash relative path from workspace root.
534/// - `bool` - Whether the path refers to a directory.
535/// - `&[PrettierIgnoreRule]` - Ordered ignore rules.
536///
537/// # Returns
538///
539/// - `bool` - `true` when the path should be skipped.
540fn 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
553/// Tests whether a single `.prettierignore` rule matches `rel_path` (checking ancestor directories only for non-negated rules).
554///
555/// # Arguments
556///
557/// - `&PrettierIgnoreRule` - Ignore rule to test.
558/// - `&str` - Forward-slash relative path.
559/// - `bool` - Whether `rel_path` itself is a directory.
560///
561/// # Returns
562///
563/// - `bool` - Whether the rule matches.
564fn 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/// Matches a normalized glob pattern against either the full path (if anchored) or the final path segment.
588///
589/// # Arguments
590///
591/// - `&str` - Normalized glob pattern.
592/// - `bool` - Whether the pattern is anchored to the workspace root.
593/// - `&str` - Relative POSIX path candidate.
594///
595/// # Returns
596///
597/// - `bool` - Whether the glob matches.
598#[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
607/// Runs one DP step of iterative glob matching over mutable `prev` and `curr` slices.
608///
609/// # Arguments
610///
611/// - `&[u8]` - Pattern bytes.
612/// - `&[u8]` - Candidate text bytes.
613/// - `&mut [bool]` - DP previous state row of length `text.len() + 1`.
614/// - `&mut [bool]` - DP current state row of length `text.len() + 1`.
615///
616/// # Returns
617///
618/// - `bool` - Whether `pat` matches `text`.
619fn 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
686/// Iterative glob matcher supporting `*` (non-slash), segment-bounded `**/`, `**` (cross-slash), and `?` (single non-slash char).
687///
688/// # Arguments
689///
690/// - `&[u8]` - Pattern bytes.
691/// - `&[u8]` - Candidate path bytes.
692///
693/// # Returns
694///
695/// - `bool` - `true` when the entire candidate matches the pattern.
696fn 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/// Compares two trait names by lowercase Unicode ordering without heap allocation.
712///
713/// # Arguments
714///
715/// - `&str` - First trait name.
716/// - `&str` - Second trait name.
717///
718/// # Returns
719///
720/// - `cmp::Ordering` - Lexicographical ordering of their lowercased forms.
721#[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
740/// Sort derive traits in a single line without redundant allocations when already sorted.
741///
742/// # Arguments
743///
744/// - `&str` - The line containing derive attribute
745///
746/// # Returns
747///
748/// - `Option<String>` - Sorted line if derive found and changed, None otherwise
749fn 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
776/// Format derive attributes in a file with zero line allocations when no derive line changes.
777///
778/// # Arguments
779///
780/// - `&Path` - Path to the Rust file
781///
782/// # Returns
783///
784/// - `Result<bool, io::Error>` - True if file was modified, false otherwise
785async 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
824/// Find all Rust files in workspace
825///
826/// # Arguments
827///
828/// - `&Path` - Path to Cargo.toml
829///
830/// # Returns
831///
832/// - `Result<Vec<PathBuf>, io::Error>` - List of Rust file paths
833async 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
859/// Recursively find Rust files in directory using `entry.file_type()` to avoid redundant `stat` syscalls.
860///
861/// # Arguments
862///
863/// - `&Path` - Directory to search
864/// - `&mut Vec<PathBuf>` - Vector to collect file paths
865///
866/// # Returns
867///
868/// - `Result<(), io::Error>` - Success or error
869async 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
887/// Format derive attributes in all workspace files
888///
889/// # Arguments
890///
891/// - `&str` - Path to Cargo.toml
892///
893/// # Returns
894///
895/// - `Result<(), io::Error>` - Success or error
896async 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
921/// Runs `cargo fmt` with optional manifest path and `--check` flag.
922///
923/// # Arguments
924///
925/// - `Option<&str>` - Optional `--manifest-path` argument.
926/// - `bool` - Whether to pass `--check`.
927///
928/// # Returns
929///
930/// - `Result<(), io::Error>` - Success or error if `cargo fmt` fails.
931async 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
972/// Check if cargo-clippy is installed
973///
974/// # Returns
975///
976/// - `bool` - True if cargo-clippy is available
977fn is_cargo_clippy_installed() -> bool {
978    which(CARGO_CLIPPY).is_ok()
979}
980
981/// Install cargo-clippy using rustup
982///
983/// # Returns
984///
985/// - `Result<(), io::Error>` - Success or error
986async 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
1026/// Execute clippy fix command
1027///
1028/// # Arguments
1029///
1030/// - `&Args` - The parsed arguments
1031///
1032/// # Returns
1033///
1034/// - `Result<(), io::Error>` - Success or error
1035async 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
1080/// Execute fmt command across all workspace text files and Rust sources.
1081///
1082/// # Arguments
1083///
1084/// - `&Args` - The parsed arguments
1085///
1086/// # Returns
1087///
1088/// - `Result<(), io::Error>` - Success or error
1089pub 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
1117/// Format code or supported text files at a specific path.
1118///
1119/// # Arguments
1120///
1121/// - `&Path` - Path to file or directory to format
1122///
1123/// # Returns
1124///
1125/// - `Result<(), io::Error>` - Success or error
1126pub 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}