use super::FormatArgs;
use super::error::{CliError, CliResult, ExitCode};
use super::io_utils::{read_file, read_stdin, write_output as write_output_impl};
use crate::lsp::formatting::{ToonFormattingOptions, format_document};
use crate::parser;
pub fn execute(args: &FormatArgs) -> CliResult<()> {
let (content, _input_path) = read_input(args)?;
let (ast, errors) = parser::parse_with_errors(&content);
if !errors.is_empty() {
let error_msg = errors.iter().map(|e| e.kind.to_string()).collect::<Vec<_>>().join("; ");
return Err(CliError::Validation(error_msg));
}
let ast_node =
ast.ok_or_else(|| CliError::Validation("Failed to parse document".to_string()))?;
let options = ToonFormattingOptions { indent_size: args.indent as u32 };
let formatted = format_document(&ast_node, options)
.ok_or_else(|| CliError::Format("Failed to format document".to_string()))?;
if args.check {
if formatted != content {
return Err(CliError::FormatMismatch);
}
return Ok(());
}
write_output(args, &formatted)?;
Ok(())
}
fn read_input(args: &FormatArgs) -> CliResult<(String, Option<std::path::PathBuf>)> {
match &args.input {
Some(path) if path.as_os_str() == "-" => Ok((read_stdin()?, None)),
Some(path) => Ok((read_file(path)?, Some(path.clone()))),
None => Ok((read_stdin()?, None)),
}
}
fn write_output(args: &FormatArgs, content: &str) -> CliResult<()> {
write_output_impl(&args.output, content)
}
pub fn error_exit_code(error: &CliError) -> ExitCode {
match error {
CliError::Validation(_) => ExitCode::ValidationFailed,
CliError::FormatMismatch => ExitCode::Error,
_ => error.exit_code(),
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::io;
#[test]
fn test_format_simple_toon() {
let content = "key: value\n";
let (ast, errors) = parser::parse_with_errors(content);
assert!(errors.is_empty());
let ast_node = ast.unwrap();
let options = ToonFormattingOptions::default();
let formatted = format_document(&ast_node, options).unwrap();
assert!(formatted.contains("key"));
assert!(formatted.contains("value"));
}
#[test]
fn test_format_normalizes_spacing() {
let content = "key: value\n";
let (ast, errors) = parser::parse_with_errors(content);
assert!(errors.is_empty());
let ast_node = ast.unwrap();
let options = ToonFormattingOptions::default();
let formatted = format_document(&ast_node, options).unwrap();
assert!(formatted.contains("key: value"));
}
#[test]
fn test_format_with_custom_indent() {
let content = "server:\n host: localhost\n";
let (ast, errors) = parser::parse_with_errors(content);
assert!(errors.is_empty());
let ast_node = ast.unwrap();
let options = ToonFormattingOptions { indent_size: 4 };
let formatted = format_document(&ast_node, options).unwrap();
assert!(formatted.contains(" host:"));
}
#[test]
fn test_format_always_uses_spaces() {
let content = "server:\n host: localhost\n";
let (ast, errors) = parser::parse_with_errors(content);
assert!(errors.is_empty());
let ast_node = ast.unwrap();
let options = ToonFormattingOptions { indent_size: 2 };
let formatted = format_document(&ast_node, options).unwrap();
assert!(formatted.contains(" host:"));
assert!(!formatted.contains('\t'), "Output should not contain tabs");
}
#[test]
fn test_error_exit_code() {
let validation_err = CliError::Validation("test".to_string());
assert_eq!(error_exit_code(&validation_err), ExitCode::ValidationFailed);
let format_err = CliError::FormatMismatch;
assert_eq!(error_exit_code(&format_err), ExitCode::Error);
let io_err = CliError::Io(io::Error::new(io::ErrorKind::NotFound, "not found"));
assert_eq!(error_exit_code(&io_err), ExitCode::Error);
}
}