Skip to main content

parquet_cli/
stdlib.rs

1//! The parts of a scripting environment the experiments need.
2//!
3//! Luau itself comes with the usual table, string, math and os libraries.
4//! What is missing for the work is the file and data plumbing: reading and
5//! writing files, JSON, CSV, and walking directories. Those are here, in Rust,
6//! so a script can do the whole round trip: read a fixture, filter it, write
7//! the result out.
8
9use 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
17/// Put the extra libraries into the state.
18pub 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
26/// `io` — reading and writing files.
27fn 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
141/// `json` — encoding and decoding JSON.
142fn 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
168/// `csv` — reading and writing comma separated values.
169fn 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
249/// The file parts of `os`.
250fn register_os(lua: &Lua) -> mlua::Result<()> {
251    let os = lua.globals().get::<Table>("os")?;
252
253    os.set(
254        "execute",
255        lua.create_function(|lua, command: String| {
256            let output = std::process::Command::new("sh")
257                .arg("-c")
258                .arg(&command)
259                .output()
260                .map_err(|error| mlua::Error::RuntimeError(error.to_string()))?;
261            let mut object = Map::new();
262            object.insert("ok".into(), Json::Bool(output.status.success()));
263            object.insert(
264                "code".into(),
265                Json::from(output.status.code().unwrap_or(-1) as i64),
266            );
267            object.insert(
268                "output".into(),
269                Json::String(String::from_utf8_lossy(&output.stdout).to_string()),
270            );
271            object.insert(
272                "error".into(),
273                Json::String(String::from_utf8_lossy(&output.stderr).to_string()),
274            );
275            from_json(lua, &Json::Object(object))
276        })?,
277    )?;
278
279    os.set(
280        "getenv",
281        lua.create_function(|_, name: String| Ok(std::env::var(&name).ok()))?,
282    )?;
283
284    os.set(
285        "listdir",
286        lua.create_function(|_, path: String| {
287            let mut names: Vec<String> = std::fs::read_dir(&path)
288                .map_err(|error| mlua::Error::RuntimeError(error.to_string()))?
289                .filter_map(|entry| entry.ok())
290                .map(|entry| entry.file_name().to_string_lossy().to_string())
291                .collect();
292            names.sort();
293            Ok(names)
294        })?,
295    )?;
296
297    os.set(
298        "mkdir",
299        lua.create_function(|_, path: String| {
300            std::fs::create_dir_all(&path)
301                .map_err(|error| mlua::Error::RuntimeError(error.to_string()))?;
302            Ok(())
303        })?,
304    )?;
305
306    os.set(
307        "remove",
308        lua.create_function(|_, path: String| {
309            let path = std::path::Path::new(&path);
310            let result = if path.is_dir() {
311                std::fs::remove_dir_all(path)
312            } else {
313                std::fs::remove_file(path)
314            };
315            result.map_err(|error| mlua::Error::RuntimeError(error.to_string()))?;
316            Ok(())
317        })?,
318    )?;
319
320    os.set(
321        "rename",
322        lua.create_function(|_, (from, to): (String, String)| {
323            std::fs::rename(&from, &to)
324                .map_err(|error| mlua::Error::RuntimeError(error.to_string()))?;
325            Ok(())
326        })?,
327    )?;
328
329    os.set(
330        "stat",
331        lua.create_function(|lua, path: String| {
332            let meta = std::fs::metadata(&path)
333                .map_err(|error| mlua::Error::RuntimeError(error.to_string()))?;
334            let mut object = Map::new();
335            object.insert("size".into(), Json::from(meta.len()));
336            object.insert("is_dir".into(), Json::Bool(meta.is_dir()));
337            from_json(lua, &Json::Object(object))
338        })?,
339    )?;
340
341    Ok(())
342}
343
344/// A Luau value as JSON.
345pub fn to_json(value: &Value) -> mlua::Result<Json> {
346    Ok(match value {
347        Value::Nil => Json::Null,
348        Value::Boolean(on) => Json::Bool(*on),
349        Value::Integer(number) => Json::from(*number),
350        Value::Number(number) => Json::from(*number),
351        Value::String(text) => Json::String(
352            text.to_str()
353                .map_err(|error| mlua::Error::RuntimeError(error.to_string()))?
354                .to_string(),
355        ),
356        Value::Table(table) => {
357            let length = table.raw_len();
358            let mut list = Vec::new();
359            let mut object = Map::new();
360            for pair in table.clone().pairs::<Value, Value>() {
361                let (key, value) = pair?;
362                let value = to_json(&value)?;
363                match key {
364                    Value::Integer(index)
365                        if length > 0 && index >= 1 && index as usize <= length =>
366                    {
367                        list.push(value);
368                    }
369                    Value::String(name) => {
370                        let name = name
371                            .to_str()
372                            .map_err(|error| mlua::Error::RuntimeError(error.to_string()))?
373                            .to_string();
374                        object.insert(name, value);
375                    }
376                    _ => {}
377                }
378            }
379            if length > 0 && list.len() == length {
380                Json::Array(list)
381            } else {
382                Json::Object(object)
383            }
384        }
385        other => {
386            return Err(mlua::Error::RuntimeError(format!(
387                "cannot use {other:?} as data"
388            )))
389        }
390    })
391}
392
393/// JSON as a Luau value.
394pub fn from_json(lua: &Lua, value: &Json) -> mlua::Result<Value> {
395    Ok(match value {
396        Json::Null => Value::Nil,
397        Json::Bool(on) => Value::Boolean(*on),
398        Json::Number(number) => {
399            if let Some(number) = number.as_i64() {
400                Value::Integer(number)
401            } else {
402                Value::Number(number.as_f64().unwrap_or_default())
403            }
404        }
405        Json::String(text) => Value::String(lua.create_string(text)?),
406        Json::Array(items) => {
407            let table = lua.create_table()?;
408            for (index, item) in items.iter().enumerate() {
409                table.set(index + 1, from_json(lua, item)?)?;
410            }
411            Value::Table(table)
412        }
413        Json::Object(object) => {
414            let table = lua.create_table()?;
415            for (name, item) in object {
416                table.set(name.as_str(), from_json(lua, item)?)?;
417            }
418            Value::Table(table)
419        }
420    })
421}
422
423/// Parse comma separated values into rows of cells.
424fn parse_csv(text: &str) -> Vec<Json> {
425    let mut rows = Vec::new();
426    let mut row: Vec<Json> = Vec::new();
427    let mut cell = String::new();
428    let mut quoted = false;
429    let mut chars = text.chars().peekable();
430
431    while let Some(character) = chars.next() {
432        match character {
433            '"' if quoted => {
434                if chars.peek() == Some(&'"') {
435                    cell.push('"');
436                    chars.next();
437                } else {
438                    quoted = false;
439                }
440            }
441            '"' => quoted = true,
442            ',' if !quoted => {
443                row.push(Json::String(cell.clone()));
444                cell.clear();
445            }
446            '\n' if !quoted => {
447                row.push(Json::String(cell.clone()));
448                cell.clear();
449                rows.push(Json::Array(std::mem::take(&mut row)));
450            }
451            '\r' => {}
452            other => cell.push(other),
453        }
454    }
455    if !cell.is_empty() || !row.is_empty() {
456        row.push(Json::String(cell));
457        rows.push(Json::Array(row));
458    }
459    rows
460}
461
462/// Quote a cell if it needs it.
463fn quote(text: &str) -> String {
464    if text.contains([',', '"', '\n']) {
465        format!("\"{}\"", text.replace('"', "\"\""))
466    } else {
467        text.to_string()
468    }
469}