use std::cell::RefCell;
use std::fs::OpenOptions;
use std::io::{Read, Write};
use std::rc::Rc;
use mlua::{Lua, Table, Value};
use serde_json::{Map, Value as Json};
pub fn register(lua: &Lua) -> mlua::Result<()> {
register_io(lua)?;
register_json(lua)?;
register_csv(lua)?;
register_os(lua)?;
Ok(())
}
fn register_io(lua: &Lua) -> mlua::Result<()> {
let io = lua.create_table()?;
io.set(
"open",
lua.create_function(|lua, (path, mode): (String, Option<String>)| {
let mode = mode.unwrap_or_else(|| "r".to_string());
let file = OpenOptions::new()
.read(mode.contains('r'))
.write(mode.contains('w'))
.append(mode.contains('a'))
.create(mode.contains('w') || mode.contains('a'))
.open(&path)
.map_err(|error| mlua::Error::RuntimeError(error.to_string()))?;
let file = Rc::new(RefCell::new(file));
let handle = lua.create_table()?;
let reader = file.clone();
handle.set(
"read",
lua.create_function(move |_, (what,): (Option<String>,)| {
let mut file = reader.borrow_mut();
let what = what.unwrap_or_else(|| "a".to_string());
let mut text = String::new();
match what.as_str() {
"a" => {
file.read_to_string(&mut text)
.map_err(|error| mlua::Error::RuntimeError(error.to_string()))?;
}
"l" => {
let mut bytes = Vec::new();
let mut byte = [0u8; 1];
loop {
match file.read(&mut byte) {
Ok(0) => break,
Ok(_) => {
if byte[0] == b'\n' {
break;
}
bytes.push(byte[0]);
}
Err(error) => {
return Err(mlua::Error::RuntimeError(error.to_string()))
}
}
}
text = String::from_utf8_lossy(&bytes).to_string();
}
"n" => {
let mut bytes = [0u8; 1];
let _ = file.read(&mut bytes);
text = String::from_utf8_lossy(&bytes).to_string();
}
other => {
return Err(mlua::Error::RuntimeError(format!(
"io.read takes a, l or n, not {other}"
)))
}
}
Ok(text)
})?,
)?;
let writer = file.clone();
handle.set(
"write",
lua.create_function(move |_, (text,): (String,)| {
let mut file = writer.borrow_mut();
file.write_all(text.as_bytes())
.map_err(|error| mlua::Error::RuntimeError(error.to_string()))?;
Ok(())
})?,
)?;
let closer = file.clone();
handle.set(
"close",
lua.create_function(move |_, ()| {
let _ = closer.borrow_mut().flush();
Ok(())
})?,
)?;
Ok(handle)
})?,
)?;
io.set(
"read",
lua.create_function(|_, (path,): (String,)| {
let text = std::fs::read_to_string(&path)
.map_err(|error| mlua::Error::RuntimeError(error.to_string()))?;
Ok(text)
})?,
)?;
io.set(
"write",
lua.create_function(|_, (path, text): (String, String)| {
std::fs::write(&path, text)
.map_err(|error| mlua::Error::RuntimeError(error.to_string()))?;
Ok(())
})?,
)?;
io.set(
"exists",
lua.create_function(|_, (path,): (String,)| Ok(std::path::Path::new(&path).exists()))?,
)?;
lua.globals().set("io", io)?;
Ok(())
}
fn register_json(lua: &Lua) -> mlua::Result<()> {
let json = lua.create_table()?;
json.set(
"encode",
lua.create_function(|_, value: Value| {
let value = to_json(&value)?;
let text = serde_json::to_string(&value)
.map_err(|error| mlua::Error::RuntimeError(error.to_string()))?;
Ok(text)
})?,
)?;
json.set(
"decode",
lua.create_function(|lua, text: String| {
let value: Json = serde_json::from_str(&text)
.map_err(|error| mlua::Error::RuntimeError(error.to_string()))?;
from_json(lua, &value)
})?,
)?;
lua.globals().set("json", json)?;
Ok(())
}
fn register_csv(lua: &Lua) -> mlua::Result<()> {
let csv = lua.create_table()?;
csv.set(
"decode",
lua.create_function(|lua, text: String| {
let rows = parse_csv(&text);
from_json(lua, &Json::Array(rows))
})?,
)?;
csv.set(
"encode",
lua.create_function(|_, rows: Value| {
let rows = to_json(&rows)?;
let rows = rows.as_array().cloned().unwrap_or_default();
Ok(rows
.iter()
.map(|row| {
row.as_array()
.map(|cells| {
cells
.iter()
.map(|cell| match cell {
Json::String(text) => quote(text),
other => other.to_string(),
})
.collect::<Vec<_>>()
.join(",")
})
.unwrap_or_default()
})
.collect::<Vec<_>>()
.join("\n"))
})?,
)?;
csv.set(
"read",
lua.create_function(|lua, path: String| {
let text = std::fs::read_to_string(&path)
.map_err(|error| mlua::Error::RuntimeError(error.to_string()))?;
let rows = parse_csv(&text);
from_json(lua, &Json::Array(rows))
})?,
)?;
csv.set(
"write",
lua.create_function(|_, (path, rows): (String, Value)| {
let rows = to_json(&rows)?;
let rows = rows.as_array().cloned().unwrap_or_default();
let text = rows
.iter()
.map(|row| {
row.as_array()
.map(|cells| {
cells
.iter()
.map(|cell| match cell {
Json::String(text) => quote(text),
other => other.to_string(),
})
.collect::<Vec<_>>()
.join(",")
})
.unwrap_or_default()
})
.collect::<Vec<_>>()
.join("\n");
std::fs::write(&path, text)
.map_err(|error| mlua::Error::RuntimeError(error.to_string()))?;
Ok(())
})?,
)?;
lua.globals().set("csv", csv)?;
Ok(())
}
fn register_os(lua: &Lua) -> mlua::Result<()> {
let os = lua.globals().get::<Table>("os")?;
os.set(
"listdir",
lua.create_function(|_, path: String| {
let mut names: Vec<String> = std::fs::read_dir(&path)
.map_err(|error| mlua::Error::RuntimeError(error.to_string()))?
.filter_map(|entry| entry.ok())
.map(|entry| entry.file_name().to_string_lossy().to_string())
.collect();
names.sort();
Ok(names)
})?,
)?;
os.set(
"mkdir",
lua.create_function(|_, path: String| {
std::fs::create_dir_all(&path)
.map_err(|error| mlua::Error::RuntimeError(error.to_string()))?;
Ok(())
})?,
)?;
os.set(
"remove",
lua.create_function(|_, path: String| {
let path = std::path::Path::new(&path);
let result = if path.is_dir() {
std::fs::remove_dir_all(path)
} else {
std::fs::remove_file(path)
};
result.map_err(|error| mlua::Error::RuntimeError(error.to_string()))?;
Ok(())
})?,
)?;
os.set(
"rename",
lua.create_function(|_, (from, to): (String, String)| {
std::fs::rename(&from, &to)
.map_err(|error| mlua::Error::RuntimeError(error.to_string()))?;
Ok(())
})?,
)?;
os.set(
"stat",
lua.create_function(|lua, path: String| {
let meta = std::fs::metadata(&path)
.map_err(|error| mlua::Error::RuntimeError(error.to_string()))?;
let mut object = Map::new();
object.insert("size".into(), Json::from(meta.len()));
object.insert("is_dir".into(), Json::Bool(meta.is_dir()));
from_json(lua, &Json::Object(object))
})?,
)?;
Ok(())
}
pub fn to_json(value: &Value) -> mlua::Result<Json> {
Ok(match value {
Value::Nil => Json::Null,
Value::Boolean(on) => Json::Bool(*on),
Value::Integer(number) => Json::from(*number),
Value::Number(number) => Json::from(*number),
Value::String(text) => Json::String(
text.to_str()
.map_err(|error| mlua::Error::RuntimeError(error.to_string()))?
.to_string(),
),
Value::Table(table) => {
let length = table.raw_len();
let mut list = Vec::new();
let mut object = Map::new();
for pair in table.clone().pairs::<Value, Value>() {
let (key, value) = pair?;
let value = to_json(&value)?;
match key {
Value::Integer(index)
if length > 0 && index >= 1 && index as usize <= length =>
{
list.push(value);
}
Value::String(name) => {
let name = name
.to_str()
.map_err(|error| mlua::Error::RuntimeError(error.to_string()))?
.to_string();
object.insert(name, value);
}
_ => {}
}
}
if length > 0 && list.len() == length {
Json::Array(list)
} else {
Json::Object(object)
}
}
other => {
return Err(mlua::Error::RuntimeError(format!(
"cannot use {other:?} as data"
)))
}
})
}
pub fn from_json(lua: &Lua, value: &Json) -> mlua::Result<Value> {
Ok(match value {
Json::Null => Value::Nil,
Json::Bool(on) => Value::Boolean(*on),
Json::Number(number) => {
if let Some(number) = number.as_i64() {
Value::Integer(number)
} else {
Value::Number(number.as_f64().unwrap_or_default())
}
}
Json::String(text) => Value::String(lua.create_string(text)?),
Json::Array(items) => {
let table = lua.create_table()?;
for (index, item) in items.iter().enumerate() {
table.set(index + 1, from_json(lua, item)?)?;
}
Value::Table(table)
}
Json::Object(object) => {
let table = lua.create_table()?;
for (name, item) in object {
table.set(name.as_str(), from_json(lua, item)?)?;
}
Value::Table(table)
}
})
}
fn parse_csv(text: &str) -> Vec<Json> {
let mut rows = Vec::new();
let mut row: Vec<Json> = Vec::new();
let mut cell = String::new();
let mut quoted = false;
let mut chars = text.chars().peekable();
while let Some(character) = chars.next() {
match character {
'"' if quoted => {
if chars.peek() == Some(&'"') {
cell.push('"');
chars.next();
} else {
quoted = false;
}
}
'"' => quoted = true,
',' if !quoted => {
row.push(Json::String(cell.clone()));
cell.clear();
}
'\n' if !quoted => {
row.push(Json::String(cell.clone()));
cell.clear();
rows.push(Json::Array(std::mem::take(&mut row)));
}
'\r' => {}
other => cell.push(other),
}
}
if !cell.is_empty() || !row.is_empty() {
row.push(Json::String(cell));
rows.push(Json::Array(row));
}
rows
}
fn quote(text: &str) -> String {
if text.contains([',', '"', '\n']) {
format!("\"{}\"", text.replace('"', "\"\""))
} else {
text.to_string()
}
}