banshee 0.2.10

PostgreSQL SQL parser, formatter, linter and language server.
Documentation
//! `banshee fix` — apply autofixes from fixable lint rules.

use std::path::PathBuf;

use anyhow::{Context, Result, bail};
use banshee_config::fixes::{apply_fixes, is_safe_fix, validate_fix_output};
use clap::Args;
use rayon::prelude::*;

use super::analysis;
use super::io::{self, gather_inputs};
use super::{Cli, exit};

#[derive(Args, Debug)]
pub struct FixArgs {
    /// Files or directories to fix. Use `-` or omit to read stdin.
    paths: Vec<PathBuf>,

    /// Print a unified-ish diff instead of writing changes.
    #[arg(long)]
    diff: bool,

    /// Include fixes that can change SQL behavior.
    #[arg(long)]
    unsafe_fixes: bool,

    /// Write changes to files. Implied unless `--diff` or stdin is used.
    #[arg(long)]
    write: bool,

    /// Do not print the per-file "fixed:" lines.
    #[arg(long)]
    quiet: bool,
}

pub fn run(args: &FixArgs, cli: &Cli) -> Result<u8> {
    let config = cli.load_config(&io::discovery_anchor(&args.paths))?;
    let inputs = gather_inputs(&args.paths)?;
    let provider = super::schema::resolve(&config)?;
    let provider_ref = provider
        .as_ref()
        .map(|p| p as &dyn banshee_hir::SchemaProvider);

    let columns = analysis::migration_columns(&inputs);

    // Compute the fixed text per file in parallel; `None` means unchanged.
    let candidates: Vec<_> = inputs
        .par_iter()
        .map(|input| {
            let analyzed = analysis::analyze(&input.text, &config, provider_ref, &columns);
            if analyzed.has_parse_errors {
                bail!("input has SQL parse errors");
            }
            let fixes = analyzed
                .diagnostics
                .iter()
                .filter(|d| args.unsafe_fixes || is_safe_fix(d.code))
                .filter_map(|d| d.fixes.first());
            let Some(out) = apply_fixes(&input.text, fixes) else {
                return Ok(None);
            };
            if out == input.text {
                return Ok(None);
            }
            validate_fix_output(&input.text, &out, &config.templater, args.unsafe_fixes)?;
            Ok(Some(out))
        })
        .collect();
    let fixed = inputs
        .iter()
        .zip(candidates)
        .map(|(input, result)| result.with_context(|| format!("cannot fix {}", input.label)))
        .collect::<Result<Vec<_>>>()?;

    let mut fixed_files = 0usize;
    for (input, fixed) in inputs.iter().zip(&fixed) {
        let Some(fixed) = fixed else {
            // Nothing to fix: pass stdin through unchanged.
            if input.path.is_none() && !args.diff {
                print!("{}", input.text);
            }
            continue;
        };
        fixed_files += 1;

        if args.diff {
            print_diff(&input.label, &input.text, fixed);
        } else if let Some(path) = &input.path {
            std::fs::write(path, fixed)?;
            if !args.quiet {
                eprintln!("fixed: {}", input.label);
            }
        } else {
            // stdin: emit fixed source to stdout.
            print!("{fixed}");
        }
    }

    if args.diff && fixed_files > 0 {
        return Ok(exit::FINDINGS);
    }
    Ok(exit::OK)
}

/// Prints a minimal line-oriented diff. Not a full unified diff, but enough to
/// review changes at a glance without pulling in a diff dependency.
fn print_diff(label: &str, before: &str, after: &str) {
    println!("--- {label}");
    println!("+++ {label} (fixed)");
    let before_lines: Vec<&str> = before.lines().collect();
    let after_lines: Vec<&str> = after.lines().collect();
    let max = before_lines.len().max(after_lines.len());
    for i in 0..max {
        match (before_lines.get(i), after_lines.get(i)) {
            (Some(b), Some(a)) if b == a => {}
            (Some(b), Some(a)) => {
                println!("-{b}");
                println!("+{a}");
            }
            (Some(b), None) => println!("-{b}"),
            (None, Some(a)) => println!("+{a}"),
            (None, None) => {}
        }
    }
}