use super::*;
use std::{fs, io::Write, path::PathBuf};
pub struct FSFile {
pub file: File,
}
impl From<File> for FSFile {
fn from(value: File) -> Self {
Self { file: value }
}
}
impl LuaUserData for FSFile {
fn add_methods<M: LuaUserDataMethods<Self>>(methods: &mut M) {
methods.add_method_mut("write", |_, this, data: String| {
this.file.write_all(data.as_bytes())?;
Ok(())
});
methods.add_method_mut("read_line", |lua, this, _: ()| {
this.file.read_line_trim()?.into_lua(lua)
});
methods.add_method_mut("read_all", |lua, this, _: ()| {
this.file.read_everything()?.into_lua(lua)
});
methods.add_method_mut("flush", |_, this, _: ()| {
this.file.flush()?;
Ok(())
});
methods.add_method_mut("is_symlink", |_, this, _: ()| {
Ok(this.file.metadata()?.is_symlink())
});
methods.add_method_mut("is_file", |_, this, _: ()| {
Ok(this.file.metadata()?.is_file())
});
}
}
pub struct FS;
impl Module for FS {
fn load(&self, state: &mut State) -> Result<(), LuaError> {
let module = state.lua.create_table()?;
module.set(
"create",
state
.lua
.create_function(|_, path: PathBuf| match fs::File::create(path) {
Ok(f) => Ok(FSFile::from(f)),
Err(e) => Err(e.into()),
})?,
)?;
module.set(
"open",
state
.lua
.create_function(|_, path: PathBuf| match fs::File::open(path) {
Ok(f) => Ok(FSFile::from(f)),
Err(e) => Err(e.into()),
})?,
)?;
create_module(&state.lua, "autosway.fs", module)?;
Ok(())
}
}