guartcl 0.5.0-beta4

Enhanced Jim Tcl.
Documentation
//! typedata YAML interchange

use std::fs::File;

use jimtcl::{
    Interp, JimError, JimObject, JimResult, check_or_error, custom::JimExtensionType, tcl_error,
};
use serde_yaml_ng::{to_string, to_writer};

use super::TypedData;

/// Parse YAML into a Typed Data structure.
pub fn td_parse_yaml<'jim>(
    _interp: &'jim Interp,
    args: &[JimObject<'jim>],
) -> JimResult<TypedData> {
    let usage = "usage: td parse yaml ?-file? <input>";
    check_or_error!(args.len() >= 2, usage);
    let res = if args[1].as_str()? == "-file" {
        check_or_error!(args.len() == 3, usage);
        let path = &args[2];
        path.require_untainted("path")?;
        let open = File::open(path.as_str()?)?;
        serde_yaml_ng::from_reader(open)
    } else {
        check_or_error!(args.len() == 2, usage);
        let data = args[1].as_bytes();
        serde_yaml_ng::from_slice(data)
    };

    res.map_err(JimError::wrap)
}

/// Save a TD structure as YAML.
pub fn td_dump_yaml<'jim>(_interp: &'jim Interp, args: &[JimObject<'jim>]) -> JimResult<String> {
    let usage = "usage: td dump yaml ?-file out? <td>";
    let mut out_file = None;
    let mut pos = 1;
    while pos < args.len() {
        let arg = &args[pos];
        let astr = arg.as_str()?;
        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])?;
    if let Some(f) = out_file {
        let mut out = File::options().write(true).truncate(true).open(f)?;
        to_writer(&mut out, &data).map_err(|e| tcl_error!("could not generate JSON: {}", e))?;
        Ok("".into())
    } else {
        let text = to_string(&data);
        text.map_err(|e| tcl_error!("could not generate JSON: {}", e))
    }
}