use std::fs::File;
use std::io::{self, BufReader, Read, Write};
use std::path::Path;
use super::convert::{encode_json_with_indent, read_json, read_yaml};
use super::error::{CliError, CliResult};
use super::{EncodeArgs, InputFormat};
pub fn execute(args: &EncodeArgs) -> CliResult<()> {
if let Some(ref path) = args.input {
if path.is_dir() {
return batch_encode(path, args);
}
}
let format = detect_input_format(args)?;
let value = read_input(args, format)?;
let toon = encode_json_with_indent(&value, args.indent)?;
write_output(args, &toon)?;
Ok(())
}
fn batch_encode(dir: &Path, args: &EncodeArgs) -> 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()) {
let format = match ext.to_lowercase().as_str() {
"json" => Some(InputFormat::Json),
"yaml" | "yml" => Some(InputFormat::Yaml),
_ => None,
};
if let Some(fmt) = format {
let val = read_from_file(&path, fmt)?;
let toon = encode_json_with_indent(&val, args.indent)?;
let mut out_path = path.clone();
out_path.set_extension("toon");
let mut file = File::create(&out_path).map_err(|e| {
CliError::Io(io::Error::new(
e.kind(),
format!("Failed to create '{}': {}", out_path.display(), e),
))
})?;
file.write_all(toon.as_bytes())?;
}
}
}
}
Ok(())
}
fn walk_dir(dir: &Path, files: &mut Vec<std::path::PathBuf>) -> 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 detect_input_format(args: &EncodeArgs) -> CliResult<InputFormat> {
if let Some(ref path) = args.input {
if path.as_os_str() == "-" {
return Ok(args.input_format);
}
if let Some(ext) = path.extension().and_then(|e| e.to_str()) {
match ext.to_lowercase().as_str() {
"json" => return Ok(InputFormat::Json),
"yaml" | "yml" => return Ok(InputFormat::Yaml),
_ => {} }
}
}
Ok(args.input_format)
}
fn read_input(args: &EncodeArgs, format: InputFormat) -> CliResult<serde_json::Value> {
match &args.input {
Some(path) if path.as_os_str() == "-" => {
read_from_stdin(format)
}
Some(path) => {
read_from_file(path, format)
}
None => {
read_from_stdin(format)
}
}
}
fn read_from_stdin(format: InputFormat) -> CliResult<serde_json::Value> {
let stdin = io::stdin();
let reader = stdin.lock();
parse_input(reader, format)
}
fn read_from_file(path: &Path, format: InputFormat) -> CliResult<serde_json::Value> {
let file = File::open(path).map_err(|e| {
CliError::Io(io::Error::new(
e.kind(),
format!("Failed to open '{}': {}", path.display(), e),
))
})?;
let reader = BufReader::new(file);
parse_input(reader, format)
}
fn parse_input<R: Read>(reader: R, format: InputFormat) -> CliResult<serde_json::Value> {
match format {
InputFormat::Json => read_json(reader),
InputFormat::Yaml => read_yaml(reader),
}
}
fn write_output(args: &EncodeArgs, toon: &str) -> CliResult<()> {
if let Some(path) = &args.output {
let mut file = File::create(path).map_err(|e| {
CliError::Io(io::Error::new(
e.kind(),
format!("Failed to create '{}': {}", path.display(), e),
))
})?;
file.write_all(toon.as_bytes())?;
} else {
let stdout = io::stdout();
let mut handle = stdout.lock();
handle.write_all(toon.as_bytes())?;
}
Ok(())
}
pub fn error_exit_code(error: &super::error::CliError) -> super::error::ExitCode {
use super::error::{CliError, ExitCode};
match error {
CliError::Parse(_) | CliError::Encode(_) | CliError::Json(_) | CliError::Yaml(_) => {
ExitCode::ValidationFailed
}
_ => error.exit_code(),
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::path::PathBuf;
fn make_encode_args(input: Option<&str>, format: InputFormat) -> EncodeArgs {
EncodeArgs {
input: input.map(PathBuf::from),
output: None,
input_format: format,
indent: 2,
}
}
#[test]
fn test_detect_json_from_extension() {
let args = make_encode_args(Some("test.json"), InputFormat::Yaml);
let format = detect_input_format(&args).expect("detect format");
assert_eq!(format, InputFormat::Json);
}
#[test]
fn test_detect_yaml_from_extension() {
let args = make_encode_args(Some("test.yaml"), InputFormat::Json);
let format = detect_input_format(&args).expect("detect format");
assert_eq!(format, InputFormat::Yaml);
}
#[test]
fn test_detect_yml_from_extension() {
let args = make_encode_args(Some("test.yml"), InputFormat::Json);
let format = detect_input_format(&args).expect("detect format");
assert_eq!(format, InputFormat::Yaml);
}
#[test]
fn test_stdin_uses_explicit_format() {
let args = make_encode_args(Some("-"), InputFormat::Yaml);
let format = detect_input_format(&args).expect("detect format");
assert_eq!(format, InputFormat::Yaml);
}
#[test]
fn test_unknown_extension_uses_explicit_format() {
let args = make_encode_args(Some("test.txt"), InputFormat::Json);
let format = detect_input_format(&args).expect("detect format");
assert_eq!(format, InputFormat::Json);
}
#[test]
fn test_no_input_uses_explicit_format() {
let args = make_encode_args(None, InputFormat::Yaml);
let format = detect_input_format(&args).expect("detect format");
assert_eq!(format, InputFormat::Yaml);
}
#[test]
fn test_error_exit_code() {
use super::super::error::{CliError, ExitCode};
use std::io;
let parse_err = CliError::Parse("invalid JSON".to_string());
assert_eq!(error_exit_code(&parse_err), ExitCode::ValidationFailed);
let encode_err = CliError::Encode("encoding failed".to_string());
assert_eq!(error_exit_code(&encode_err), ExitCode::ValidationFailed);
let json_err = CliError::Json(serde_json::from_str::<()>("invalid").unwrap_err());
assert_eq!(error_exit_code(&json_err), ExitCode::ValidationFailed);
let yaml_err = CliError::Yaml(serde_yaml::from_str::<()>("invalid: [").unwrap_err());
assert_eq!(error_exit_code(&yaml_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);
}
}