use std::{fs, ops::Deref, sync::Arc};
use imbl::vector;
use serde::{Deserialize, Serialize};
use crate::{model::{Graph, LibFunc, Param, FS_LIB}, runtime::{instruction::{Instruction, Instructions}, proc::ProcEnv, Error, Type, Val, Variable}};
pub fn fs_library(graph: &mut Graph) {
graph.insert_libfunc(read());
graph.insert_libfunc(write());
graph.insert_libfunc(read_string());
}
pub(self) fn read() -> LibFunc {
LibFunc {
library: FS_LIB.clone(),
name: "read".into(),
is_async: false,
docs: r#"# fs.read(path: str) -> blob
If available, will read a file from a path into a binary blob.
```rust
const bytes = fs.read("src/lib.rs");
```"#.into(),
params: vector![
Param { name: "path".into(), param_type: Type::Str, default: None }
],
return_type: None,
unbounded_args: false,
args_to_symbol_table: false,
func: Arc::new(|_as_ref, _arg_count, _env, _graph| {
let mut instructions = Instructions::default();
instructions.push(Arc::new(FsIns::Read));
Ok(instructions)
})
}
}
pub(self) fn read_string() -> LibFunc {
LibFunc {
library: FS_LIB.clone(),
name: "read_string".into(),
is_async: false,
docs: r#"# fs.read_string(path: str) -> str
If available, will read a file from a path into a string.
```rust
const content = fs.read_string("src/lib.rs");
```"#.into(),
params: vector![
Param { name: "path".into(), param_type: Type::Str, default: None }
],
return_type: None,
unbounded_args: false,
args_to_symbol_table: false,
func: Arc::new(|_as_ref, _arg_count, _env, _graph| {
let mut instructions = Instructions::default();
instructions.push(Arc::new(FsIns::ReadString));
Ok(instructions)
})
}
}
pub(self) fn write() -> LibFunc {
LibFunc {
library: FS_LIB.clone(),
name: "write".into(),
is_async: false,
docs: r#"# fs.write(path: str, content: str | blob) -> void
If available, will write content into a file at the given path. Will throw an error if the directory doesn't exist and will overwrite the file if it already exists.
```rust
fs.write("src/text.txt", "testing");
```"#.into(),
params: vector![
Param { name: "path".into(), param_type: Type::Str, default: None },
Param { name: "content".into(), param_type: Type::Union(vector![Type::Str, Type::Blob]), default: None }
],
return_type: None,
unbounded_args: false,
args_to_symbol_table: false,
func: Arc::new(|_as_ref, _arg_count, _env, _graph| {
let mut instructions = Instructions::default();
instructions.push(Arc::new(FsIns::Write));
Ok(instructions)
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum FsIns {
Read,
ReadString,
Write,
}
#[typetag::serde(name = "FsIns")]
impl Instruction for FsIns {
fn exec(&self, env: &mut ProcEnv, _graph: &mut Graph) -> Result<Option<Instructions> , Error> {
match self {
Self::Read => {
if let Some(var) = env.stack.pop() {
let path = var.val.read().to_string();
match fs::read(path) {
Ok(contents) => {
env.stack.push(Variable::val(Val::Blob(contents.into())));
},
Err(error) => {
return Err(Error::FsReadError(error.to_string()));
}
}
} else {
return Err(Error::FsReadStackError);
}
},
Self::ReadString => {
if let Some(var) = env.stack.pop() {
let path = var.val.read().to_string();
match fs::read_to_string(path) {
Ok(contents) => {
env.stack.push(Variable::val(Val::Str(contents.into())));
},
Err(error) => {
return Err(Error::FsReadStringError(error.to_string()));
}
}
} else {
return Err(Error::FsReadStringStackError);
}
},
Self::Write => { if let Some(content) = env.stack.pop() {
if let Some(path) = env.stack.pop() {
let path = path.val.read().to_string();
match content.val.read().deref() {
Val::Blob(content) => {
match fs::write(path, content) {
Ok(_) => {
return Ok(None);
},
Err(error) => {
return Err(Error::FsWriteError(error.to_string()));
}
}
},
val => {
let content = val.to_string();
match fs::write(path, content) {
Ok(_) => {
return Ok(None);
},
Err(error) => {
return Err(Error::FsWriteError(error.to_string()));
}
}
}
}
}
}
return Err(Error::FsWriteStackError);
},
}
Ok(None)
}
}