use crate::Error;
use crate::dir_context::PathResolver;
use crate::runtime::Runtime;
use crate::support::yamls;
use mlua::{IntoLua, Lua, Value};
use simple_fs::read_to_string;
pub(super) fn file_load_yaml(lua: &Lua, runtime: &Runtime, path: String) -> mlua::Result<Value> {
let full_path =
runtime
.dir_context()
.resolve_path(runtime.session(), path.clone().into(), PathResolver::WksDir, None)?;
let content = read_to_string(&full_path).map_err(|e| {
Error::from(format!(
"aip.file.load_yaml - Failed to read yaml file '{path}'.\nCause: {e}",
))
})?;
let yaml_docs = yamls::parse(&content).map_err(|e| {
Error::from(format!(
"aip.file.load_yaml - Failed to parse yaml file '{path}'.\nCause: {e}",
))
})?;
let lua_value = yaml_docs.into_lua(lua)?;
Ok(lua_value)
}
#[cfg(test)]
mod tests {
type Result<T> = core::result::Result<T, Box<dyn std::error::Error>>;
use crate::_test_support::{assert_contains, create_sanbox_01_tmp_file, run_reflective_agent};
use value_ext::JsonValueExt as _;
#[tokio::test]
async fn test_lua_file_load_yaml_ok() -> Result<()> {
let fx_file = create_sanbox_01_tmp_file(
"test_lua_file_load_yaml_ok.yaml",
r#"
title: Test YAML
---
name: Doc2
"#,
)?;
let fx_path = fx_file.as_str();
let res = run_reflective_agent(&format!(r#"return aip.file.load_yaml("{fx_path}")"#), None).await?;
let arr = res.as_array().ok_or("Should be array")?;
assert_eq!(arr.len(), 2);
assert_eq!(arr[0].x_get_str("title")?, "Test YAML");
assert_eq!(arr[1].x_get_str("name")?, "Doc2");
Ok(())
}
#[tokio::test]
async fn test_lua_file_load_yaml_file_not_found() -> Result<()> {
let fx_path = "other/non_existent_file.yaml";
let res = run_reflective_agent(&format!(r#"return aip.file.load_yaml("{fx_path}")"#), None).await;
let Err(err) = res else {
panic!("Should have returned an error");
};
assert_contains(&err.to_string(), "aip.file.load_yaml - Failed to read yaml file");
assert_contains(&err.to_string(), "non_existent_file.yaml");
Ok(())
}
}