use std::fs::File;
use std::io::{self, Write};
use super::convert::{decode_toon, write_json, write_yaml};
use super::error::{CliError, CliResult, ExitCode};
use super::io_utils::{read_file, read_stdin};
use super::{DecodeArgs, OutputFormat};
pub fn execute(args: &DecodeArgs) -> CliResult<()> {
if let Some(ref path) = args.input {
if path.is_dir() {
return batch_decode(path, args);
}
}
let toon_content = read_input(args)?;
let value = decode_toon(&toon_content).map_err(|e| {
CliError::Validation(e.to_string())
})?;
write_output(args, &value)?;
Ok(())
}
fn batch_decode(dir: &std::path::Path, args: &DecodeArgs) -> CliResult<()> {
let mut files = Vec::new();
walk_dir(dir, &mut files)?;
for path in files {
if path.is_file() {
if let Some(ext) = path.extension().and_then(|e| e.to_str()) {
if ext.to_lowercase() == "toon" {
let toon_content = std::fs::read_to_string(&path)?;
let value = decode_toon(&toon_content)
.map_err(|e| CliError::Validation(e.to_string()))?;
let mut out_path = path.clone();
match args.output_format {
OutputFormat::Json => {
out_path.set_extension("json");
let file = File::create(&out_path).map_err(|e| {
CliError::Io(io::Error::new(
e.kind(),
format!("Failed to create '{}': {}", out_path.display(), e),
))
})?;
write_json(file, &value, args.pretty)?;
}
OutputFormat::Yaml => {
out_path.set_extension("yaml");
let file = File::create(&out_path).map_err(|e| {
CliError::Io(io::Error::new(
e.kind(),
format!("Failed to create '{}': {}", out_path.display(), e),
))
})?;
write_yaml(file, &value)?;
}
}
}
}
}
}
Ok(())
}
fn walk_dir(dir: &std::path::Path, files: &mut Vec<std::path::PathBuf>) -> std::io::Result<()> {
if dir.is_dir() {
for entry in std::fs::read_dir(dir)? {
let entry = entry?;
let path = entry.path();
if path.is_dir() {
walk_dir(&path, files)?;
} else {
files.push(path);
}
}
}
Ok(())
}
fn read_input(args: &DecodeArgs) -> CliResult<String> {
match &args.input {
Some(path) if path.as_os_str() == "-" => read_stdin(),
Some(path) => read_file(path),
None => read_stdin(),
}
}
fn write_output(args: &DecodeArgs, value: &serde_json::Value) -> CliResult<()> {
if let Some(path) = &args.output {
let file = File::create(path).map_err(|e| {
CliError::Io(io::Error::new(
e.kind(),
format!("Failed to create '{}': {}", path.display(), e),
))
})?;
write_to_writer(file, args, value)
} else {
let stdout = io::stdout();
let handle = stdout.lock();
write_to_writer(handle, args, value)
}
}
fn write_to_writer<W: Write>(
writer: W,
args: &DecodeArgs,
value: &serde_json::Value,
) -> CliResult<()> {
match args.output_format {
OutputFormat::Json => write_json(writer, value, args.pretty),
OutputFormat::Yaml => write_yaml(writer, value),
}
}
pub fn error_exit_code(error: &CliError) -> ExitCode {
match error {
CliError::Validation(_) | CliError::Decode(_) => ExitCode::ValidationFailed,
_ => error.exit_code(),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_decode_simple_toon() {
let toon = "key: value\n";
let value = decode_toon(toon).expect("decode");
assert_eq!(value.get("key").and_then(|v| v.as_str()), Some("value"));
}
#[test]
fn test_decode_nested_toon() {
let toon = "server:\n host: localhost\n port: 8080\n";
let value = decode_toon(toon).expect("decode");
let server = value.get("server").expect("server key");
assert_eq!(server.get("host").and_then(|v| v.as_str()), Some("localhost"));
}
#[test]
fn test_error_exit_code() {
let validation_err = CliError::Validation("test".to_string());
assert_eq!(error_exit_code(&validation_err), ExitCode::ValidationFailed);
let decode_err = CliError::Decode("test".to_string());
assert_eq!(error_exit_code(&decode_err), ExitCode::ValidationFailed);
let io_err = CliError::Io(io::Error::new(io::ErrorKind::NotFound, "not found"));
assert_eq!(error_exit_code(&io_err), ExitCode::Error);
}
}