Skip to main content

aft/
format.rs

1//! External tool runner and auto-formatter detection.
2//!
3//! Provides subprocess execution with timeout protection, language-to-formatter
4//! mapping, and the `auto_format` entry point used by `write_format_validate`.
5
6use std::collections::{HashMap, HashSet};
7use std::io::ErrorKind;
8use std::path::{Path, PathBuf};
9use std::process::{Command, Stdio};
10use std::sync::Mutex;
11use std::thread;
12use std::time::{Duration, Instant};
13
14use crate::config::Config;
15use crate::parser::{detect_language, LangId};
16
17/// Result of running an external tool subprocess.
18#[derive(Debug)]
19pub struct ExternalToolResult {
20    pub stdout: String,
21    pub stderr: String,
22    pub exit_code: i32,
23}
24
25/// Errors from external tool execution.
26#[derive(Debug)]
27pub enum FormatError {
28    /// The tool binary was not found on PATH.
29    NotFound { tool: String },
30    /// The tool exceeded its timeout and was killed.
31    Timeout { tool: String, timeout_secs: u32 },
32    /// The tool exited with a non-zero status.
33    Failed { tool: String, stderr: String },
34    /// No formatter is configured for this language.
35    UnsupportedLanguage,
36}
37
38/// A configured formatter/checker that cannot be resolved for configure warnings.
39#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
40pub struct MissingTool {
41    pub kind: String,
42    pub language: String,
43    pub tool: String,
44    pub hint: String,
45}
46
47#[derive(Debug, Clone)]
48struct ToolCandidate {
49    tool: String,
50    source: String,
51    args: Vec<String>,
52    required: bool,
53}
54
55#[derive(Debug, Clone)]
56enum ToolDetection {
57    Found(String, Vec<String>),
58    NotConfigured,
59    NotInstalled { tool: String },
60}
61
62impl std::fmt::Display for FormatError {
63    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
64        match self {
65            FormatError::NotFound { tool } => write!(f, "formatter not found: {}", tool),
66            FormatError::Timeout { tool, timeout_secs } => {
67                write!(f, "formatter '{}' timed out after {}s", tool, timeout_secs)
68            }
69            FormatError::Failed { tool, stderr } => {
70                write!(f, "formatter '{}' failed: {}", tool, stderr)
71            }
72            FormatError::UnsupportedLanguage => write!(f, "unsupported language for formatting"),
73        }
74    }
75}
76
77/// Spawn a subprocess and wait for completion with timeout protection.
78///
79/// Polls `try_wait()` at 50ms intervals. On timeout, kills the child process
80/// and waits for it to exit. Returns `FormatError::NotFound` when the binary
81/// isn't on PATH.
82pub fn run_external_tool(
83    command: &str,
84    args: &[&str],
85    working_dir: Option<&Path>,
86    timeout_secs: u32,
87) -> Result<ExternalToolResult, FormatError> {
88    let mut cmd = Command::new(command);
89    cmd.args(args).stdout(Stdio::piped()).stderr(Stdio::piped());
90
91    if let Some(dir) = working_dir {
92        cmd.current_dir(dir);
93    }
94
95    let mut child = match cmd.spawn() {
96        Ok(c) => c,
97        Err(e) if e.kind() == ErrorKind::NotFound => {
98            return Err(FormatError::NotFound {
99                tool: command.to_string(),
100            });
101        }
102        Err(e) => {
103            return Err(FormatError::Failed {
104                tool: command.to_string(),
105                stderr: e.to_string(),
106            });
107        }
108    };
109
110    let deadline = Instant::now() + Duration::from_secs(timeout_secs as u64);
111
112    loop {
113        match child.try_wait() {
114            Ok(Some(status)) => {
115                let stdout = child
116                    .stdout
117                    .take()
118                    .map(|s| std::io::read_to_string(s).unwrap_or_default())
119                    .unwrap_or_default();
120                let stderr = child
121                    .stderr
122                    .take()
123                    .map(|s| std::io::read_to_string(s).unwrap_or_default())
124                    .unwrap_or_default();
125
126                let exit_code = status.code().unwrap_or(-1);
127                if exit_code != 0 {
128                    return Err(FormatError::Failed {
129                        tool: command.to_string(),
130                        stderr,
131                    });
132                }
133
134                return Ok(ExternalToolResult {
135                    stdout,
136                    stderr,
137                    exit_code,
138                });
139            }
140            Ok(None) => {
141                // Still running
142                if Instant::now() >= deadline {
143                    // Kill the process and reap it
144                    let _ = child.kill();
145                    let _ = child.wait();
146                    return Err(FormatError::Timeout {
147                        tool: command.to_string(),
148                        timeout_secs,
149                    });
150                }
151                thread::sleep(Duration::from_millis(50));
152            }
153            Err(e) => {
154                return Err(FormatError::Failed {
155                    tool: command.to_string(),
156                    stderr: format!("try_wait error: {}", e),
157                });
158            }
159        }
160    }
161}
162
163/// TTL for tool availability and resolution cache entries.
164const TOOL_CACHE_TTL: Duration = Duration::from_secs(60);
165
166#[derive(Debug, Clone, PartialEq, Eq, Hash)]
167struct ToolCacheKey {
168    command: String,
169    project_root: PathBuf,
170}
171
172static TOOL_RESOLUTION_CACHE: std::sync::LazyLock<
173    Mutex<HashMap<ToolCacheKey, (Option<PathBuf>, Instant)>>,
174> = std::sync::LazyLock::new(|| Mutex::new(HashMap::new()));
175
176static TOOL_AVAILABILITY_CACHE: std::sync::LazyLock<Mutex<HashMap<String, (bool, Instant)>>> =
177    std::sync::LazyLock::new(|| Mutex::new(HashMap::new()));
178
179fn tool_cache_key(command: &str, project_root: Option<&Path>) -> ToolCacheKey {
180    ToolCacheKey {
181        command: command.to_string(),
182        project_root: project_root.map(Path::to_path_buf).unwrap_or_default(),
183    }
184}
185
186fn availability_cache_key(command: &str, project_root: Option<&Path>) -> String {
187    let root = project_root
188        .map(|path| path.to_string_lossy())
189        .unwrap_or_default();
190    format!("{}\0{}", command, root)
191}
192
193pub fn clear_tool_cache() {
194    if let Ok(mut cache) = TOOL_RESOLUTION_CACHE.lock() {
195        cache.clear();
196    }
197    if let Ok(mut cache) = TOOL_AVAILABILITY_CACHE.lock() {
198        cache.clear();
199    }
200}
201
202/// Resolve a tool by checking node_modules/.bin relative to project_root, then PATH.
203/// Returns the full path to the tool if found, otherwise None.
204fn resolve_tool(command: &str, project_root: Option<&Path>) -> Option<String> {
205    let key = tool_cache_key(command, project_root);
206    if let Ok(cache) = TOOL_RESOLUTION_CACHE.lock() {
207        if let Some((resolved, checked_at)) = cache.get(&key) {
208            if checked_at.elapsed() < TOOL_CACHE_TTL {
209                return resolved
210                    .as_ref()
211                    .map(|path| path.to_string_lossy().to_string());
212            }
213        }
214    }
215
216    let resolved = resolve_tool_uncached(command, project_root);
217    if let Ok(mut cache) = TOOL_RESOLUTION_CACHE.lock() {
218        cache.insert(key, (resolved.clone(), Instant::now()));
219    }
220    resolved.map(|path| path.to_string_lossy().to_string())
221}
222
223fn resolve_tool_uncached(command: &str, project_root: Option<&Path>) -> Option<PathBuf> {
224    // 1. Check node_modules/.bin/<command> relative to project root
225    if let Some(root) = project_root {
226        let local_bin = root.join("node_modules").join(".bin").join(command);
227        if local_bin.exists() {
228            return Some(local_bin);
229        }
230    }
231
232    // 2. Fall back to PATH lookup
233    match Command::new(command)
234        .arg("--version")
235        .stdin(Stdio::null())
236        .stdout(Stdio::null())
237        .stderr(Stdio::null())
238        .spawn()
239    {
240        Ok(mut child) => {
241            let start = Instant::now();
242            let timeout = Duration::from_secs(2);
243            loop {
244                match child.try_wait() {
245                    Ok(Some(status)) => {
246                        return if status.success() {
247                            Some(PathBuf::from(command))
248                        } else {
249                            None
250                        };
251                    }
252                    Ok(None) if start.elapsed() > timeout => {
253                        let _ = child.kill();
254                        let _ = child.wait();
255                        return None;
256                    }
257                    Ok(None) => thread::sleep(Duration::from_millis(50)),
258                    Err(_) => return None,
259                }
260            }
261        }
262        Err(_) => None,
263    }
264}
265
266/// Check if `ruff format` is available with a stable formatter.
267///
268/// Ruff's formatter became stable in v0.1.2. Versions before that output
269/// `NOT_YET_IMPLEMENTED_*` stubs instead of formatted code. We parse the
270/// version from `ruff --version` (format: "ruff X.Y.Z") and require >= 0.1.2.
271/// Falls back to false if ruff is not found or version cannot be parsed.
272fn ruff_format_available(project_root: Option<&Path>) -> bool {
273    let key = availability_cache_key("ruff-format", project_root);
274    if let Ok(cache) = TOOL_AVAILABILITY_CACHE.lock() {
275        if let Some((available, checked_at)) = cache.get(&key) {
276            if checked_at.elapsed() < TOOL_CACHE_TTL {
277                return *available;
278            }
279        }
280    }
281
282    let result = ruff_format_available_uncached(project_root);
283    if let Ok(mut cache) = TOOL_AVAILABILITY_CACHE.lock() {
284        cache.insert(key, (result, Instant::now()));
285    }
286    result
287}
288
289fn ruff_format_available_uncached(project_root: Option<&Path>) -> bool {
290    let command = match resolve_tool("ruff", project_root) {
291        Some(command) => command,
292        None => return false,
293    };
294    let output = match Command::new(&command)
295        .arg("--version")
296        .stdout(Stdio::piped())
297        .stderr(Stdio::null())
298        .output()
299    {
300        Ok(o) => o,
301        Err(_) => return false,
302    };
303
304    let version_str = String::from_utf8_lossy(&output.stdout);
305    // Parse "ruff X.Y.Z" or just "X.Y.Z"
306    let version_part = version_str
307        .trim()
308        .strip_prefix("ruff ")
309        .unwrap_or(version_str.trim());
310
311    let parts: Vec<&str> = version_part.split('.').collect();
312    if parts.len() < 3 {
313        return false;
314    }
315
316    let major: u32 = match parts[0].parse() {
317        Ok(v) => v,
318        Err(_) => return false,
319    };
320    let minor: u32 = match parts[1].parse() {
321        Ok(v) => v,
322        Err(_) => return false,
323    };
324    let patch: u32 = match parts[2].parse() {
325        Ok(v) => v,
326        Err(_) => return false,
327    };
328
329    // Require >= 0.1.2 where ruff format became stable
330    (major, minor, patch) >= (0, 1, 2)
331}
332
333fn resolve_candidate_tool(
334    candidate: &ToolCandidate,
335    project_root: Option<&Path>,
336) -> Option<String> {
337    if candidate.tool == "ruff" && !ruff_format_available(project_root) {
338        return None;
339    }
340
341    resolve_tool(&candidate.tool, project_root)
342}
343
344fn lang_key(lang: LangId) -> &'static str {
345    match lang {
346        LangId::TypeScript | LangId::JavaScript | LangId::Tsx => "typescript",
347        LangId::Python => "python",
348        LangId::Rust => "rust",
349        LangId::Go => "go",
350        LangId::C => "c",
351        LangId::Cpp => "cpp",
352        LangId::Zig => "zig",
353        LangId::CSharp => "csharp",
354        LangId::Bash => "bash",
355        LangId::Html => "html",
356        LangId::Markdown => "markdown",
357    }
358}
359
360fn has_formatter_support(lang: LangId) -> bool {
361    matches!(
362        lang,
363        LangId::TypeScript
364            | LangId::JavaScript
365            | LangId::Tsx
366            | LangId::Python
367            | LangId::Rust
368            | LangId::Go
369    )
370}
371
372fn has_checker_support(lang: LangId) -> bool {
373    matches!(
374        lang,
375        LangId::TypeScript
376            | LangId::JavaScript
377            | LangId::Tsx
378            | LangId::Python
379            | LangId::Rust
380            | LangId::Go
381    )
382}
383
384fn formatter_candidates(lang: LangId, config: &Config, file_str: &str) -> Vec<ToolCandidate> {
385    let project_root = config.project_root.as_deref();
386    if let Some(preferred) = config.formatter.get(lang_key(lang)) {
387        return explicit_formatter_candidate(preferred, file_str);
388    }
389
390    match lang {
391        LangId::TypeScript | LangId::JavaScript | LangId::Tsx => {
392            if has_project_config(project_root, &["biome.json", "biome.jsonc"]) {
393                vec![ToolCandidate {
394                    tool: "biome".to_string(),
395                    source: "biome.json".to_string(),
396                    args: vec![
397                        "format".to_string(),
398                        "--write".to_string(),
399                        file_str.to_string(),
400                    ],
401                    required: true,
402                }]
403            } else if has_project_config(
404                project_root,
405                &[
406                    ".prettierrc",
407                    ".prettierrc.json",
408                    ".prettierrc.yml",
409                    ".prettierrc.yaml",
410                    ".prettierrc.js",
411                    ".prettierrc.cjs",
412                    ".prettierrc.mjs",
413                    ".prettierrc.toml",
414                    "prettier.config.js",
415                    "prettier.config.cjs",
416                    "prettier.config.mjs",
417                ],
418            ) {
419                vec![ToolCandidate {
420                    tool: "prettier".to_string(),
421                    source: "Prettier config".to_string(),
422                    args: vec!["--write".to_string(), file_str.to_string()],
423                    required: true,
424                }]
425            } else if has_project_config(project_root, &["deno.json", "deno.jsonc"]) {
426                vec![ToolCandidate {
427                    tool: "deno".to_string(),
428                    source: "deno.json".to_string(),
429                    args: vec!["fmt".to_string(), file_str.to_string()],
430                    required: true,
431                }]
432            } else {
433                Vec::new()
434            }
435        }
436        LangId::Python => {
437            if has_project_config(project_root, &["ruff.toml", ".ruff.toml"])
438                || has_pyproject_tool(project_root, "ruff")
439            {
440                vec![ToolCandidate {
441                    tool: "ruff".to_string(),
442                    source: "ruff config".to_string(),
443                    args: vec!["format".to_string(), file_str.to_string()],
444                    required: true,
445                }]
446            } else if has_pyproject_tool(project_root, "black") {
447                vec![ToolCandidate {
448                    tool: "black".to_string(),
449                    source: "pyproject.toml".to_string(),
450                    args: vec![file_str.to_string()],
451                    required: true,
452                }]
453            } else {
454                Vec::new()
455            }
456        }
457        LangId::Rust => {
458            if has_project_config(project_root, &["Cargo.toml"]) {
459                vec![ToolCandidate {
460                    tool: "rustfmt".to_string(),
461                    source: "Cargo.toml".to_string(),
462                    args: vec![file_str.to_string()],
463                    required: true,
464                }]
465            } else {
466                Vec::new()
467            }
468        }
469        LangId::Go => {
470            if has_project_config(project_root, &["go.mod"]) {
471                vec![
472                    ToolCandidate {
473                        tool: "goimports".to_string(),
474                        source: "go.mod".to_string(),
475                        args: vec!["-w".to_string(), file_str.to_string()],
476                        required: false,
477                    },
478                    ToolCandidate {
479                        tool: "gofmt".to_string(),
480                        source: "go.mod".to_string(),
481                        args: vec!["-w".to_string(), file_str.to_string()],
482                        required: true,
483                    },
484                ]
485            } else {
486                Vec::new()
487            }
488        }
489        LangId::C | LangId::Cpp | LangId::Zig | LangId::CSharp | LangId::Bash => Vec::new(),
490        LangId::Html => Vec::new(),
491        LangId::Markdown => Vec::new(),
492    }
493}
494
495fn checker_candidates(lang: LangId, config: &Config, file_str: &str) -> Vec<ToolCandidate> {
496    let project_root = config.project_root.as_deref();
497    if let Some(preferred) = config.checker.get(lang_key(lang)) {
498        return explicit_checker_candidate(preferred, file_str);
499    }
500
501    match lang {
502        LangId::TypeScript | LangId::JavaScript | LangId::Tsx => {
503            if has_project_config(project_root, &["biome.json", "biome.jsonc"]) {
504                vec![ToolCandidate {
505                    tool: "biome".to_string(),
506                    source: "biome.json".to_string(),
507                    args: vec!["check".to_string(), file_str.to_string()],
508                    required: true,
509                }]
510            } else if has_project_config(project_root, &["tsconfig.json"]) {
511                vec![ToolCandidate {
512                    tool: "tsc".to_string(),
513                    source: "tsconfig.json".to_string(),
514                    args: vec![
515                        "--noEmit".to_string(),
516                        "--pretty".to_string(),
517                        "false".to_string(),
518                    ],
519                    required: true,
520                }]
521            } else {
522                Vec::new()
523            }
524        }
525        LangId::Python => {
526            if has_project_config(project_root, &["pyrightconfig.json"])
527                || has_pyproject_tool(project_root, "pyright")
528            {
529                vec![ToolCandidate {
530                    tool: "pyright".to_string(),
531                    source: "pyright config".to_string(),
532                    args: vec!["--outputjson".to_string(), file_str.to_string()],
533                    required: true,
534                }]
535            } else if has_project_config(project_root, &["ruff.toml", ".ruff.toml"])
536                || has_pyproject_tool(project_root, "ruff")
537            {
538                vec![ToolCandidate {
539                    tool: "ruff".to_string(),
540                    source: "ruff config".to_string(),
541                    args: vec![
542                        "check".to_string(),
543                        "--output-format=json".to_string(),
544                        file_str.to_string(),
545                    ],
546                    required: true,
547                }]
548            } else {
549                Vec::new()
550            }
551        }
552        LangId::Rust => {
553            if has_project_config(project_root, &["Cargo.toml"]) {
554                vec![ToolCandidate {
555                    tool: "cargo".to_string(),
556                    source: "Cargo.toml".to_string(),
557                    args: vec!["check".to_string(), "--message-format=json".to_string()],
558                    required: true,
559                }]
560            } else {
561                Vec::new()
562            }
563        }
564        LangId::Go => {
565            if has_project_config(project_root, &["go.mod"]) {
566                vec![
567                    ToolCandidate {
568                        tool: "staticcheck".to_string(),
569                        source: "go.mod".to_string(),
570                        args: vec![file_str.to_string()],
571                        required: false,
572                    },
573                    ToolCandidate {
574                        tool: "go".to_string(),
575                        source: "go.mod".to_string(),
576                        args: vec!["vet".to_string(), file_str.to_string()],
577                        required: true,
578                    },
579                ]
580            } else {
581                Vec::new()
582            }
583        }
584        LangId::C | LangId::Cpp | LangId::Zig | LangId::CSharp | LangId::Bash => Vec::new(),
585        LangId::Html => Vec::new(),
586        LangId::Markdown => Vec::new(),
587    }
588}
589
590fn explicit_formatter_candidate(name: &str, file_str: &str) -> Vec<ToolCandidate> {
591    match name {
592        "none" | "off" | "false" => Vec::new(),
593        "biome" => vec![ToolCandidate {
594            tool: name.to_string(),
595            source: "formatter config".to_string(),
596            args: vec![
597                "format".to_string(),
598                "--write".to_string(),
599                file_str.to_string(),
600            ],
601            required: true,
602        }],
603        "prettier" => vec![ToolCandidate {
604            tool: name.to_string(),
605            source: "formatter config".to_string(),
606            args: vec!["--write".to_string(), file_str.to_string()],
607            required: true,
608        }],
609        "deno" => vec![ToolCandidate {
610            tool: name.to_string(),
611            source: "formatter config".to_string(),
612            args: vec!["fmt".to_string(), file_str.to_string()],
613            required: true,
614        }],
615        "ruff" => vec![ToolCandidate {
616            tool: name.to_string(),
617            source: "formatter config".to_string(),
618            args: vec!["format".to_string(), file_str.to_string()],
619            required: true,
620        }],
621        "black" | "rustfmt" => vec![ToolCandidate {
622            tool: name.to_string(),
623            source: "formatter config".to_string(),
624            args: vec![file_str.to_string()],
625            required: true,
626        }],
627        "goimports" | "gofmt" => vec![ToolCandidate {
628            tool: name.to_string(),
629            source: "formatter config".to_string(),
630            args: vec!["-w".to_string(), file_str.to_string()],
631            required: true,
632        }],
633        _ => Vec::new(),
634    }
635}
636
637fn explicit_checker_candidate(name: &str, file_str: &str) -> Vec<ToolCandidate> {
638    match name {
639        "none" | "off" | "false" => Vec::new(),
640        "tsc" => vec![ToolCandidate {
641            tool: name.to_string(),
642            source: "checker config".to_string(),
643            args: vec![
644                "--noEmit".to_string(),
645                "--pretty".to_string(),
646                "false".to_string(),
647            ],
648            required: true,
649        }],
650        "cargo" => vec![ToolCandidate {
651            tool: name.to_string(),
652            source: "checker config".to_string(),
653            args: vec!["check".to_string(), "--message-format=json".to_string()],
654            required: true,
655        }],
656        "go" => vec![ToolCandidate {
657            tool: name.to_string(),
658            source: "checker config".to_string(),
659            args: vec!["vet".to_string(), file_str.to_string()],
660            required: true,
661        }],
662        "biome" => vec![ToolCandidate {
663            tool: name.to_string(),
664            source: "checker config".to_string(),
665            args: vec!["check".to_string(), file_str.to_string()],
666            required: true,
667        }],
668        "pyright" => vec![ToolCandidate {
669            tool: name.to_string(),
670            source: "checker config".to_string(),
671            args: vec!["--outputjson".to_string(), file_str.to_string()],
672            required: true,
673        }],
674        "ruff" => vec![ToolCandidate {
675            tool: name.to_string(),
676            source: "checker config".to_string(),
677            args: vec![
678                "check".to_string(),
679                "--output-format=json".to_string(),
680                file_str.to_string(),
681            ],
682            required: true,
683        }],
684        "staticcheck" => vec![ToolCandidate {
685            tool: name.to_string(),
686            source: "checker config".to_string(),
687            args: vec![file_str.to_string()],
688            required: true,
689        }],
690        _ => Vec::new(),
691    }
692}
693
694fn resolve_tool_candidates(
695    candidates: Vec<ToolCandidate>,
696    project_root: Option<&Path>,
697) -> ToolDetection {
698    if candidates.is_empty() {
699        return ToolDetection::NotConfigured;
700    }
701
702    let mut missing_required = None;
703    for candidate in candidates {
704        if let Some(command) = resolve_candidate_tool(&candidate, project_root) {
705            return ToolDetection::Found(command, candidate.args);
706        }
707        if candidate.required && missing_required.is_none() {
708            missing_required = Some(candidate.tool);
709        }
710    }
711
712    match missing_required {
713        Some(tool) => ToolDetection::NotInstalled { tool },
714        None => ToolDetection::NotConfigured,
715    }
716}
717
718fn checker_command(candidate: &ToolCandidate, resolved: String) -> String {
719    match candidate.tool.as_str() {
720        "tsc" => resolved,
721        "cargo" => "cargo".to_string(),
722        "go" => "go".to_string(),
723        _ => resolved,
724    }
725}
726
727fn checker_args(candidate: &ToolCandidate) -> Vec<String> {
728    if candidate.tool == "tsc" {
729        vec![
730            "--noEmit".to_string(),
731            "--pretty".to_string(),
732            "false".to_string(),
733        ]
734    } else {
735        candidate.args.clone()
736    }
737}
738
739fn detect_formatter_for_path(path: &Path, lang: LangId, config: &Config) -> ToolDetection {
740    let file_str = path.to_string_lossy().to_string();
741    resolve_tool_candidates(
742        formatter_candidates(lang, config, &file_str),
743        config.project_root.as_deref(),
744    )
745}
746
747fn detect_checker_for_path(path: &Path, lang: LangId, config: &Config) -> ToolDetection {
748    let file_str = path.to_string_lossy().to_string();
749    let candidates = checker_candidates(lang, config, &file_str);
750    if candidates.is_empty() {
751        return ToolDetection::NotConfigured;
752    }
753
754    let project_root = config.project_root.as_deref();
755    let mut missing_required = None;
756    for candidate in candidates {
757        if let Some(command) = resolve_candidate_tool(&candidate, project_root) {
758            return ToolDetection::Found(
759                checker_command(&candidate, command),
760                checker_args(&candidate),
761            );
762        }
763        if candidate.required && missing_required.is_none() {
764            missing_required = Some(candidate.tool);
765        }
766    }
767
768    match missing_required {
769        Some(tool) => ToolDetection::NotInstalled { tool },
770        None => ToolDetection::NotConfigured,
771    }
772}
773
774fn languages_in_project(project_root: &Path) -> HashSet<LangId> {
775    crate::callgraph::walk_project_files(project_root)
776        .filter_map(|path| detect_language(&path))
777        .collect()
778}
779
780fn placeholder_file_for_language(project_root: &Path, lang: LangId) -> PathBuf {
781    let filename = match lang {
782        LangId::TypeScript => "aft-tool-detection.ts",
783        LangId::Tsx => "aft-tool-detection.tsx",
784        LangId::JavaScript => "aft-tool-detection.js",
785        LangId::Python => "aft-tool-detection.py",
786        LangId::Rust => "aft_tool_detection.rs",
787        LangId::Go => "aft_tool_detection.go",
788        LangId::C => "aft_tool_detection.c",
789        LangId::Cpp => "aft_tool_detection.cpp",
790        LangId::Zig => "aft_tool_detection.zig",
791        LangId::CSharp => "aft_tool_detection.cs",
792        LangId::Bash => "aft_tool_detection.sh",
793        LangId::Html => "aft-tool-detection.html",
794        LangId::Markdown => "aft-tool-detection.md",
795    };
796    project_root.join(filename)
797}
798
799pub(crate) fn install_hint(tool: &str) -> String {
800    match tool {
801        "biome" => {
802            "Run `bun add -d --workspace-root @biomejs/biome` or install globally.".to_string()
803        }
804        "prettier" => "Run `npm install -D prettier` or install globally.".to_string(),
805        "tsc" => "Run `npm install -D typescript` or install globally.".to_string(),
806        "pyright" | "pyright-langserver" => "Install: `npm install -g pyright`".to_string(),
807        "ruff" => {
808            "Install: `pip install ruff` or your Python package manager equivalent.".to_string()
809        }
810        "black" => {
811            "Install: `pip install black` or your Python package manager equivalent.".to_string()
812        }
813        "rustfmt" => "Install: `rustup component add rustfmt`".to_string(),
814        "rust-analyzer" => "Install: `rustup component add rust-analyzer`".to_string(),
815        "cargo" => "Install Rust from https://rustup.rs/.".to_string(),
816        "go" => "Install Go from https://go.dev/dl/.".to_string(),
817        "gopls" => "Install: `go install golang.org/x/tools/gopls@latest`".to_string(),
818        "bash-language-server" => "Install: `npm install -g bash-language-server`".to_string(),
819        "yaml-language-server" => "Install: `npm install -g yaml-language-server`".to_string(),
820        "typescript-language-server" => {
821            "Install: `npm install -g typescript-language-server typescript`".to_string()
822        }
823        "deno" => "Install Deno from https://deno.com/.".to_string(),
824        "goimports" => "Install: `go install golang.org/x/tools/cmd/goimports@latest`".to_string(),
825        "staticcheck" => {
826            "Install: `go install honnef.co/go/tools/cmd/staticcheck@latest`".to_string()
827        }
828        other => format!("Install `{other}` and ensure it is on PATH."),
829    }
830}
831
832fn configured_tool_hint(tool: &str, source: &str) -> String {
833    format!(
834        "{tool} is configured in {source} but not installed. {}",
835        install_hint(tool)
836    )
837}
838
839fn missing_tool_warning(
840    kind: &str,
841    language: &str,
842    candidate: &ToolCandidate,
843    project_root: Option<&Path>,
844) -> Option<MissingTool> {
845    if !candidate.required || resolve_candidate_tool(candidate, project_root).is_some() {
846        return None;
847    }
848
849    Some(MissingTool {
850        kind: kind.to_string(),
851        language: language.to_string(),
852        tool: candidate.tool.clone(),
853        hint: configured_tool_hint(&candidate.tool, &candidate.source),
854    })
855}
856
857/// Detect configured formatters/checkers that are missing for languages present in the project.
858pub fn detect_missing_tools(project_root: &Path, config: &Config) -> Vec<MissingTool> {
859    let languages = languages_in_project(project_root);
860    let mut warnings = Vec::new();
861    let mut seen = HashSet::new();
862
863    for lang in languages {
864        let language = lang_key(lang);
865        let placeholder = placeholder_file_for_language(project_root, lang);
866        let file_str = placeholder.to_string_lossy().to_string();
867
868        for candidate in formatter_candidates(lang, config, &file_str) {
869            if let Some(warning) = missing_tool_warning(
870                "formatter_not_installed",
871                language,
872                &candidate,
873                config.project_root.as_deref(),
874            ) {
875                if seen.insert((
876                    warning.kind.clone(),
877                    warning.language.clone(),
878                    warning.tool.clone(),
879                )) {
880                    warnings.push(warning);
881                }
882            }
883        }
884
885        for candidate in checker_candidates(lang, config, &file_str) {
886            if let Some(warning) = missing_tool_warning(
887                "checker_not_installed",
888                language,
889                &candidate,
890                config.project_root.as_deref(),
891            ) {
892                if seen.insert((
893                    warning.kind.clone(),
894                    warning.language.clone(),
895                    warning.tool.clone(),
896                )) {
897                    warnings.push(warning);
898                }
899            }
900        }
901    }
902
903    warnings.sort_by(|left, right| {
904        (&left.kind, &left.language, &left.tool).cmp(&(&right.kind, &right.language, &right.tool))
905    });
906    warnings
907}
908
909/// Detect the appropriate formatter command and arguments for a file.
910///
911/// Priority per language:
912/// - TypeScript/JavaScript/TSX: `prettier --write <file>`
913/// - Python: `ruff format <file>` (fallback: `black <file>`)
914/// - Rust: `rustfmt <file>`
915/// - Go: `gofmt -w <file>`
916///
917/// Returns `None` if no formatter is available for the language.
918pub fn detect_formatter(
919    path: &Path,
920    lang: LangId,
921    config: &Config,
922) -> Option<(String, Vec<String>)> {
923    match detect_formatter_for_path(path, lang, config) {
924        ToolDetection::Found(cmd, args) => Some((cmd, args)),
925        ToolDetection::NotConfigured | ToolDetection::NotInstalled { .. } => None,
926    }
927}
928
929/// Check if any of the given config file names exist in the project root.
930fn has_project_config(project_root: Option<&Path>, filenames: &[&str]) -> bool {
931    let root = match project_root {
932        Some(r) => r,
933        None => return false,
934    };
935    filenames.iter().any(|f| root.join(f).exists())
936}
937
938/// Check if pyproject.toml exists and contains a `[tool.<name>]` section.
939fn has_pyproject_tool(project_root: Option<&Path>, tool_name: &str) -> bool {
940    let root = match project_root {
941        Some(r) => r,
942        None => return false,
943    };
944    let pyproject = root.join("pyproject.toml");
945    if !pyproject.exists() {
946        return false;
947    }
948    match std::fs::read_to_string(&pyproject) {
949        Ok(content) => {
950            let pattern = format!("[tool.{}]", tool_name);
951            content.contains(&pattern)
952        }
953        Err(_) => false,
954    }
955}
956
957/// Auto-format a file using the detected formatter for its language.
958///
959/// Returns `(formatted, skip_reason)`:
960/// - `(true, None)` — file was successfully formatted
961/// - `(false, Some(reason))` — formatting was skipped, reason explains why
962///
963/// Skip reasons: `"unsupported_language"`, `"no_formatter_configured"`,
964/// `"formatter_not_installed"`, `"timeout"`, `"error"`
965pub fn auto_format(path: &Path, config: &Config) -> (bool, Option<String>) {
966    // Check if formatting is disabled via plugin config
967    if !config.format_on_edit {
968        return (false, Some("no_formatter_configured".to_string()));
969    }
970
971    let lang = match detect_language(path) {
972        Some(l) => l,
973        None => {
974            log::debug!(
975                "[aft] format: {} (skipped: unsupported_language)",
976                path.display()
977            );
978            return (false, Some("unsupported_language".to_string()));
979        }
980    };
981    if !has_formatter_support(lang) {
982        log::debug!(
983            "[aft] format: {} (skipped: unsupported_language)",
984            path.display()
985        );
986        return (false, Some("unsupported_language".to_string()));
987    }
988
989    let (cmd, args) = match detect_formatter_for_path(path, lang, config) {
990        ToolDetection::Found(cmd, args) => (cmd, args),
991        ToolDetection::NotConfigured => {
992            log::debug!(
993                "[aft] format: {} (skipped: no_formatter_configured)",
994                path.display()
995            );
996            return (false, Some("no_formatter_configured".to_string()));
997        }
998        ToolDetection::NotInstalled { tool } => {
999            log::warn!(
1000                "format: {} (skipped: formatter_not_installed: {})",
1001                path.display(),
1002                tool
1003            );
1004            return (false, Some("formatter_not_installed".to_string()));
1005        }
1006    };
1007
1008    let arg_refs: Vec<&str> = args.iter().map(|s| s.as_str()).collect();
1009
1010    // Run the formatter in the project root so tool-local config files
1011    // (biome.json, .prettierrc, rustfmt.toml, etc.) are discovered. The
1012    // type-checker path (`validate_full`) already does this via
1013    // `path.parent()`; formatters need the same treatment. Without it,
1014    // formatters silently fall back to built-in defaults when the aft
1015    // process CWD differs from the project root (audit #18).
1016    let working_dir = config.project_root.as_deref();
1017
1018    match run_external_tool(&cmd, &arg_refs, working_dir, config.formatter_timeout_secs) {
1019        Ok(_) => {
1020            log::info!("format: {} ({})", path.display(), cmd);
1021            (true, None)
1022        }
1023        Err(FormatError::Timeout { .. }) => {
1024            log::warn!("format: {} (skipped: timeout)", path.display());
1025            (false, Some("timeout".to_string()))
1026        }
1027        Err(FormatError::NotFound { .. }) => {
1028            log::warn!(
1029                "format: {} (skipped: formatter_not_installed)",
1030                path.display()
1031            );
1032            (false, Some("formatter_not_installed".to_string()))
1033        }
1034        Err(FormatError::Failed { stderr, .. }) => {
1035            log::debug!(
1036                "[aft] format: {} (skipped: error: {})",
1037                path.display(),
1038                stderr.lines().next().unwrap_or("unknown")
1039            );
1040            (false, Some("error".to_string()))
1041        }
1042        Err(FormatError::UnsupportedLanguage) => {
1043            log::debug!(
1044                "[aft] format: {} (skipped: unsupported_language)",
1045                path.display()
1046            );
1047            (false, Some("unsupported_language".to_string()))
1048        }
1049    }
1050}
1051
1052/// Spawn a subprocess and capture output regardless of exit code.
1053///
1054/// Unlike `run_external_tool`, this does NOT treat non-zero exit as an error —
1055/// type checkers return non-zero when they find issues, which is expected.
1056/// Returns `FormatError::NotFound` when the binary isn't on PATH, and
1057/// `FormatError::Timeout` if the deadline is exceeded.
1058pub fn run_external_tool_capture(
1059    command: &str,
1060    args: &[&str],
1061    working_dir: Option<&Path>,
1062    timeout_secs: u32,
1063) -> Result<ExternalToolResult, FormatError> {
1064    let mut cmd = Command::new(command);
1065    cmd.args(args).stdout(Stdio::piped()).stderr(Stdio::piped());
1066
1067    if let Some(dir) = working_dir {
1068        cmd.current_dir(dir);
1069    }
1070
1071    let mut child = match cmd.spawn() {
1072        Ok(c) => c,
1073        Err(e) if e.kind() == ErrorKind::NotFound => {
1074            return Err(FormatError::NotFound {
1075                tool: command.to_string(),
1076            });
1077        }
1078        Err(e) => {
1079            return Err(FormatError::Failed {
1080                tool: command.to_string(),
1081                stderr: e.to_string(),
1082            });
1083        }
1084    };
1085
1086    let deadline = Instant::now() + Duration::from_secs(timeout_secs as u64);
1087
1088    loop {
1089        match child.try_wait() {
1090            Ok(Some(status)) => {
1091                let stdout = child
1092                    .stdout
1093                    .take()
1094                    .map(|s| std::io::read_to_string(s).unwrap_or_default())
1095                    .unwrap_or_default();
1096                let stderr = child
1097                    .stderr
1098                    .take()
1099                    .map(|s| std::io::read_to_string(s).unwrap_or_default())
1100                    .unwrap_or_default();
1101
1102                return Ok(ExternalToolResult {
1103                    stdout,
1104                    stderr,
1105                    exit_code: status.code().unwrap_or(-1),
1106                });
1107            }
1108            Ok(None) => {
1109                if Instant::now() >= deadline {
1110                    let _ = child.kill();
1111                    let _ = child.wait();
1112                    return Err(FormatError::Timeout {
1113                        tool: command.to_string(),
1114                        timeout_secs,
1115                    });
1116                }
1117                thread::sleep(Duration::from_millis(50));
1118            }
1119            Err(e) => {
1120                return Err(FormatError::Failed {
1121                    tool: command.to_string(),
1122                    stderr: format!("try_wait error: {}", e),
1123                });
1124            }
1125        }
1126    }
1127}
1128
1129// ============================================================================
1130// Type-checker validation (R017)
1131// ============================================================================
1132
1133/// A structured error from a type checker.
1134#[derive(Debug, Clone, serde::Serialize)]
1135pub struct ValidationError {
1136    pub line: u32,
1137    pub column: u32,
1138    pub message: String,
1139    pub severity: String,
1140}
1141
1142/// Detect the appropriate type checker command and arguments for a file.
1143///
1144/// Returns `(command, args)` for the type checker. The `--noEmit` / equivalent
1145/// flags ensure no output files are produced.
1146///
1147/// Supported:
1148/// - TypeScript/JavaScript/TSX → `npx tsc --noEmit` (fallback: `tsc --noEmit`)
1149/// - Python → `pyright`
1150/// - Rust → `cargo check`
1151/// - Go → `go vet`
1152pub fn detect_type_checker(
1153    path: &Path,
1154    lang: LangId,
1155    config: &Config,
1156) -> Option<(String, Vec<String>)> {
1157    match detect_checker_for_path(path, lang, config) {
1158        ToolDetection::Found(cmd, args) => Some((cmd, args)),
1159        ToolDetection::NotConfigured | ToolDetection::NotInstalled { .. } => None,
1160    }
1161}
1162
1163/// Parse type checker output into structured validation errors.
1164///
1165/// Handles output formats from tsc, pyright (JSON), cargo check (JSON), and go vet.
1166/// Filters to errors related to the edited file where feasible.
1167pub fn parse_checker_output(
1168    stdout: &str,
1169    stderr: &str,
1170    file: &Path,
1171    checker: &str,
1172) -> Vec<ValidationError> {
1173    let checker_name = Path::new(checker)
1174        .file_name()
1175        .and_then(|name| name.to_str())
1176        .unwrap_or(checker);
1177    match checker_name {
1178        "npx" | "tsc" => parse_tsc_output(stdout, stderr, file),
1179        "pyright" => parse_pyright_output(stdout, file),
1180        "cargo" => parse_cargo_output(stdout, stderr, file),
1181        "go" => parse_go_vet_output(stderr, file),
1182        _ => Vec::new(),
1183    }
1184}
1185
1186/// Parse tsc output lines like: `path(line,col): error TSxxxx: message`
1187fn parse_tsc_output(stdout: &str, stderr: &str, file: &Path) -> Vec<ValidationError> {
1188    let mut errors = Vec::new();
1189    let file_str = file.to_string_lossy();
1190    // tsc writes diagnostics to stdout (with --pretty false)
1191    let combined = format!("{}{}", stdout, stderr);
1192    for line in combined.lines() {
1193        // Format: path(line,col): severity TSxxxx: message
1194        // or: path(line,col): severity: message
1195        if let Some((loc, rest)) = line.split_once("): ") {
1196            // Check if this error is for our file (compare filename part)
1197            let file_part = loc.split('(').next().unwrap_or("");
1198            if !file_str.ends_with(file_part)
1199                && !file_part.ends_with(&*file_str)
1200                && file_part != &*file_str
1201            {
1202                continue;
1203            }
1204
1205            // Parse (line,col) from the location part
1206            let coords = loc.split('(').last().unwrap_or("");
1207            let parts: Vec<&str> = coords.split(',').collect();
1208            let line_num: u32 = parts.first().and_then(|s| s.parse().ok()).unwrap_or(0);
1209            let col_num: u32 = parts.get(1).and_then(|s| s.parse().ok()).unwrap_or(0);
1210
1211            // Parse severity and message
1212            let (severity, message) = if let Some(msg) = rest.strip_prefix("error ") {
1213                ("error".to_string(), msg.to_string())
1214            } else if let Some(msg) = rest.strip_prefix("warning ") {
1215                ("warning".to_string(), msg.to_string())
1216            } else {
1217                ("error".to_string(), rest.to_string())
1218            };
1219
1220            errors.push(ValidationError {
1221                line: line_num,
1222                column: col_num,
1223                message,
1224                severity,
1225            });
1226        }
1227    }
1228    errors
1229}
1230
1231/// Parse pyright JSON output.
1232fn parse_pyright_output(stdout: &str, file: &Path) -> Vec<ValidationError> {
1233    let mut errors = Vec::new();
1234    let file_str = file.to_string_lossy();
1235
1236    // pyright --outputjson emits JSON with generalDiagnostics array
1237    if let Ok(json) = serde_json::from_str::<serde_json::Value>(stdout) {
1238        if let Some(diags) = json.get("generalDiagnostics").and_then(|d| d.as_array()) {
1239            for diag in diags {
1240                // Filter to our file
1241                let diag_file = diag.get("file").and_then(|f| f.as_str()).unwrap_or("");
1242                if !diag_file.is_empty()
1243                    && !file_str.ends_with(diag_file)
1244                    && !diag_file.ends_with(&*file_str)
1245                    && diag_file != &*file_str
1246                {
1247                    continue;
1248                }
1249
1250                let line_num = diag
1251                    .get("range")
1252                    .and_then(|r| r.get("start"))
1253                    .and_then(|s| s.get("line"))
1254                    .and_then(|l| l.as_u64())
1255                    .unwrap_or(0) as u32;
1256                let col_num = diag
1257                    .get("range")
1258                    .and_then(|r| r.get("start"))
1259                    .and_then(|s| s.get("character"))
1260                    .and_then(|c| c.as_u64())
1261                    .unwrap_or(0) as u32;
1262                let message = diag
1263                    .get("message")
1264                    .and_then(|m| m.as_str())
1265                    .unwrap_or("unknown error")
1266                    .to_string();
1267                let severity = diag
1268                    .get("severity")
1269                    .and_then(|s| s.as_str())
1270                    .unwrap_or("error")
1271                    .to_lowercase();
1272
1273                errors.push(ValidationError {
1274                    line: line_num + 1, // pyright uses 0-indexed lines
1275                    column: col_num,
1276                    message,
1277                    severity,
1278                });
1279            }
1280        }
1281    }
1282    errors
1283}
1284
1285/// Parse cargo check JSON output, filtering to errors in the target file.
1286fn parse_cargo_output(stdout: &str, _stderr: &str, file: &Path) -> Vec<ValidationError> {
1287    let mut errors = Vec::new();
1288    let file_str = file.to_string_lossy();
1289
1290    for line in stdout.lines() {
1291        if let Ok(msg) = serde_json::from_str::<serde_json::Value>(line) {
1292            if msg.get("reason").and_then(|r| r.as_str()) != Some("compiler-message") {
1293                continue;
1294            }
1295            let message_obj = match msg.get("message") {
1296                Some(m) => m,
1297                None => continue,
1298            };
1299
1300            let level = message_obj
1301                .get("level")
1302                .and_then(|l| l.as_str())
1303                .unwrap_or("error");
1304
1305            // Only include errors and warnings, skip notes/help
1306            if level != "error" && level != "warning" {
1307                continue;
1308            }
1309
1310            let text = message_obj
1311                .get("message")
1312                .and_then(|m| m.as_str())
1313                .unwrap_or("unknown error")
1314                .to_string();
1315
1316            // Find the primary span for our file
1317            if let Some(spans) = message_obj.get("spans").and_then(|s| s.as_array()) {
1318                for span in spans {
1319                    let span_file = span.get("file_name").and_then(|f| f.as_str()).unwrap_or("");
1320                    let is_primary = span
1321                        .get("is_primary")
1322                        .and_then(|p| p.as_bool())
1323                        .unwrap_or(false);
1324
1325                    if !is_primary {
1326                        continue;
1327                    }
1328
1329                    // Filter to our file
1330                    if !file_str.ends_with(span_file)
1331                        && !span_file.ends_with(&*file_str)
1332                        && span_file != &*file_str
1333                    {
1334                        continue;
1335                    }
1336
1337                    let line_num =
1338                        span.get("line_start").and_then(|l| l.as_u64()).unwrap_or(0) as u32;
1339                    let col_num = span
1340                        .get("column_start")
1341                        .and_then(|c| c.as_u64())
1342                        .unwrap_or(0) as u32;
1343
1344                    errors.push(ValidationError {
1345                        line: line_num,
1346                        column: col_num,
1347                        message: text.clone(),
1348                        severity: level.to_string(),
1349                    });
1350                }
1351            }
1352        }
1353    }
1354    errors
1355}
1356
1357/// Parse go vet output lines like: `path:line:col: message`
1358fn parse_go_vet_output(stderr: &str, file: &Path) -> Vec<ValidationError> {
1359    let mut errors = Vec::new();
1360    let file_str = file.to_string_lossy();
1361
1362    for line in stderr.lines() {
1363        // Format: path:line:col: message  OR  path:line: message
1364        let parts: Vec<&str> = line.splitn(4, ':').collect();
1365        if parts.len() < 3 {
1366            continue;
1367        }
1368
1369        let err_file = parts[0].trim();
1370        if !file_str.ends_with(err_file)
1371            && !err_file.ends_with(&*file_str)
1372            && err_file != &*file_str
1373        {
1374            continue;
1375        }
1376
1377        let line_num: u32 = parts[1].trim().parse().unwrap_or(0);
1378        let (col_num, message) = if parts.len() >= 4 {
1379            if let Ok(col) = parts[2].trim().parse::<u32>() {
1380                (col, parts[3].trim().to_string())
1381            } else {
1382                // parts[2] is part of the message, not a column
1383                (0, format!("{}:{}", parts[2].trim(), parts[3].trim()))
1384            }
1385        } else {
1386            (0, parts[2].trim().to_string())
1387        };
1388
1389        errors.push(ValidationError {
1390            line: line_num,
1391            column: col_num,
1392            message,
1393            severity: "error".to_string(),
1394        });
1395    }
1396    errors
1397}
1398
1399/// Run the project's type checker and return structured validation errors.
1400///
1401/// Returns `(errors, skip_reason)`:
1402/// - `(errors, None)` — checker ran, errors may be empty (= valid code)
1403/// - `([], Some(reason))` — checker was skipped
1404///
1405/// Skip reasons: `"unsupported_language"`, `"no_checker_configured"`,
1406/// `"checker_not_installed"`, `"timeout"`, `"error"`
1407pub fn validate_full(path: &Path, config: &Config) -> (Vec<ValidationError>, Option<String>) {
1408    let lang = match detect_language(path) {
1409        Some(l) => l,
1410        None => {
1411            log::debug!(
1412                "[aft] validate: {} (skipped: unsupported_language)",
1413                path.display()
1414            );
1415            return (Vec::new(), Some("unsupported_language".to_string()));
1416        }
1417    };
1418    if !has_checker_support(lang) {
1419        log::debug!(
1420            "[aft] validate: {} (skipped: unsupported_language)",
1421            path.display()
1422        );
1423        return (Vec::new(), Some("unsupported_language".to_string()));
1424    }
1425
1426    let (cmd, args) = match detect_checker_for_path(path, lang, config) {
1427        ToolDetection::Found(cmd, args) => (cmd, args),
1428        ToolDetection::NotConfigured => {
1429            log::debug!(
1430                "[aft] validate: {} (skipped: no_checker_configured)",
1431                path.display()
1432            );
1433            return (Vec::new(), Some("no_checker_configured".to_string()));
1434        }
1435        ToolDetection::NotInstalled { tool } => {
1436            log::warn!(
1437                "validate: {} (skipped: checker_not_installed: {})",
1438                path.display(),
1439                tool
1440            );
1441            return (Vec::new(), Some("checker_not_installed".to_string()));
1442        }
1443    };
1444
1445    let arg_refs: Vec<&str> = args.iter().map(|s| s.as_str()).collect();
1446
1447    // Type checkers may need to run from the project root
1448    let working_dir = config.project_root.as_deref();
1449
1450    match run_external_tool_capture(
1451        &cmd,
1452        &arg_refs,
1453        working_dir,
1454        config.type_checker_timeout_secs,
1455    ) {
1456        Ok(result) => {
1457            let errors = parse_checker_output(&result.stdout, &result.stderr, path, &cmd);
1458            log::debug!(
1459                "[aft] validate: {} ({}, {} errors)",
1460                path.display(),
1461                cmd,
1462                errors.len()
1463            );
1464            (errors, None)
1465        }
1466        Err(FormatError::Timeout { .. }) => {
1467            log::error!("validate: {} (skipped: timeout)", path.display());
1468            (Vec::new(), Some("timeout".to_string()))
1469        }
1470        Err(FormatError::NotFound { .. }) => {
1471            log::warn!(
1472                "validate: {} (skipped: checker_not_installed)",
1473                path.display()
1474            );
1475            (Vec::new(), Some("checker_not_installed".to_string()))
1476        }
1477        Err(FormatError::Failed { stderr, .. }) => {
1478            log::debug!(
1479                "[aft] validate: {} (skipped: error: {})",
1480                path.display(),
1481                stderr.lines().next().unwrap_or("unknown")
1482            );
1483            (Vec::new(), Some("error".to_string()))
1484        }
1485        Err(FormatError::UnsupportedLanguage) => {
1486            log::debug!(
1487                "[aft] validate: {} (skipped: unsupported_language)",
1488                path.display()
1489            );
1490            (Vec::new(), Some("unsupported_language".to_string()))
1491        }
1492    }
1493}
1494
1495#[cfg(test)]
1496mod tests {
1497    use super::*;
1498    use std::fs;
1499    use std::io::Write;
1500
1501    #[test]
1502    fn run_external_tool_not_found() {
1503        let result = run_external_tool("__nonexistent_tool_xyz__", &[], None, 5);
1504        assert!(result.is_err());
1505        match result.unwrap_err() {
1506            FormatError::NotFound { tool } => {
1507                assert_eq!(tool, "__nonexistent_tool_xyz__");
1508            }
1509            other => panic!("expected NotFound, got: {:?}", other),
1510        }
1511    }
1512
1513    #[test]
1514    fn run_external_tool_timeout_kills_subprocess() {
1515        // Use `sleep 60` as a long-running process, timeout after 1 second
1516        let result = run_external_tool("sleep", &["60"], None, 1);
1517        assert!(result.is_err());
1518        match result.unwrap_err() {
1519            FormatError::Timeout { tool, timeout_secs } => {
1520                assert_eq!(tool, "sleep");
1521                assert_eq!(timeout_secs, 1);
1522            }
1523            other => panic!("expected Timeout, got: {:?}", other),
1524        }
1525    }
1526
1527    #[test]
1528    fn run_external_tool_success() {
1529        let result = run_external_tool("echo", &["hello"], None, 5);
1530        assert!(result.is_ok());
1531        let res = result.unwrap();
1532        assert_eq!(res.exit_code, 0);
1533        assert!(res.stdout.contains("hello"));
1534    }
1535
1536    #[test]
1537    fn run_external_tool_nonzero_exit() {
1538        // `false` always exits with code 1
1539        let result = run_external_tool("false", &[], None, 5);
1540        assert!(result.is_err());
1541        match result.unwrap_err() {
1542            FormatError::Failed { tool, .. } => {
1543                assert_eq!(tool, "false");
1544            }
1545            other => panic!("expected Failed, got: {:?}", other),
1546        }
1547    }
1548
1549    #[test]
1550    fn auto_format_unsupported_language() {
1551        let dir = tempfile::tempdir().unwrap();
1552        let path = dir.path().join("file.txt");
1553        fs::write(&path, "hello").unwrap();
1554
1555        let config = Config::default();
1556        let (formatted, reason) = auto_format(&path, &config);
1557        assert!(!formatted);
1558        assert_eq!(reason.as_deref(), Some("unsupported_language"));
1559    }
1560
1561    #[test]
1562    fn detect_formatter_rust_when_rustfmt_available() {
1563        let dir = tempfile::tempdir().unwrap();
1564        fs::write(dir.path().join("Cargo.toml"), "[package]\nname = \"test\"").unwrap();
1565        let path = dir.path().join("test.rs");
1566        let config = Config {
1567            project_root: Some(dir.path().to_path_buf()),
1568            ..Config::default()
1569        };
1570        let result = detect_formatter(&path, LangId::Rust, &config);
1571        if resolve_tool("rustfmt", config.project_root.as_deref()).is_some() {
1572            let (cmd, args) = result.unwrap();
1573            assert_eq!(cmd, "rustfmt");
1574            assert!(args.iter().any(|a| a.ends_with("test.rs")));
1575        } else {
1576            assert!(result.is_none());
1577        }
1578    }
1579
1580    #[test]
1581    fn detect_formatter_go_mapping() {
1582        let dir = tempfile::tempdir().unwrap();
1583        fs::write(dir.path().join("go.mod"), "module test\ngo 1.21").unwrap();
1584        let path = dir.path().join("main.go");
1585        let config = Config {
1586            project_root: Some(dir.path().to_path_buf()),
1587            ..Config::default()
1588        };
1589        let result = detect_formatter(&path, LangId::Go, &config);
1590        if resolve_tool("goimports", config.project_root.as_deref()).is_some() {
1591            let (cmd, args) = result.unwrap();
1592            assert_eq!(cmd, "goimports");
1593            assert!(args.contains(&"-w".to_string()));
1594        } else if resolve_tool("gofmt", config.project_root.as_deref()).is_some() {
1595            let (cmd, args) = result.unwrap();
1596            assert_eq!(cmd, "gofmt");
1597            assert!(args.contains(&"-w".to_string()));
1598        } else {
1599            assert!(result.is_none());
1600        }
1601    }
1602
1603    #[test]
1604    fn detect_formatter_python_mapping() {
1605        let dir = tempfile::tempdir().unwrap();
1606        fs::write(dir.path().join("ruff.toml"), "").unwrap();
1607        let path = dir.path().join("main.py");
1608        let config = Config {
1609            project_root: Some(dir.path().to_path_buf()),
1610            ..Config::default()
1611        };
1612        let result = detect_formatter(&path, LangId::Python, &config);
1613        if ruff_format_available(config.project_root.as_deref()) {
1614            let (cmd, args) = result.unwrap();
1615            assert_eq!(cmd, "ruff");
1616            assert!(args.contains(&"format".to_string()));
1617        } else {
1618            assert!(result.is_none());
1619        }
1620    }
1621
1622    #[test]
1623    fn detect_formatter_no_config_returns_none() {
1624        let path = Path::new("test.ts");
1625        let result = detect_formatter(path, LangId::TypeScript, &Config::default());
1626        assert!(
1627            result.is_none(),
1628            "expected no formatter without project config"
1629        );
1630    }
1631
1632    #[test]
1633    fn detect_formatter_explicit_override() {
1634        // Create a temp dir with a fake node_modules/.bin/biome so resolve_tool finds it
1635        let dir = tempfile::tempdir().unwrap();
1636        let bin_dir = dir.path().join("node_modules").join(".bin");
1637        fs::create_dir_all(&bin_dir).unwrap();
1638        #[cfg(unix)]
1639        {
1640            use std::os::unix::fs::PermissionsExt;
1641            let fake = bin_dir.join("biome");
1642            fs::write(&fake, "#!/bin/sh\necho 1.0.0").unwrap();
1643            fs::set_permissions(&fake, fs::Permissions::from_mode(0o755)).unwrap();
1644        }
1645        #[cfg(not(unix))]
1646        {
1647            fs::write(bin_dir.join("biome.cmd"), "@echo 1.0.0").unwrap();
1648        }
1649
1650        let path = Path::new("test.ts");
1651        let mut config = Config {
1652            project_root: Some(dir.path().to_path_buf()),
1653            ..Config::default()
1654        };
1655        config
1656            .formatter
1657            .insert("typescript".to_string(), "biome".to_string());
1658        let result = detect_formatter(path, LangId::TypeScript, &config);
1659        let (cmd, args) = result.unwrap();
1660        assert!(cmd.contains("biome"), "expected biome in cmd, got: {}", cmd);
1661        assert!(args.contains(&"format".to_string()));
1662        assert!(args.contains(&"--write".to_string()));
1663    }
1664
1665    #[test]
1666    fn resolve_tool_caches_positive_result_until_clear() {
1667        clear_tool_cache();
1668        let dir = tempfile::tempdir().unwrap();
1669        let bin_dir = dir.path().join("node_modules").join(".bin");
1670        fs::create_dir_all(&bin_dir).unwrap();
1671        let tool = bin_dir.join("aft-cache-hit-tool");
1672        fs::write(&tool, "#!/bin/sh\necho cached").unwrap();
1673
1674        let first = resolve_tool("aft-cache-hit-tool", Some(dir.path()));
1675        assert_eq!(first.as_deref(), Some(tool.to_string_lossy().as_ref()));
1676
1677        fs::remove_file(&tool).unwrap();
1678        let cached = resolve_tool("aft-cache-hit-tool", Some(dir.path()));
1679        assert_eq!(cached, first);
1680
1681        clear_tool_cache();
1682        assert!(resolve_tool("aft-cache-hit-tool", Some(dir.path())).is_none());
1683    }
1684
1685    #[test]
1686    fn resolve_tool_caches_negative_result_until_clear() {
1687        clear_tool_cache();
1688        let dir = tempfile::tempdir().unwrap();
1689        let bin_dir = dir.path().join("node_modules").join(".bin");
1690        let tool = bin_dir.join("aft-cache-miss-tool");
1691
1692        assert!(resolve_tool("aft-cache-miss-tool", Some(dir.path())).is_none());
1693
1694        fs::create_dir_all(&bin_dir).unwrap();
1695        fs::write(&tool, "#!/bin/sh\necho cached").unwrap();
1696        assert!(resolve_tool("aft-cache-miss-tool", Some(dir.path())).is_none());
1697
1698        clear_tool_cache();
1699        assert_eq!(
1700            resolve_tool("aft-cache-miss-tool", Some(dir.path())).as_deref(),
1701            Some(tool.to_string_lossy().as_ref())
1702        );
1703    }
1704
1705    #[test]
1706    fn auto_format_happy_path_rustfmt() {
1707        if resolve_tool("rustfmt", None).is_none() {
1708            log::warn!("skipping: rustfmt not available");
1709            return;
1710        }
1711
1712        let dir = tempfile::tempdir().unwrap();
1713        fs::write(dir.path().join("Cargo.toml"), "[package]\nname = \"test\"").unwrap();
1714        let path = dir.path().join("test.rs");
1715
1716        let mut f = fs::File::create(&path).unwrap();
1717        writeln!(f, "fn    main()   {{  println!(\"hello\");  }}").unwrap();
1718        drop(f);
1719
1720        let config = Config {
1721            project_root: Some(dir.path().to_path_buf()),
1722            ..Config::default()
1723        };
1724        let (formatted, reason) = auto_format(&path, &config);
1725        assert!(formatted, "expected formatting to succeed");
1726        assert!(reason.is_none());
1727
1728        let content = fs::read_to_string(&path).unwrap();
1729        assert!(
1730            !content.contains("fn    main"),
1731            "expected rustfmt to fix spacing"
1732        );
1733    }
1734
1735    #[test]
1736    fn parse_tsc_output_basic() {
1737        let stdout = "src/app.ts(10,5): error TS2322: Type 'string' is not assignable to type 'number'.\nsrc/app.ts(20,1): error TS2304: Cannot find name 'foo'.\n";
1738        let file = Path::new("src/app.ts");
1739        let errors = parse_tsc_output(stdout, "", file);
1740        assert_eq!(errors.len(), 2);
1741        assert_eq!(errors[0].line, 10);
1742        assert_eq!(errors[0].column, 5);
1743        assert_eq!(errors[0].severity, "error");
1744        assert!(errors[0].message.contains("TS2322"));
1745        assert_eq!(errors[1].line, 20);
1746    }
1747
1748    #[test]
1749    fn parse_tsc_output_filters_other_files() {
1750        let stdout =
1751            "other.ts(1,1): error TS2322: wrong file\nsrc/app.ts(5,3): error TS1234: our file\n";
1752        let file = Path::new("src/app.ts");
1753        let errors = parse_tsc_output(stdout, "", file);
1754        assert_eq!(errors.len(), 1);
1755        assert_eq!(errors[0].line, 5);
1756    }
1757
1758    #[test]
1759    fn parse_cargo_output_basic() {
1760        let json_line = r#"{"reason":"compiler-message","message":{"level":"error","message":"mismatched types","spans":[{"file_name":"src/main.rs","line_start":10,"column_start":5,"is_primary":true}]}}"#;
1761        let file = Path::new("src/main.rs");
1762        let errors = parse_cargo_output(json_line, "", file);
1763        assert_eq!(errors.len(), 1);
1764        assert_eq!(errors[0].line, 10);
1765        assert_eq!(errors[0].column, 5);
1766        assert_eq!(errors[0].severity, "error");
1767        assert!(errors[0].message.contains("mismatched types"));
1768    }
1769
1770    #[test]
1771    fn parse_cargo_output_skips_notes() {
1772        // Notes and help messages should be filtered out
1773        let json_line = r#"{"reason":"compiler-message","message":{"level":"note","message":"expected this","spans":[{"file_name":"src/main.rs","line_start":10,"column_start":5,"is_primary":true}]}}"#;
1774        let file = Path::new("src/main.rs");
1775        let errors = parse_cargo_output(json_line, "", file);
1776        assert_eq!(errors.len(), 0);
1777    }
1778
1779    #[test]
1780    fn parse_cargo_output_filters_other_files() {
1781        let json_line = r#"{"reason":"compiler-message","message":{"level":"error","message":"err","spans":[{"file_name":"src/other.rs","line_start":1,"column_start":1,"is_primary":true}]}}"#;
1782        let file = Path::new("src/main.rs");
1783        let errors = parse_cargo_output(json_line, "", file);
1784        assert_eq!(errors.len(), 0);
1785    }
1786
1787    #[test]
1788    fn parse_go_vet_output_basic() {
1789        let stderr = "main.go:10:5: unreachable code\nmain.go:20: another issue\n";
1790        let file = Path::new("main.go");
1791        let errors = parse_go_vet_output(stderr, file);
1792        assert_eq!(errors.len(), 2);
1793        assert_eq!(errors[0].line, 10);
1794        assert_eq!(errors[0].column, 5);
1795        assert!(errors[0].message.contains("unreachable code"));
1796        assert_eq!(errors[1].line, 20);
1797        assert_eq!(errors[1].column, 0);
1798    }
1799
1800    #[test]
1801    fn parse_pyright_output_basic() {
1802        let stdout = r#"{"generalDiagnostics":[{"file":"test.py","range":{"start":{"line":4,"character":10}},"message":"Type error here","severity":"error"}]}"#;
1803        let file = Path::new("test.py");
1804        let errors = parse_pyright_output(stdout, file);
1805        assert_eq!(errors.len(), 1);
1806        assert_eq!(errors[0].line, 5); // 0-indexed → 1-indexed
1807        assert_eq!(errors[0].column, 10);
1808        assert_eq!(errors[0].severity, "error");
1809        assert!(errors[0].message.contains("Type error here"));
1810    }
1811
1812    #[test]
1813    fn validate_full_unsupported_language() {
1814        let dir = tempfile::tempdir().unwrap();
1815        let path = dir.path().join("file.txt");
1816        fs::write(&path, "hello").unwrap();
1817
1818        let config = Config::default();
1819        let (errors, reason) = validate_full(&path, &config);
1820        assert!(errors.is_empty());
1821        assert_eq!(reason.as_deref(), Some("unsupported_language"));
1822    }
1823
1824    #[test]
1825    fn detect_type_checker_rust() {
1826        let dir = tempfile::tempdir().unwrap();
1827        fs::write(dir.path().join("Cargo.toml"), "[package]\nname = \"test\"").unwrap();
1828        let path = dir.path().join("src/main.rs");
1829        let config = Config {
1830            project_root: Some(dir.path().to_path_buf()),
1831            ..Config::default()
1832        };
1833        let result = detect_type_checker(&path, LangId::Rust, &config);
1834        if resolve_tool("cargo", config.project_root.as_deref()).is_some() {
1835            let (cmd, args) = result.unwrap();
1836            assert_eq!(cmd, "cargo");
1837            assert!(args.contains(&"check".to_string()));
1838        } else {
1839            assert!(result.is_none());
1840        }
1841    }
1842
1843    #[test]
1844    fn detect_type_checker_go() {
1845        let dir = tempfile::tempdir().unwrap();
1846        fs::write(dir.path().join("go.mod"), "module test\ngo 1.21").unwrap();
1847        let path = dir.path().join("main.go");
1848        let config = Config {
1849            project_root: Some(dir.path().to_path_buf()),
1850            ..Config::default()
1851        };
1852        let result = detect_type_checker(&path, LangId::Go, &config);
1853        if resolve_tool("go", config.project_root.as_deref()).is_some() {
1854            let (cmd, _args) = result.unwrap();
1855            // Could be staticcheck or go vet depending on what's installed
1856            assert!(cmd == "go" || cmd == "staticcheck");
1857        } else {
1858            assert!(result.is_none());
1859        }
1860    }
1861    #[test]
1862    fn run_external_tool_capture_nonzero_not_error() {
1863        // `false` exits with code 1 — capture should still return Ok
1864        let result = run_external_tool_capture("false", &[], None, 5);
1865        assert!(result.is_ok(), "capture should not error on non-zero exit");
1866        assert_eq!(result.unwrap().exit_code, 1);
1867    }
1868
1869    #[test]
1870    fn run_external_tool_capture_not_found() {
1871        let result = run_external_tool_capture("__nonexistent_xyz__", &[], None, 5);
1872        assert!(result.is_err());
1873        match result.unwrap_err() {
1874            FormatError::NotFound { tool } => assert_eq!(tool, "__nonexistent_xyz__"),
1875            other => panic!("expected NotFound, got: {:?}", other),
1876        }
1877    }
1878}