maslc 1.0.1

Maduka Authorization Specification Language (MASL) toolchain and runtime
use std::fs;
use std::path::PathBuf;
use std::process::exit;

use crate::diagnostics::print_diagnostics;

/// Runs the `fmt` command on a single `.mdk` file.
pub fn run(path: PathBuf, check: bool, diff: bool) {
    let source = match fs::read_to_string(&path) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("Error reading file: {}", e);
            exit(1);
        }
    };

    match masl_parser::parse(&source) {
        Ok(ast) => {
            let formatted = masl_formatter::format(&ast);

            if formatted == source {
                if !check {
                    println!("Already formatted.");
                }
                exit(0);
            }

            if check {
                println!("File is not formatted.");
                exit(1);
            }

            if diff {
                println!("--- original");
                println!("+++ formatted");
                for line in formatted.lines() {
                    println!("+{}", line);
                }
                exit(0);
            }

            if let Err(e) = fs::write(&path, formatted) {
                eprintln!("Error writing file: {}", e);
                exit(1);
            }
            println!("Successfully formatted {}", path.display());
        }
        Err(e) => {
            print_diagnostics(&e, &source, path.to_str().unwrap_or(""));
            exit(1);
        }
    }
}