use crate::Result;
use crate::dir_context::PathResolver;
use crate::runtime::Runtime;
use crate::support::editor;
use mlua::{IntoLua, Lua, Table, Value};
pub fn init_module(lua: &Lua, runtime: &Runtime) -> Result<Table> {
let table = lua.create_table()?;
let rt = runtime.clone();
let open_file_fn = lua.create_function(move |lua, path: String| open_file(lua, &rt, path))?;
table.set("open_file", open_file_fn)?;
Ok(table)
}
fn open_file(lua: &Lua, runtime: &Runtime, path: String) -> mlua::Result<Value> {
let dir_context = runtime.dir_context();
let full_path = dir_context.resolve_path(runtime.session(), (&path).into(), PathResolver::WksDir, None)?;
if !full_path.is_file() {
return Err(crate::Error::custom(format!("File does not exist: {path}")).into());
}
match editor::open_file_auto(&full_path) {
Ok(editor_program) => {
let result = lua.create_table()?;
result.set("editor", editor_program.program())?;
result.into_lua(lua)
}
Err(_) => Ok(Value::Nil),
}
}
#[cfg(test)]
mod tests {
type Result<T> = core::result::Result<T, Box<dyn std::error::Error>>;
use crate::_test_support::{eval_lua, setup_lua};
use crate::script::aip_modules::aip_editor;
#[tokio::test]
async fn test_lua_editor_open_file_not_found() -> Result<()> {
let lua = setup_lua(aip_editor::init_module, "editor").await?;
let code = r#"return aip.editor.open_file("non_existent_file.txt")"#;
let res = eval_lua(&lua, code);
assert!(res.is_err(), "Should return error for non-existent file");
let err = res.unwrap_err();
assert!(
err.to_string().contains("File does not exist"),
"Error should mention file does not exist"
);
Ok(())
}
}