//! `wai-quantum fmt`: programs in the one layout the language server formats //! to ([`wai_quantum::engine::editor::format`]). A program whose brackets do //! not match, or that holds a character the language has no use for, is left //! as it is, with its line. use std::path::{Path, PathBuf}; /// Formats `files` (standard input for none or `-`): printed for one program, /// listed when not formatted with `check`, written back with `write`. The exit /// status: 0, or 1 when a program is not formatted (`check`) or is left as it is. pub fn main(files: &[PathBuf], check: bool, write: bool) -> i32 { let stdin = files.is_empty() || (files.len() == 1 && files[0] == Path::new("-")); if stdin { if write { eprintln!("wai-quantum: --write needs the files to write"); return 1; } let src = match crate::read_text(None) { Ok(s) => s, Err(e) => { eprintln!("wai-quantum: {e}"); return 1; } }; return match wai_quantum::engine::editor::format(&src) { Ok(f) if check => { if f == src { 0 } else { println!(""); 1 } } Ok(f) => { print!("{f}"); 0 } Err(e) => { eprintln!("{}", located("", &e)); 1 } }; } if files.len() > 1 && !check && !write { eprintln!("wai-quantum: give --write or --check to format more than one file"); return 1; } let mut status = 0; for p in files { let name = p.display(); let src = match std::fs::read_to_string(p) { Ok(s) => s, Err(e) => { eprintln!("{name}: {e}"); status = 1; continue; } }; match wai_quantum::engine::editor::format(&src) { Ok(f) if f == src => { if !check && !write { print!("{f}"); } } Ok(_) if check => { println!("{name}"); status = 1; } Ok(f) if write => { if let Err(e) = std::fs::write(p, &f) { eprintln!("{name}: {e}"); status = 1; } else { eprintln!("formatted {name}"); } } Ok(f) => print!("{f}"), Err(e) => { eprintln!("{}", located(&name.to_string(), &e)); status = 1; } } } status } /// A refusal as `file:line: problem`, or `file: problem` when it names no line. fn located(name: &str, e: &str) -> String { match e.strip_prefix("line ") { Some(rest) => format!("{name}:{rest}"), None => format!("{name}: {e}"), } }