use std::fs::write;
use std::{borrow::Cow, fs::read_to_string};
use jimtcl::tcl_error;
use jimtcl::{Interp, JimError, JimObject, JimResult, check_or_error, custom::JimExtensionType};
use toml::from_str;
use toml::{to_string, to_string_pretty};
use super::TypedData;
pub fn td_parse_toml<'jim>(
_interp: &'jim Interp,
args: &[JimObject<'jim>],
) -> JimResult<TypedData> {
let usage = "usage: td parse toml ?-file? <input>";
check_or_error!(args.len() >= 2, usage);
let data: Cow<'_, str> = if args[1].as_str()? == "-file" {
check_or_error!(args.len() == 3, usage);
let path = &args[2];
path.require_untainted("path")?;
read_to_string(path.as_str()?)?.into()
} else {
check_or_error!(args.len() == 2, usage);
args[1].as_str()?.into()
};
let data = from_str(&data).map_err(JimError::wrap)?;
Ok(data)
}
pub fn td_dump_toml<'jim>(_interp: &'jim Interp, args: &[JimObject<'jim>]) -> JimResult<String> {
let usage = "usage: td dump toml ?-pretty? <td>";
let mut pretty = false;
let mut out_file = None;
let mut pos = 1;
while pos < args.len() {
let arg = &args[pos];
let astr = arg.as_str()?;
if astr == "-pretty" {
pretty = true;
pos += 1;
} else if astr == "-file" {
let path = &args[pos + 1];
path.require_untainted("path")?;
out_file = Some(path.as_str()?);
pos += 2;
} else if astr == "--" {
pos += 1;
break;
} else if astr.starts_with("-") {
return Err(tcl_error!("invalid option {}", astr));
} else {
break;
}
}
check_or_error!(pos == args.len() - 1, usage);
let data = TypedData::extract(&args[pos])?;
let text = if pretty {
to_string_pretty(&data)
} else {
to_string(&data)
};
let text = text.map_err(|e| tcl_error!("could not generate JSON: {}", e))?;
if let Some(f) = out_file {
write(f, text.as_bytes())?;
Ok("".into())
} else {
Ok(text)
}
}