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;
7use std::io::ErrorKind;
8use std::path::Path;
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
38impl std::fmt::Display for FormatError {
39    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
40        match self {
41            FormatError::NotFound { tool } => write!(f, "formatter not found: {}", tool),
42            FormatError::Timeout { tool, timeout_secs } => {
43                write!(f, "formatter '{}' timed out after {}s", tool, timeout_secs)
44            }
45            FormatError::Failed { tool, stderr } => {
46                write!(f, "formatter '{}' failed: {}", tool, stderr)
47            }
48            FormatError::UnsupportedLanguage => write!(f, "unsupported language for formatting"),
49        }
50    }
51}
52
53/// Spawn a subprocess and wait for completion with timeout protection.
54///
55/// Polls `try_wait()` at 50ms intervals. On timeout, kills the child process
56/// and waits for it to exit. Returns `FormatError::NotFound` when the binary
57/// isn't on PATH.
58pub fn run_external_tool(
59    command: &str,
60    args: &[&str],
61    working_dir: Option<&Path>,
62    timeout_secs: u32,
63) -> Result<ExternalToolResult, FormatError> {
64    let mut cmd = Command::new(command);
65    cmd.args(args).stdout(Stdio::piped()).stderr(Stdio::piped());
66
67    if let Some(dir) = working_dir {
68        cmd.current_dir(dir);
69    }
70
71    let mut child = match cmd.spawn() {
72        Ok(c) => c,
73        Err(e) if e.kind() == ErrorKind::NotFound => {
74            return Err(FormatError::NotFound {
75                tool: command.to_string(),
76            });
77        }
78        Err(e) => {
79            return Err(FormatError::Failed {
80                tool: command.to_string(),
81                stderr: e.to_string(),
82            });
83        }
84    };
85
86    let deadline = Instant::now() + Duration::from_secs(timeout_secs as u64);
87
88    loop {
89        match child.try_wait() {
90            Ok(Some(status)) => {
91                let stdout = child
92                    .stdout
93                    .take()
94                    .map(|s| std::io::read_to_string(s).unwrap_or_default())
95                    .unwrap_or_default();
96                let stderr = child
97                    .stderr
98                    .take()
99                    .map(|s| std::io::read_to_string(s).unwrap_or_default())
100                    .unwrap_or_default();
101
102                let exit_code = status.code().unwrap_or(-1);
103                if exit_code != 0 {
104                    return Err(FormatError::Failed {
105                        tool: command.to_string(),
106                        stderr,
107                    });
108                }
109
110                return Ok(ExternalToolResult {
111                    stdout,
112                    stderr,
113                    exit_code,
114                });
115            }
116            Ok(None) => {
117                // Still running
118                if Instant::now() >= deadline {
119                    // Kill the process and reap it
120                    let _ = child.kill();
121                    let _ = child.wait();
122                    return Err(FormatError::Timeout {
123                        tool: command.to_string(),
124                        timeout_secs,
125                    });
126                }
127                thread::sleep(Duration::from_millis(50));
128            }
129            Err(e) => {
130                return Err(FormatError::Failed {
131                    tool: command.to_string(),
132                    stderr: format!("try_wait error: {}", e),
133                });
134            }
135        }
136    }
137}
138
139/// TTL for tool availability cache entries.
140const TOOL_CACHE_TTL: Duration = Duration::from_secs(60);
141
142static TOOL_CACHE: std::sync::LazyLock<Mutex<HashMap<String, (bool, Instant)>>> =
143    std::sync::LazyLock::new(|| Mutex::new(HashMap::new()));
144
145/// Check if a command exists by attempting to spawn it with `--version`.
146///
147/// First checks `<project_root>/node_modules/.bin/<command>` (for locally installed tools
148/// like biome, prettier), then falls back to PATH lookup.
149/// Results are cached for 60 seconds to avoid repeated subprocess spawning.
150fn tool_available(command: &str) -> bool {
151    if let Ok(cache) = TOOL_CACHE.lock() {
152        if let Some((available, checked_at)) = cache.get(command) {
153            if checked_at.elapsed() < TOOL_CACHE_TTL {
154                return *available;
155            }
156        }
157    }
158    let result = resolve_tool(command, None).is_some();
159    if let Ok(mut cache) = TOOL_CACHE.lock() {
160        cache.insert(command.to_string(), (result, Instant::now()));
161    }
162    result
163}
164
165/// Like `tool_available` but also checks node_modules/.bin relative to project_root.
166/// Returns the full path to the tool if found, otherwise None.
167fn resolve_tool(command: &str, project_root: Option<&Path>) -> Option<String> {
168    // 1. Check node_modules/.bin/<command> relative to project root
169    if let Some(root) = project_root {
170        let local_bin = root.join("node_modules").join(".bin").join(command);
171        if local_bin.exists() {
172            return Some(local_bin.to_string_lossy().to_string());
173        }
174    }
175
176    // 2. Fall back to PATH lookup
177    match Command::new(command)
178        .arg("--version")
179        .stdout(Stdio::null())
180        .stderr(Stdio::null())
181        .spawn()
182    {
183        Ok(mut child) => {
184            let _ = child.wait();
185            Some(command.to_string())
186        }
187        Err(_) => None,
188    }
189}
190
191/// Check if `ruff format` is available with a stable formatter.
192///
193/// Ruff's formatter became stable in v0.1.2. Versions before that output
194/// `NOT_YET_IMPLEMENTED_*` stubs instead of formatted code. We parse the
195/// version from `ruff --version` (format: "ruff X.Y.Z") and require >= 0.1.2.
196/// Falls back to false if ruff is not found or version cannot be parsed.
197fn ruff_format_available() -> bool {
198    let output = match Command::new("ruff")
199        .arg("--version")
200        .stdout(Stdio::piped())
201        .stderr(Stdio::null())
202        .output()
203    {
204        Ok(o) => o,
205        Err(_) => return false,
206    };
207
208    let version_str = String::from_utf8_lossy(&output.stdout);
209    // Parse "ruff X.Y.Z" or just "X.Y.Z"
210    let version_part = version_str
211        .trim()
212        .strip_prefix("ruff ")
213        .unwrap_or(version_str.trim());
214
215    let parts: Vec<&str> = version_part.split('.').collect();
216    if parts.len() < 3 {
217        return false;
218    }
219
220    let major: u32 = match parts[0].parse() {
221        Ok(v) => v,
222        Err(_) => return false,
223    };
224    let minor: u32 = match parts[1].parse() {
225        Ok(v) => v,
226        Err(_) => return false,
227    };
228    let patch: u32 = match parts[2].parse() {
229        Ok(v) => v,
230        Err(_) => return false,
231    };
232
233    // Require >= 0.1.2 where ruff format became stable
234    (major, minor, patch) >= (0, 1, 2)
235}
236
237/// Detect the appropriate formatter command and arguments for a file.
238///
239/// Priority per language:
240/// - TypeScript/JavaScript/TSX: `prettier --write <file>`
241/// - Python: `ruff format <file>` (fallback: `black <file>`)
242/// - Rust: `rustfmt <file>`
243/// - Go: `gofmt -w <file>`
244///
245/// Returns `None` if no formatter is available for the language.
246pub fn detect_formatter(
247    path: &Path,
248    lang: LangId,
249    config: &Config,
250) -> Option<(String, Vec<String>)> {
251    let file_str = path.to_string_lossy().to_string();
252
253    // 1. Per-language override from plugin config
254    let lang_key = match lang {
255        LangId::TypeScript | LangId::JavaScript | LangId::Tsx => "typescript",
256        LangId::Python => "python",
257        LangId::Rust => "rust",
258        LangId::Go => "go",
259        LangId::Markdown => "markdown",
260    };
261    if let Some(preferred) = config.formatter.get(lang_key) {
262        return resolve_explicit_formatter(preferred, &file_str, lang);
263    }
264
265    // 2. Project config file detection only — no config file means no formatting.
266    //    This avoids silently reformatting code in projects without formatter setup.
267    let project_root = config.project_root.as_deref();
268
269    match lang {
270        LangId::TypeScript | LangId::JavaScript | LangId::Tsx => {
271            // biome.json / biome.jsonc → biome (check node_modules/.bin first)
272            if has_project_config(project_root, &["biome.json", "biome.jsonc"]) {
273                if let Some(biome_cmd) = resolve_tool("biome", project_root) {
274                    return Some((
275                        biome_cmd,
276                        vec!["format".to_string(), "--write".to_string(), file_str],
277                    ));
278                }
279            }
280            // .prettierrc / .prettierrc.* / prettier.config.* → prettier (check node_modules/.bin first)
281            if has_project_config(
282                project_root,
283                &[
284                    ".prettierrc",
285                    ".prettierrc.json",
286                    ".prettierrc.yml",
287                    ".prettierrc.yaml",
288                    ".prettierrc.js",
289                    ".prettierrc.cjs",
290                    ".prettierrc.mjs",
291                    ".prettierrc.toml",
292                    "prettier.config.js",
293                    "prettier.config.cjs",
294                    "prettier.config.mjs",
295                ],
296            ) {
297                if let Some(prettier_cmd) = resolve_tool("prettier", project_root) {
298                    return Some((prettier_cmd, vec!["--write".to_string(), file_str]));
299                }
300            }
301            // deno.json / deno.jsonc → deno fmt
302            if has_project_config(project_root, &["deno.json", "deno.jsonc"])
303                && tool_available("deno")
304            {
305                return Some(("deno".to_string(), vec!["fmt".to_string(), file_str]));
306            }
307            // No config file found → do not format
308            None
309        }
310        LangId::Python => {
311            // ruff.toml or pyproject.toml with ruff config → ruff
312            if (has_project_config(project_root, &["ruff.toml", ".ruff.toml"])
313                || has_pyproject_tool(project_root, "ruff"))
314                && ruff_format_available()
315            {
316                return Some(("ruff".to_string(), vec!["format".to_string(), file_str]));
317            }
318            // pyproject.toml with black config → black
319            if has_pyproject_tool(project_root, "black") && tool_available("black") {
320                return Some(("black".to_string(), vec![file_str]));
321            }
322            // No config file found → do not format
323            None
324        }
325        LangId::Rust => {
326            // Cargo.toml implies standard Rust formatting
327            if has_project_config(project_root, &["Cargo.toml"]) && tool_available("rustfmt") {
328                Some(("rustfmt".to_string(), vec![file_str]))
329            } else {
330                None
331            }
332        }
333        LangId::Go => {
334            // go.mod implies a Go project
335            if has_project_config(project_root, &["go.mod"]) {
336                if tool_available("goimports") {
337                    Some(("goimports".to_string(), vec!["-w".to_string(), file_str]))
338                } else if tool_available("gofmt") {
339                    Some(("gofmt".to_string(), vec!["-w".to_string(), file_str]))
340                } else {
341                    None
342                }
343            } else {
344                None
345            }
346        }
347        LangId::Markdown => None,
348    }
349}
350
351/// Resolve an explicitly configured formatter name to a command + args.
352fn resolve_explicit_formatter(
353    name: &str,
354    file_str: &str,
355    lang: LangId,
356) -> Option<(String, Vec<String>)> {
357    match name {
358        "biome" => Some((
359            "biome".to_string(),
360            vec![
361                "format".to_string(),
362                "--write".to_string(),
363                file_str.to_string(),
364            ],
365        )),
366        "prettier" => Some((
367            "prettier".to_string(),
368            vec!["--write".to_string(), file_str.to_string()],
369        )),
370        "deno" => Some((
371            "deno".to_string(),
372            vec!["fmt".to_string(), file_str.to_string()],
373        )),
374        "ruff" => Some((
375            "ruff".to_string(),
376            vec!["format".to_string(), file_str.to_string()],
377        )),
378        "black" => Some(("black".to_string(), vec![file_str.to_string()])),
379        "rustfmt" => Some(("rustfmt".to_string(), vec![file_str.to_string()])),
380        "goimports" => Some((
381            "goimports".to_string(),
382            vec!["-w".to_string(), file_str.to_string()],
383        )),
384        "gofmt" => Some((
385            "gofmt".to_string(),
386            vec!["-w".to_string(), file_str.to_string()],
387        )),
388        "none" | "off" | "false" => None,
389        _ => {
390            log::debug!(
391                "[aft] format: unknown preferred_formatter '{}' for {:?}, falling back to auto",
392                name, lang
393            );
394            None
395        }
396    }
397}
398
399/// Check if any of the given config file names exist in the project root.
400fn has_project_config(project_root: Option<&Path>, filenames: &[&str]) -> bool {
401    let root = match project_root {
402        Some(r) => r,
403        None => return false,
404    };
405    filenames.iter().any(|f| root.join(f).exists())
406}
407
408/// Check if pyproject.toml exists and contains a `[tool.<name>]` section.
409fn has_pyproject_tool(project_root: Option<&Path>, tool_name: &str) -> bool {
410    let root = match project_root {
411        Some(r) => r,
412        None => return false,
413    };
414    let pyproject = root.join("pyproject.toml");
415    if !pyproject.exists() {
416        return false;
417    }
418    match std::fs::read_to_string(&pyproject) {
419        Ok(content) => {
420            let pattern = format!("[tool.{}]", tool_name);
421            content.contains(&pattern)
422        }
423        Err(_) => false,
424    }
425}
426
427/// Auto-format a file using the detected formatter for its language.
428///
429/// Returns `(formatted, skip_reason)`:
430/// - `(true, None)` — file was successfully formatted
431/// - `(false, Some(reason))` — formatting was skipped, reason explains why
432///
433/// Skip reasons: `"unsupported_language"`, `"not_found"`, `"timeout"`, `"error"`
434pub fn auto_format(path: &Path, config: &Config) -> (bool, Option<String>) {
435    // Check if formatting is disabled via plugin config
436    if !config.format_on_edit {
437        return (false, Some("disabled".to_string()));
438    }
439
440    let lang = match detect_language(path) {
441        Some(l) => l,
442        None => {
443            log::debug!(
444                "[aft] format: {} (skipped: unsupported_language)",
445                path.display()
446            );
447            return (false, Some("unsupported_language".to_string()));
448        }
449    };
450
451    let (cmd, args) = match detect_formatter(path, lang, config) {
452        Some(pair) => pair,
453        None => {
454            log::warn!("format: {} (skipped: not_found)", path.display());
455            return (false, Some("not_found".to_string()));
456        }
457    };
458
459    let arg_refs: Vec<&str> = args.iter().map(|s| s.as_str()).collect();
460
461    match run_external_tool(&cmd, &arg_refs, None, config.formatter_timeout_secs) {
462        Ok(_) => {
463            log::error!("format: {} ({})", path.display(), cmd);
464            (true, None)
465        }
466        Err(FormatError::Timeout { .. }) => {
467            log::error!("format: {} (skipped: timeout)", path.display());
468            (false, Some("timeout".to_string()))
469        }
470        Err(FormatError::NotFound { .. }) => {
471            log::warn!("format: {} (skipped: not_found)", path.display());
472            (false, Some("not_found".to_string()))
473        }
474        Err(FormatError::Failed { stderr, .. }) => {
475            log::debug!(
476                "[aft] format: {} (skipped: error: {})",
477                path.display(),
478                stderr.lines().next().unwrap_or("unknown")
479            );
480            (false, Some("error".to_string()))
481        }
482        Err(FormatError::UnsupportedLanguage) => {
483            log::debug!(
484                "[aft] format: {} (skipped: unsupported_language)",
485                path.display()
486            );
487            (false, Some("unsupported_language".to_string()))
488        }
489    }
490}
491
492/// Spawn a subprocess and capture output regardless of exit code.
493///
494/// Unlike `run_external_tool`, this does NOT treat non-zero exit as an error —
495/// type checkers return non-zero when they find issues, which is expected.
496/// Returns `FormatError::NotFound` when the binary isn't on PATH, and
497/// `FormatError::Timeout` if the deadline is exceeded.
498pub fn run_external_tool_capture(
499    command: &str,
500    args: &[&str],
501    working_dir: Option<&Path>,
502    timeout_secs: u32,
503) -> Result<ExternalToolResult, FormatError> {
504    let mut cmd = Command::new(command);
505    cmd.args(args).stdout(Stdio::piped()).stderr(Stdio::piped());
506
507    if let Some(dir) = working_dir {
508        cmd.current_dir(dir);
509    }
510
511    let mut child = match cmd.spawn() {
512        Ok(c) => c,
513        Err(e) if e.kind() == ErrorKind::NotFound => {
514            return Err(FormatError::NotFound {
515                tool: command.to_string(),
516            });
517        }
518        Err(e) => {
519            return Err(FormatError::Failed {
520                tool: command.to_string(),
521                stderr: e.to_string(),
522            });
523        }
524    };
525
526    let deadline = Instant::now() + Duration::from_secs(timeout_secs as u64);
527
528    loop {
529        match child.try_wait() {
530            Ok(Some(status)) => {
531                let stdout = child
532                    .stdout
533                    .take()
534                    .map(|s| std::io::read_to_string(s).unwrap_or_default())
535                    .unwrap_or_default();
536                let stderr = child
537                    .stderr
538                    .take()
539                    .map(|s| std::io::read_to_string(s).unwrap_or_default())
540                    .unwrap_or_default();
541
542                return Ok(ExternalToolResult {
543                    stdout,
544                    stderr,
545                    exit_code: status.code().unwrap_or(-1),
546                });
547            }
548            Ok(None) => {
549                if Instant::now() >= deadline {
550                    let _ = child.kill();
551                    let _ = child.wait();
552                    return Err(FormatError::Timeout {
553                        tool: command.to_string(),
554                        timeout_secs,
555                    });
556                }
557                thread::sleep(Duration::from_millis(50));
558            }
559            Err(e) => {
560                return Err(FormatError::Failed {
561                    tool: command.to_string(),
562                    stderr: format!("try_wait error: {}", e),
563                });
564            }
565        }
566    }
567}
568
569// ============================================================================
570// Type-checker validation (R017)
571// ============================================================================
572
573/// A structured error from a type checker.
574#[derive(Debug, Clone, serde::Serialize)]
575pub struct ValidationError {
576    pub line: u32,
577    pub column: u32,
578    pub message: String,
579    pub severity: String,
580}
581
582/// Detect the appropriate type checker command and arguments for a file.
583///
584/// Returns `(command, args)` for the type checker. The `--noEmit` / equivalent
585/// flags ensure no output files are produced.
586///
587/// Supported:
588/// - TypeScript/JavaScript/TSX → `npx tsc --noEmit` (fallback: `tsc --noEmit`)
589/// - Python → `pyright`
590/// - Rust → `cargo check`
591/// - Go → `go vet`
592pub fn detect_type_checker(
593    path: &Path,
594    lang: LangId,
595    config: &Config,
596) -> Option<(String, Vec<String>)> {
597    let file_str = path.to_string_lossy().to_string();
598    let project_root = config.project_root.as_deref();
599
600    // Per-language override from plugin config
601    let lang_key = match lang {
602        LangId::TypeScript | LangId::JavaScript | LangId::Tsx => "typescript",
603        LangId::Python => "python",
604        LangId::Rust => "rust",
605        LangId::Go => "go",
606        LangId::Markdown => "markdown",
607    };
608    if let Some(preferred) = config.checker.get(lang_key) {
609        return resolve_explicit_checker(preferred, &file_str, lang);
610    }
611
612    match lang {
613        LangId::TypeScript | LangId::JavaScript | LangId::Tsx => {
614            // biome.json → biome check (lint + type errors, check node_modules/.bin first)
615            if has_project_config(project_root, &["biome.json", "biome.jsonc"]) {
616                if let Some(biome_cmd) = resolve_tool("biome", project_root) {
617                    return Some((biome_cmd, vec!["check".to_string(), file_str]));
618                }
619            }
620            // tsconfig.json → tsc (check node_modules/.bin first)
621            if has_project_config(project_root, &["tsconfig.json"]) {
622                if let Some(tsc_cmd) = resolve_tool("tsc", project_root) {
623                    return Some((
624                        tsc_cmd,
625                        vec![
626                            "--noEmit".to_string(),
627                            "--pretty".to_string(),
628                            "false".to_string(),
629                        ],
630                    ));
631                } else if tool_available("npx") {
632                    return Some((
633                        "npx".to_string(),
634                        vec![
635                            "tsc".to_string(),
636                            "--noEmit".to_string(),
637                            "--pretty".to_string(),
638                            "false".to_string(),
639                        ],
640                    ));
641                }
642            }
643            None
644        }
645        LangId::Python => {
646            // pyrightconfig.json or pyproject.toml with pyright → pyright
647            if has_project_config(project_root, &["pyrightconfig.json"])
648                || has_pyproject_tool(project_root, "pyright")
649            {
650                if let Some(pyright_cmd) = resolve_tool("pyright", project_root) {
651                    return Some((pyright_cmd, vec!["--outputjson".to_string(), file_str]));
652                }
653            }
654            // ruff.toml or pyproject.toml with ruff → ruff check
655            if (has_project_config(project_root, &["ruff.toml", ".ruff.toml"])
656                || has_pyproject_tool(project_root, "ruff"))
657                && ruff_format_available()
658            {
659                return Some((
660                    "ruff".to_string(),
661                    vec![
662                        "check".to_string(),
663                        "--output-format=json".to_string(),
664                        file_str,
665                    ],
666                ));
667            }
668            None
669        }
670        LangId::Rust => {
671            // Cargo.toml implies cargo check
672            if has_project_config(project_root, &["Cargo.toml"]) && tool_available("cargo") {
673                Some((
674                    "cargo".to_string(),
675                    vec!["check".to_string(), "--message-format=json".to_string()],
676                ))
677            } else {
678                None
679            }
680        }
681        LangId::Go => {
682            // go.mod implies Go project
683            if has_project_config(project_root, &["go.mod"]) {
684                if tool_available("staticcheck") {
685                    Some(("staticcheck".to_string(), vec![file_str]))
686                } else if tool_available("go") {
687                    Some(("go".to_string(), vec!["vet".to_string(), file_str]))
688                } else {
689                    None
690                }
691            } else {
692                None
693            }
694        }
695        LangId::Markdown => None,
696    }
697}
698
699/// Resolve an explicitly configured checker name to a command + args.
700fn resolve_explicit_checker(
701    name: &str,
702    file_str: &str,
703    _lang: LangId,
704) -> Option<(String, Vec<String>)> {
705    match name {
706        "tsc" => Some((
707            "npx".to_string(),
708            vec![
709                "tsc".to_string(),
710                "--noEmit".to_string(),
711                "--pretty".to_string(),
712                "false".to_string(),
713            ],
714        )),
715        "biome" => Some((
716            "biome".to_string(),
717            vec!["check".to_string(), file_str.to_string()],
718        )),
719        "pyright" => Some((
720            "pyright".to_string(),
721            vec!["--outputjson".to_string(), file_str.to_string()],
722        )),
723        "ruff" => Some((
724            "ruff".to_string(),
725            vec![
726                "check".to_string(),
727                "--output-format=json".to_string(),
728                file_str.to_string(),
729            ],
730        )),
731        "cargo" => Some((
732            "cargo".to_string(),
733            vec!["check".to_string(), "--message-format=json".to_string()],
734        )),
735        "go" => Some((
736            "go".to_string(),
737            vec!["vet".to_string(), file_str.to_string()],
738        )),
739        "staticcheck" => Some(("staticcheck".to_string(), vec![file_str.to_string()])),
740        "none" | "off" | "false" => None,
741        _ => {
742            log::debug!(
743                "[aft] validate: unknown preferred_checker '{}', falling back to auto",
744                name
745            );
746            None
747        }
748    }
749}
750
751/// Parse type checker output into structured validation errors.
752///
753/// Handles output formats from tsc, pyright (JSON), cargo check (JSON), and go vet.
754/// Filters to errors related to the edited file where feasible.
755pub fn parse_checker_output(
756    stdout: &str,
757    stderr: &str,
758    file: &Path,
759    checker: &str,
760) -> Vec<ValidationError> {
761    match checker {
762        "npx" | "tsc" => parse_tsc_output(stdout, stderr, file),
763        "pyright" => parse_pyright_output(stdout, file),
764        "cargo" => parse_cargo_output(stdout, stderr, file),
765        "go" => parse_go_vet_output(stderr, file),
766        _ => Vec::new(),
767    }
768}
769
770/// Parse tsc output lines like: `path(line,col): error TSxxxx: message`
771fn parse_tsc_output(stdout: &str, stderr: &str, file: &Path) -> Vec<ValidationError> {
772    let mut errors = Vec::new();
773    let file_str = file.to_string_lossy();
774    // tsc writes diagnostics to stdout (with --pretty false)
775    let combined = format!("{}{}", stdout, stderr);
776    for line in combined.lines() {
777        // Format: path(line,col): severity TSxxxx: message
778        // or: path(line,col): severity: message
779        if let Some((loc, rest)) = line.split_once("): ") {
780            // Check if this error is for our file (compare filename part)
781            let file_part = loc.split('(').next().unwrap_or("");
782            if !file_str.ends_with(file_part)
783                && !file_part.ends_with(&*file_str)
784                && file_part != &*file_str
785            {
786                continue;
787            }
788
789            // Parse (line,col) from the location part
790            let coords = loc.split('(').last().unwrap_or("");
791            let parts: Vec<&str> = coords.split(',').collect();
792            let line_num: u32 = parts.first().and_then(|s| s.parse().ok()).unwrap_or(0);
793            let col_num: u32 = parts.get(1).and_then(|s| s.parse().ok()).unwrap_or(0);
794
795            // Parse severity and message
796            let (severity, message) = if let Some(msg) = rest.strip_prefix("error ") {
797                ("error".to_string(), msg.to_string())
798            } else if let Some(msg) = rest.strip_prefix("warning ") {
799                ("warning".to_string(), msg.to_string())
800            } else {
801                ("error".to_string(), rest.to_string())
802            };
803
804            errors.push(ValidationError {
805                line: line_num,
806                column: col_num,
807                message,
808                severity,
809            });
810        }
811    }
812    errors
813}
814
815/// Parse pyright JSON output.
816fn parse_pyright_output(stdout: &str, file: &Path) -> Vec<ValidationError> {
817    let mut errors = Vec::new();
818    let file_str = file.to_string_lossy();
819
820    // pyright --outputjson emits JSON with generalDiagnostics array
821    if let Ok(json) = serde_json::from_str::<serde_json::Value>(stdout) {
822        if let Some(diags) = json.get("generalDiagnostics").and_then(|d| d.as_array()) {
823            for diag in diags {
824                // Filter to our file
825                let diag_file = diag.get("file").and_then(|f| f.as_str()).unwrap_or("");
826                if !diag_file.is_empty()
827                    && !file_str.ends_with(diag_file)
828                    && !diag_file.ends_with(&*file_str)
829                    && diag_file != &*file_str
830                {
831                    continue;
832                }
833
834                let line_num = diag
835                    .get("range")
836                    .and_then(|r| r.get("start"))
837                    .and_then(|s| s.get("line"))
838                    .and_then(|l| l.as_u64())
839                    .unwrap_or(0) as u32;
840                let col_num = diag
841                    .get("range")
842                    .and_then(|r| r.get("start"))
843                    .and_then(|s| s.get("character"))
844                    .and_then(|c| c.as_u64())
845                    .unwrap_or(0) as u32;
846                let message = diag
847                    .get("message")
848                    .and_then(|m| m.as_str())
849                    .unwrap_or("unknown error")
850                    .to_string();
851                let severity = diag
852                    .get("severity")
853                    .and_then(|s| s.as_str())
854                    .unwrap_or("error")
855                    .to_lowercase();
856
857                errors.push(ValidationError {
858                    line: line_num + 1, // pyright uses 0-indexed lines
859                    column: col_num,
860                    message,
861                    severity,
862                });
863            }
864        }
865    }
866    errors
867}
868
869/// Parse cargo check JSON output, filtering to errors in the target file.
870fn parse_cargo_output(stdout: &str, _stderr: &str, file: &Path) -> Vec<ValidationError> {
871    let mut errors = Vec::new();
872    let file_str = file.to_string_lossy();
873
874    for line in stdout.lines() {
875        if let Ok(msg) = serde_json::from_str::<serde_json::Value>(line) {
876            if msg.get("reason").and_then(|r| r.as_str()) != Some("compiler-message") {
877                continue;
878            }
879            let message_obj = match msg.get("message") {
880                Some(m) => m,
881                None => continue,
882            };
883
884            let level = message_obj
885                .get("level")
886                .and_then(|l| l.as_str())
887                .unwrap_or("error");
888
889            // Only include errors and warnings, skip notes/help
890            if level != "error" && level != "warning" {
891                continue;
892            }
893
894            let text = message_obj
895                .get("message")
896                .and_then(|m| m.as_str())
897                .unwrap_or("unknown error")
898                .to_string();
899
900            // Find the primary span for our file
901            if let Some(spans) = message_obj.get("spans").and_then(|s| s.as_array()) {
902                for span in spans {
903                    let span_file = span.get("file_name").and_then(|f| f.as_str()).unwrap_or("");
904                    let is_primary = span
905                        .get("is_primary")
906                        .and_then(|p| p.as_bool())
907                        .unwrap_or(false);
908
909                    if !is_primary {
910                        continue;
911                    }
912
913                    // Filter to our file
914                    if !file_str.ends_with(span_file)
915                        && !span_file.ends_with(&*file_str)
916                        && span_file != &*file_str
917                    {
918                        continue;
919                    }
920
921                    let line_num =
922                        span.get("line_start").and_then(|l| l.as_u64()).unwrap_or(0) as u32;
923                    let col_num = span
924                        .get("column_start")
925                        .and_then(|c| c.as_u64())
926                        .unwrap_or(0) as u32;
927
928                    errors.push(ValidationError {
929                        line: line_num,
930                        column: col_num,
931                        message: text.clone(),
932                        severity: level.to_string(),
933                    });
934                }
935            }
936        }
937    }
938    errors
939}
940
941/// Parse go vet output lines like: `path:line:col: message`
942fn parse_go_vet_output(stderr: &str, file: &Path) -> Vec<ValidationError> {
943    let mut errors = Vec::new();
944    let file_str = file.to_string_lossy();
945
946    for line in stderr.lines() {
947        // Format: path:line:col: message  OR  path:line: message
948        let parts: Vec<&str> = line.splitn(4, ':').collect();
949        if parts.len() < 3 {
950            continue;
951        }
952
953        let err_file = parts[0].trim();
954        if !file_str.ends_with(err_file)
955            && !err_file.ends_with(&*file_str)
956            && err_file != &*file_str
957        {
958            continue;
959        }
960
961        let line_num: u32 = parts[1].trim().parse().unwrap_or(0);
962        let (col_num, message) = if parts.len() >= 4 {
963            if let Ok(col) = parts[2].trim().parse::<u32>() {
964                (col, parts[3].trim().to_string())
965            } else {
966                // parts[2] is part of the message, not a column
967                (0, format!("{}:{}", parts[2].trim(), parts[3].trim()))
968            }
969        } else {
970            (0, parts[2].trim().to_string())
971        };
972
973        errors.push(ValidationError {
974            line: line_num,
975            column: col_num,
976            message,
977            severity: "error".to_string(),
978        });
979    }
980    errors
981}
982
983/// Run the project's type checker and return structured validation errors.
984///
985/// Returns `(errors, skip_reason)`:
986/// - `(errors, None)` — checker ran, errors may be empty (= valid code)
987/// - `([], Some(reason))` — checker was skipped
988///
989/// Skip reasons: `"unsupported_language"`, `"not_found"`, `"timeout"`, `"error"`
990pub fn validate_full(path: &Path, config: &Config) -> (Vec<ValidationError>, Option<String>) {
991    let lang = match detect_language(path) {
992        Some(l) => l,
993        None => {
994            log::debug!(
995                "[aft] validate: {} (skipped: unsupported_language)",
996                path.display()
997            );
998            return (Vec::new(), Some("unsupported_language".to_string()));
999        }
1000    };
1001
1002    let (cmd, args) = match detect_type_checker(path, lang, config) {
1003        Some(pair) => pair,
1004        None => {
1005            log::warn!("validate: {} (skipped: not_found)", path.display());
1006            return (Vec::new(), Some("not_found".to_string()));
1007        }
1008    };
1009
1010    let arg_refs: Vec<&str> = args.iter().map(|s| s.as_str()).collect();
1011
1012    // Type checkers may need to run from the project root
1013    let working_dir = path.parent();
1014
1015    match run_external_tool_capture(
1016        &cmd,
1017        &arg_refs,
1018        working_dir,
1019        config.type_checker_timeout_secs,
1020    ) {
1021        Ok(result) => {
1022            let errors = parse_checker_output(&result.stdout, &result.stderr, path, &cmd);
1023            log::debug!(
1024                "[aft] validate: {} ({}, {} errors)",
1025                path.display(),
1026                cmd,
1027                errors.len()
1028            );
1029            (errors, None)
1030        }
1031        Err(FormatError::Timeout { .. }) => {
1032            log::error!("validate: {} (skipped: timeout)", path.display());
1033            (Vec::new(), Some("timeout".to_string()))
1034        }
1035        Err(FormatError::NotFound { .. }) => {
1036            log::warn!("validate: {} (skipped: not_found)", path.display());
1037            (Vec::new(), Some("not_found".to_string()))
1038        }
1039        Err(FormatError::Failed { stderr, .. }) => {
1040            log::debug!(
1041                "[aft] validate: {} (skipped: error: {})",
1042                path.display(),
1043                stderr.lines().next().unwrap_or("unknown")
1044            );
1045            (Vec::new(), Some("error".to_string()))
1046        }
1047        Err(FormatError::UnsupportedLanguage) => {
1048            log::debug!(
1049                "[aft] validate: {} (skipped: unsupported_language)",
1050                path.display()
1051            );
1052            (Vec::new(), Some("unsupported_language".to_string()))
1053        }
1054    }
1055}
1056
1057#[cfg(test)]
1058mod tests {
1059    use super::*;
1060    use std::fs;
1061    use std::io::Write;
1062
1063    #[test]
1064    fn run_external_tool_not_found() {
1065        let result = run_external_tool("__nonexistent_tool_xyz__", &[], None, 5);
1066        assert!(result.is_err());
1067        match result.unwrap_err() {
1068            FormatError::NotFound { tool } => {
1069                assert_eq!(tool, "__nonexistent_tool_xyz__");
1070            }
1071            other => panic!("expected NotFound, got: {:?}", other),
1072        }
1073    }
1074
1075    #[test]
1076    fn run_external_tool_timeout_kills_subprocess() {
1077        // Use `sleep 60` as a long-running process, timeout after 1 second
1078        let result = run_external_tool("sleep", &["60"], None, 1);
1079        assert!(result.is_err());
1080        match result.unwrap_err() {
1081            FormatError::Timeout { tool, timeout_secs } => {
1082                assert_eq!(tool, "sleep");
1083                assert_eq!(timeout_secs, 1);
1084            }
1085            other => panic!("expected Timeout, got: {:?}", other),
1086        }
1087    }
1088
1089    #[test]
1090    fn run_external_tool_success() {
1091        let result = run_external_tool("echo", &["hello"], None, 5);
1092        assert!(result.is_ok());
1093        let res = result.unwrap();
1094        assert_eq!(res.exit_code, 0);
1095        assert!(res.stdout.contains("hello"));
1096    }
1097
1098    #[test]
1099    fn run_external_tool_nonzero_exit() {
1100        // `false` always exits with code 1
1101        let result = run_external_tool("false", &[], None, 5);
1102        assert!(result.is_err());
1103        match result.unwrap_err() {
1104            FormatError::Failed { tool, .. } => {
1105                assert_eq!(tool, "false");
1106            }
1107            other => panic!("expected Failed, got: {:?}", other),
1108        }
1109    }
1110
1111    #[test]
1112    fn auto_format_unsupported_language() {
1113        let dir = tempfile::tempdir().unwrap();
1114        let path = dir.path().join("file.txt");
1115        fs::write(&path, "hello").unwrap();
1116
1117        let config = Config::default();
1118        let (formatted, reason) = auto_format(&path, &config);
1119        assert!(!formatted);
1120        assert_eq!(reason.as_deref(), Some("unsupported_language"));
1121    }
1122
1123    #[test]
1124    fn detect_formatter_rust_when_rustfmt_available() {
1125        let dir = tempfile::tempdir().unwrap();
1126        fs::write(dir.path().join("Cargo.toml"), "[package]\nname = \"test\"").unwrap();
1127        let path = dir.path().join("test.rs");
1128        let config = Config {
1129            project_root: Some(dir.path().to_path_buf()),
1130            ..Config::default()
1131        };
1132        let result = detect_formatter(&path, LangId::Rust, &config);
1133        if tool_available("rustfmt") {
1134            let (cmd, args) = result.unwrap();
1135            assert_eq!(cmd, "rustfmt");
1136            assert!(args.iter().any(|a| a.ends_with("test.rs")));
1137        } else {
1138            assert!(result.is_none());
1139        }
1140    }
1141
1142    #[test]
1143    fn detect_formatter_go_mapping() {
1144        let dir = tempfile::tempdir().unwrap();
1145        fs::write(dir.path().join("go.mod"), "module test\ngo 1.21").unwrap();
1146        let path = dir.path().join("main.go");
1147        let config = Config {
1148            project_root: Some(dir.path().to_path_buf()),
1149            ..Config::default()
1150        };
1151        let result = detect_formatter(&path, LangId::Go, &config);
1152        if tool_available("goimports") {
1153            let (cmd, args) = result.unwrap();
1154            assert_eq!(cmd, "goimports");
1155            assert!(args.contains(&"-w".to_string()));
1156        } else if tool_available("gofmt") {
1157            let (cmd, args) = result.unwrap();
1158            assert_eq!(cmd, "gofmt");
1159            assert!(args.contains(&"-w".to_string()));
1160        } else {
1161            assert!(result.is_none());
1162        }
1163    }
1164
1165    #[test]
1166    fn detect_formatter_python_mapping() {
1167        let dir = tempfile::tempdir().unwrap();
1168        fs::write(dir.path().join("ruff.toml"), "").unwrap();
1169        let path = dir.path().join("main.py");
1170        let config = Config {
1171            project_root: Some(dir.path().to_path_buf()),
1172            ..Config::default()
1173        };
1174        let result = detect_formatter(&path, LangId::Python, &config);
1175        if ruff_format_available() {
1176            let (cmd, args) = result.unwrap();
1177            assert_eq!(cmd, "ruff");
1178            assert!(args.contains(&"format".to_string()));
1179        } else {
1180            assert!(result.is_none());
1181        }
1182    }
1183
1184    #[test]
1185    fn detect_formatter_no_config_returns_none() {
1186        let path = Path::new("test.ts");
1187        let result = detect_formatter(path, LangId::TypeScript, &Config::default());
1188        assert!(
1189            result.is_none(),
1190            "expected no formatter without project config"
1191        );
1192    }
1193
1194    #[test]
1195    fn detect_formatter_explicit_override() {
1196        let path = Path::new("test.ts");
1197        let mut config = Config::default();
1198        config
1199            .formatter
1200            .insert("typescript".to_string(), "biome".to_string());
1201        let result = detect_formatter(path, LangId::TypeScript, &config);
1202        let (cmd, _) = result.unwrap();
1203        assert_eq!(cmd, "biome");
1204    }
1205
1206    #[test]
1207    fn auto_format_happy_path_rustfmt() {
1208        if !tool_available("rustfmt") {
1209            log::warn!("skipping: rustfmt not available");
1210            return;
1211        }
1212
1213        let dir = tempfile::tempdir().unwrap();
1214        fs::write(dir.path().join("Cargo.toml"), "[package]\nname = \"test\"").unwrap();
1215        let path = dir.path().join("test.rs");
1216
1217        let mut f = fs::File::create(&path).unwrap();
1218        writeln!(f, "fn    main()   {{  println!(\"hello\");  }}").unwrap();
1219        drop(f);
1220
1221        let config = Config {
1222            project_root: Some(dir.path().to_path_buf()),
1223            ..Config::default()
1224        };
1225        let (formatted, reason) = auto_format(&path, &config);
1226        assert!(formatted, "expected formatting to succeed");
1227        assert!(reason.is_none());
1228
1229        let content = fs::read_to_string(&path).unwrap();
1230        assert!(
1231            !content.contains("fn    main"),
1232            "expected rustfmt to fix spacing"
1233        );
1234    }
1235
1236    #[test]
1237    fn parse_tsc_output_basic() {
1238        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";
1239        let file = Path::new("src/app.ts");
1240        let errors = parse_tsc_output(stdout, "", file);
1241        assert_eq!(errors.len(), 2);
1242        assert_eq!(errors[0].line, 10);
1243        assert_eq!(errors[0].column, 5);
1244        assert_eq!(errors[0].severity, "error");
1245        assert!(errors[0].message.contains("TS2322"));
1246        assert_eq!(errors[1].line, 20);
1247    }
1248
1249    #[test]
1250    fn parse_tsc_output_filters_other_files() {
1251        let stdout =
1252            "other.ts(1,1): error TS2322: wrong file\nsrc/app.ts(5,3): error TS1234: our file\n";
1253        let file = Path::new("src/app.ts");
1254        let errors = parse_tsc_output(stdout, "", file);
1255        assert_eq!(errors.len(), 1);
1256        assert_eq!(errors[0].line, 5);
1257    }
1258
1259    #[test]
1260    fn parse_cargo_output_basic() {
1261        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}]}}"#;
1262        let file = Path::new("src/main.rs");
1263        let errors = parse_cargo_output(json_line, "", file);
1264        assert_eq!(errors.len(), 1);
1265        assert_eq!(errors[0].line, 10);
1266        assert_eq!(errors[0].column, 5);
1267        assert_eq!(errors[0].severity, "error");
1268        assert!(errors[0].message.contains("mismatched types"));
1269    }
1270
1271    #[test]
1272    fn parse_cargo_output_skips_notes() {
1273        // Notes and help messages should be filtered out
1274        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}]}}"#;
1275        let file = Path::new("src/main.rs");
1276        let errors = parse_cargo_output(json_line, "", file);
1277        assert_eq!(errors.len(), 0);
1278    }
1279
1280    #[test]
1281    fn parse_cargo_output_filters_other_files() {
1282        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}]}}"#;
1283        let file = Path::new("src/main.rs");
1284        let errors = parse_cargo_output(json_line, "", file);
1285        assert_eq!(errors.len(), 0);
1286    }
1287
1288    #[test]
1289    fn parse_go_vet_output_basic() {
1290        let stderr = "main.go:10:5: unreachable code\nmain.go:20: another issue\n";
1291        let file = Path::new("main.go");
1292        let errors = parse_go_vet_output(stderr, file);
1293        assert_eq!(errors.len(), 2);
1294        assert_eq!(errors[0].line, 10);
1295        assert_eq!(errors[0].column, 5);
1296        assert!(errors[0].message.contains("unreachable code"));
1297        assert_eq!(errors[1].line, 20);
1298        assert_eq!(errors[1].column, 0);
1299    }
1300
1301    #[test]
1302    fn parse_pyright_output_basic() {
1303        let stdout = r#"{"generalDiagnostics":[{"file":"test.py","range":{"start":{"line":4,"character":10}},"message":"Type error here","severity":"error"}]}"#;
1304        let file = Path::new("test.py");
1305        let errors = parse_pyright_output(stdout, file);
1306        assert_eq!(errors.len(), 1);
1307        assert_eq!(errors[0].line, 5); // 0-indexed → 1-indexed
1308        assert_eq!(errors[0].column, 10);
1309        assert_eq!(errors[0].severity, "error");
1310        assert!(errors[0].message.contains("Type error here"));
1311    }
1312
1313    #[test]
1314    fn validate_full_unsupported_language() {
1315        let dir = tempfile::tempdir().unwrap();
1316        let path = dir.path().join("file.txt");
1317        fs::write(&path, "hello").unwrap();
1318
1319        let config = Config::default();
1320        let (errors, reason) = validate_full(&path, &config);
1321        assert!(errors.is_empty());
1322        assert_eq!(reason.as_deref(), Some("unsupported_language"));
1323    }
1324
1325    #[test]
1326    fn detect_type_checker_rust() {
1327        let dir = tempfile::tempdir().unwrap();
1328        fs::write(dir.path().join("Cargo.toml"), "[package]\nname = \"test\"").unwrap();
1329        let path = dir.path().join("src/main.rs");
1330        let config = Config {
1331            project_root: Some(dir.path().to_path_buf()),
1332            ..Config::default()
1333        };
1334        let result = detect_type_checker(&path, LangId::Rust, &config);
1335        if tool_available("cargo") {
1336            let (cmd, args) = result.unwrap();
1337            assert_eq!(cmd, "cargo");
1338            assert!(args.contains(&"check".to_string()));
1339        } else {
1340            assert!(result.is_none());
1341        }
1342    }
1343
1344    #[test]
1345    fn detect_type_checker_go() {
1346        let dir = tempfile::tempdir().unwrap();
1347        fs::write(dir.path().join("go.mod"), "module test\ngo 1.21").unwrap();
1348        let path = dir.path().join("main.go");
1349        let config = Config {
1350            project_root: Some(dir.path().to_path_buf()),
1351            ..Config::default()
1352        };
1353        let result = detect_type_checker(&path, LangId::Go, &config);
1354        if tool_available("go") {
1355            let (cmd, _args) = result.unwrap();
1356            // Could be staticcheck or go vet depending on what's installed
1357            assert!(cmd == "go" || cmd == "staticcheck");
1358        } else {
1359            assert!(result.is_none());
1360        }
1361    }
1362    #[test]
1363    fn run_external_tool_capture_nonzero_not_error() {
1364        // `false` exits with code 1 — capture should still return Ok
1365        let result = run_external_tool_capture("false", &[], None, 5);
1366        assert!(result.is_ok(), "capture should not error on non-zero exit");
1367        assert_eq!(result.unwrap().exit_code, 1);
1368    }
1369
1370    #[test]
1371    fn run_external_tool_capture_not_found() {
1372        let result = run_external_tool_capture("__nonexistent_xyz__", &[], None, 5);
1373        assert!(result.is_err());
1374        match result.unwrap_err() {
1375            FormatError::NotFound { tool } => assert_eq!(tool, "__nonexistent_xyz__"),
1376            other => panic!("expected NotFound, got: {:?}", other),
1377        }
1378    }
1379}