1use std::cell::RefCell;
10use std::fs::OpenOptions;
11use std::io::{Read, Write};
12use std::rc::Rc;
13
14use mlua::{Lua, Table, Value};
15use serde_json::{Map, Value as Json};
16
17pub fn register(lua: &Lua) -> mlua::Result<()> {
19 register_io(lua)?;
20 register_json(lua)?;
21 register_csv(lua)?;
22 register_os(lua)?;
23 Ok(())
24}
25
26fn register_io(lua: &Lua) -> mlua::Result<()> {
28 let io = lua.create_table()?;
29
30 io.set(
31 "open",
32 lua.create_function(|lua, (path, mode): (String, Option<String>)| {
33 let mode = mode.unwrap_or_else(|| "r".to_string());
34 let file = OpenOptions::new()
35 .read(mode.contains('r'))
36 .write(mode.contains('w'))
37 .append(mode.contains('a'))
38 .create(mode.contains('w') || mode.contains('a'))
39 .open(&path)
40 .map_err(|error| mlua::Error::RuntimeError(error.to_string()))?;
41 let file = Rc::new(RefCell::new(file));
42 let handle = lua.create_table()?;
43
44 let reader = file.clone();
45 handle.set(
46 "read",
47 lua.create_function(move |_, (what,): (Option<String>,)| {
48 let mut file = reader.borrow_mut();
49 let what = what.unwrap_or_else(|| "a".to_string());
50 let mut text = String::new();
51 match what.as_str() {
52 "a" => {
53 file.read_to_string(&mut text)
54 .map_err(|error| mlua::Error::RuntimeError(error.to_string()))?;
55 }
56 "l" => {
57 let mut bytes = Vec::new();
58 let mut byte = [0u8; 1];
59 loop {
60 match file.read(&mut byte) {
61 Ok(0) => break,
62 Ok(_) => {
63 if byte[0] == b'\n' {
64 break;
65 }
66 bytes.push(byte[0]);
67 }
68 Err(error) => {
69 return Err(mlua::Error::RuntimeError(error.to_string()))
70 }
71 }
72 }
73 text = String::from_utf8_lossy(&bytes).to_string();
74 }
75 "n" => {
76 let mut bytes = [0u8; 1];
77 let _ = file.read(&mut bytes);
78 text = String::from_utf8_lossy(&bytes).to_string();
79 }
80 other => {
81 return Err(mlua::Error::RuntimeError(format!(
82 "io.read takes a, l or n, not {other}"
83 )))
84 }
85 }
86 Ok(text)
87 })?,
88 )?;
89
90 let writer = file.clone();
91 handle.set(
92 "write",
93 lua.create_function(move |_, (text,): (String,)| {
94 let mut file = writer.borrow_mut();
95 file.write_all(text.as_bytes())
96 .map_err(|error| mlua::Error::RuntimeError(error.to_string()))?;
97 Ok(())
98 })?,
99 )?;
100
101 let closer = file.clone();
102 handle.set(
103 "close",
104 lua.create_function(move |_, ()| {
105 let _ = closer.borrow_mut().flush();
106 Ok(())
107 })?,
108 )?;
109
110 Ok(handle)
111 })?,
112 )?;
113
114 io.set(
115 "read",
116 lua.create_function(|_, (path,): (String,)| {
117 let text = std::fs::read_to_string(&path)
118 .map_err(|error| mlua::Error::RuntimeError(error.to_string()))?;
119 Ok(text)
120 })?,
121 )?;
122
123 io.set(
124 "write",
125 lua.create_function(|_, (path, text): (String, String)| {
126 std::fs::write(&path, text)
127 .map_err(|error| mlua::Error::RuntimeError(error.to_string()))?;
128 Ok(())
129 })?,
130 )?;
131
132 io.set(
133 "exists",
134 lua.create_function(|_, (path,): (String,)| Ok(std::path::Path::new(&path).exists()))?,
135 )?;
136
137 lua.globals().set("io", io)?;
138 Ok(())
139}
140
141fn register_json(lua: &Lua) -> mlua::Result<()> {
143 let json = lua.create_table()?;
144
145 json.set(
146 "encode",
147 lua.create_function(|_, value: Value| {
148 let value = to_json(&value)?;
149 let text = serde_json::to_string(&value)
150 .map_err(|error| mlua::Error::RuntimeError(error.to_string()))?;
151 Ok(text)
152 })?,
153 )?;
154
155 json.set(
156 "decode",
157 lua.create_function(|lua, text: String| {
158 let value: Json = serde_json::from_str(&text)
159 .map_err(|error| mlua::Error::RuntimeError(error.to_string()))?;
160 from_json(lua, &value)
161 })?,
162 )?;
163
164 lua.globals().set("json", json)?;
165 Ok(())
166}
167
168fn register_csv(lua: &Lua) -> mlua::Result<()> {
170 let csv = lua.create_table()?;
171
172 csv.set(
173 "decode",
174 lua.create_function(|lua, text: String| {
175 let rows = parse_csv(&text);
176 from_json(lua, &Json::Array(rows))
177 })?,
178 )?;
179
180 csv.set(
181 "encode",
182 lua.create_function(|_, rows: Value| {
183 let rows = to_json(&rows)?;
184 let rows = rows.as_array().cloned().unwrap_or_default();
185 Ok(rows
186 .iter()
187 .map(|row| {
188 row.as_array()
189 .map(|cells| {
190 cells
191 .iter()
192 .map(|cell| match cell {
193 Json::String(text) => quote(text),
194 other => other.to_string(),
195 })
196 .collect::<Vec<_>>()
197 .join(",")
198 })
199 .unwrap_or_default()
200 })
201 .collect::<Vec<_>>()
202 .join("\n"))
203 })?,
204 )?;
205
206 csv.set(
207 "read",
208 lua.create_function(|lua, path: String| {
209 let text = std::fs::read_to_string(&path)
210 .map_err(|error| mlua::Error::RuntimeError(error.to_string()))?;
211 let rows = parse_csv(&text);
212 from_json(lua, &Json::Array(rows))
213 })?,
214 )?;
215
216 csv.set(
217 "write",
218 lua.create_function(|_, (path, rows): (String, Value)| {
219 let rows = to_json(&rows)?;
220 let rows = rows.as_array().cloned().unwrap_or_default();
221 let text = rows
222 .iter()
223 .map(|row| {
224 row.as_array()
225 .map(|cells| {
226 cells
227 .iter()
228 .map(|cell| match cell {
229 Json::String(text) => quote(text),
230 other => other.to_string(),
231 })
232 .collect::<Vec<_>>()
233 .join(",")
234 })
235 .unwrap_or_default()
236 })
237 .collect::<Vec<_>>()
238 .join("\n");
239 std::fs::write(&path, text)
240 .map_err(|error| mlua::Error::RuntimeError(error.to_string()))?;
241 Ok(())
242 })?,
243 )?;
244
245 lua.globals().set("csv", csv)?;
246 Ok(())
247}
248
249fn register_os(lua: &Lua) -> mlua::Result<()> {
251 let os = lua.globals().get::<Table>("os")?;
252
253 os.set(
254 "listdir",
255 lua.create_function(|_, path: String| {
256 let mut names: Vec<String> = std::fs::read_dir(&path)
257 .map_err(|error| mlua::Error::RuntimeError(error.to_string()))?
258 .filter_map(|entry| entry.ok())
259 .map(|entry| entry.file_name().to_string_lossy().to_string())
260 .collect();
261 names.sort();
262 Ok(names)
263 })?,
264 )?;
265
266 os.set(
267 "mkdir",
268 lua.create_function(|_, path: String| {
269 std::fs::create_dir_all(&path)
270 .map_err(|error| mlua::Error::RuntimeError(error.to_string()))?;
271 Ok(())
272 })?,
273 )?;
274
275 os.set(
276 "remove",
277 lua.create_function(|_, path: String| {
278 let path = std::path::Path::new(&path);
279 let result = if path.is_dir() {
280 std::fs::remove_dir_all(path)
281 } else {
282 std::fs::remove_file(path)
283 };
284 result.map_err(|error| mlua::Error::RuntimeError(error.to_string()))?;
285 Ok(())
286 })?,
287 )?;
288
289 os.set(
290 "rename",
291 lua.create_function(|_, (from, to): (String, String)| {
292 std::fs::rename(&from, &to)
293 .map_err(|error| mlua::Error::RuntimeError(error.to_string()))?;
294 Ok(())
295 })?,
296 )?;
297
298 os.set(
299 "stat",
300 lua.create_function(|lua, path: String| {
301 let meta = std::fs::metadata(&path)
302 .map_err(|error| mlua::Error::RuntimeError(error.to_string()))?;
303 let mut object = Map::new();
304 object.insert("size".into(), Json::from(meta.len()));
305 object.insert("is_dir".into(), Json::Bool(meta.is_dir()));
306 from_json(lua, &Json::Object(object))
307 })?,
308 )?;
309
310 Ok(())
311}
312
313pub fn to_json(value: &Value) -> mlua::Result<Json> {
315 Ok(match value {
316 Value::Nil => Json::Null,
317 Value::Boolean(on) => Json::Bool(*on),
318 Value::Integer(number) => Json::from(*number),
319 Value::Number(number) => Json::from(*number),
320 Value::String(text) => Json::String(
321 text.to_str()
322 .map_err(|error| mlua::Error::RuntimeError(error.to_string()))?
323 .to_string(),
324 ),
325 Value::Table(table) => {
326 let length = table.raw_len();
327 let mut list = Vec::new();
328 let mut object = Map::new();
329 for pair in table.clone().pairs::<Value, Value>() {
330 let (key, value) = pair?;
331 let value = to_json(&value)?;
332 match key {
333 Value::Integer(index)
334 if length > 0 && index >= 1 && index as usize <= length =>
335 {
336 list.push(value);
337 }
338 Value::String(name) => {
339 let name = name
340 .to_str()
341 .map_err(|error| mlua::Error::RuntimeError(error.to_string()))?
342 .to_string();
343 object.insert(name, value);
344 }
345 _ => {}
346 }
347 }
348 if length > 0 && list.len() == length {
349 Json::Array(list)
350 } else {
351 Json::Object(object)
352 }
353 }
354 other => {
355 return Err(mlua::Error::RuntimeError(format!(
356 "cannot use {other:?} as data"
357 )))
358 }
359 })
360}
361
362pub fn from_json(lua: &Lua, value: &Json) -> mlua::Result<Value> {
364 Ok(match value {
365 Json::Null => Value::Nil,
366 Json::Bool(on) => Value::Boolean(*on),
367 Json::Number(number) => {
368 if let Some(number) = number.as_i64() {
369 Value::Integer(number)
370 } else {
371 Value::Number(number.as_f64().unwrap_or_default())
372 }
373 }
374 Json::String(text) => Value::String(lua.create_string(text)?),
375 Json::Array(items) => {
376 let table = lua.create_table()?;
377 for (index, item) in items.iter().enumerate() {
378 table.set(index + 1, from_json(lua, item)?)?;
379 }
380 Value::Table(table)
381 }
382 Json::Object(object) => {
383 let table = lua.create_table()?;
384 for (name, item) in object {
385 table.set(name.as_str(), from_json(lua, item)?)?;
386 }
387 Value::Table(table)
388 }
389 })
390}
391
392fn parse_csv(text: &str) -> Vec<Json> {
394 let mut rows = Vec::new();
395 let mut row: Vec<Json> = Vec::new();
396 let mut cell = String::new();
397 let mut quoted = false;
398 let mut chars = text.chars().peekable();
399
400 while let Some(character) = chars.next() {
401 match character {
402 '"' if quoted => {
403 if chars.peek() == Some(&'"') {
404 cell.push('"');
405 chars.next();
406 } else {
407 quoted = false;
408 }
409 }
410 '"' => quoted = true,
411 ',' if !quoted => {
412 row.push(Json::String(cell.clone()));
413 cell.clear();
414 }
415 '\n' if !quoted => {
416 row.push(Json::String(cell.clone()));
417 cell.clear();
418 rows.push(Json::Array(std::mem::take(&mut row)));
419 }
420 '\r' => {}
421 other => cell.push(other),
422 }
423 }
424 if !cell.is_empty() || !row.is_empty() {
425 row.push(Json::String(cell));
426 rows.push(Json::Array(row));
427 }
428 rows
429}
430
431fn quote(text: &str) -> String {
433 if text.contains([',', '"', '\n']) {
434 format!("\"{}\"", text.replace('"', "\"\""))
435 } else {
436 text.to_string()
437 }
438}