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        "getenv",
255        lua.create_function(|_, name: String| Ok(std::env::var(&name).ok()))?,
256    )?;
257
258    os.set(
259        "listdir",
260        lua.create_function(|_, path: String| {
261            let mut names: Vec<String> = std::fs::read_dir(&path)
262                .map_err(|error| mlua::Error::RuntimeError(error.to_string()))?
263                .filter_map(|entry| entry.ok())
264                .map(|entry| entry.file_name().to_string_lossy().to_string())
265                .collect();
266            names.sort();
267            Ok(names)
268        })?,
269    )?;
270
271    os.set(
272        "mkdir",
273        lua.create_function(|_, path: String| {
274            std::fs::create_dir_all(&path)
275                .map_err(|error| mlua::Error::RuntimeError(error.to_string()))?;
276            Ok(())
277        })?,
278    )?;
279
280    os.set(
281        "remove",
282        lua.create_function(|_, path: String| {
283            let path = std::path::Path::new(&path);
284            let result = if path.is_dir() {
285                std::fs::remove_dir_all(path)
286            } else {
287                std::fs::remove_file(path)
288            };
289            result.map_err(|error| mlua::Error::RuntimeError(error.to_string()))?;
290            Ok(())
291        })?,
292    )?;
293
294    os.set(
295        "rename",
296        lua.create_function(|_, (from, to): (String, String)| {
297            std::fs::rename(&from, &to)
298                .map_err(|error| mlua::Error::RuntimeError(error.to_string()))?;
299            Ok(())
300        })?,
301    )?;
302
303    os.set(
304        "stat",
305        lua.create_function(|lua, path: String| {
306            let meta = std::fs::metadata(&path)
307                .map_err(|error| mlua::Error::RuntimeError(error.to_string()))?;
308            let mut object = Map::new();
309            object.insert("size".into(), Json::from(meta.len()));
310            object.insert("is_dir".into(), Json::Bool(meta.is_dir()));
311            from_json(lua, &Json::Object(object))
312        })?,
313    )?;
314
315    Ok(())
316}
317
318/// A Luau value as JSON.
319pub fn to_json(value: &Value) -> mlua::Result<Json> {
320    Ok(match value {
321        Value::Nil => Json::Null,
322        Value::Boolean(on) => Json::Bool(*on),
323        Value::Integer(number) => Json::from(*number),
324        Value::Number(number) => Json::from(*number),
325        Value::String(text) => Json::String(
326            text.to_str()
327                .map_err(|error| mlua::Error::RuntimeError(error.to_string()))?
328                .to_string(),
329        ),
330        Value::Table(table) => {
331            let length = table.raw_len();
332            let mut list = Vec::new();
333            let mut object = Map::new();
334            for pair in table.clone().pairs::<Value, Value>() {
335                let (key, value) = pair?;
336                let value = to_json(&value)?;
337                match key {
338                    Value::Integer(index)
339                        if length > 0 && index >= 1 && index as usize <= length =>
340                    {
341                        list.push(value);
342                    }
343                    Value::String(name) => {
344                        let name = name
345                            .to_str()
346                            .map_err(|error| mlua::Error::RuntimeError(error.to_string()))?
347                            .to_string();
348                        object.insert(name, value);
349                    }
350                    _ => {}
351                }
352            }
353            if length > 0 && list.len() == length {
354                Json::Array(list)
355            } else {
356                Json::Object(object)
357            }
358        }
359        other => {
360            return Err(mlua::Error::RuntimeError(format!(
361                "cannot use {other:?} as data"
362            )))
363        }
364    })
365}
366
367/// JSON as a Luau value.
368pub fn from_json(lua: &Lua, value: &Json) -> mlua::Result<Value> {
369    Ok(match value {
370        Json::Null => Value::Nil,
371        Json::Bool(on) => Value::Boolean(*on),
372        Json::Number(number) => {
373            if let Some(number) = number.as_i64() {
374                Value::Integer(number)
375            } else {
376                Value::Number(number.as_f64().unwrap_or_default())
377            }
378        }
379        Json::String(text) => Value::String(lua.create_string(text)?),
380        Json::Array(items) => {
381            let table = lua.create_table()?;
382            for (index, item) in items.iter().enumerate() {
383                table.set(index + 1, from_json(lua, item)?)?;
384            }
385            Value::Table(table)
386        }
387        Json::Object(object) => {
388            let table = lua.create_table()?;
389            for (name, item) in object {
390                table.set(name.as_str(), from_json(lua, item)?)?;
391            }
392            Value::Table(table)
393        }
394    })
395}
396
397/// Parse comma separated values into rows of cells.
398fn parse_csv(text: &str) -> Vec<Json> {
399    let mut rows = Vec::new();
400    let mut row: Vec<Json> = Vec::new();
401    let mut cell = String::new();
402    let mut quoted = false;
403    let mut chars = text.chars().peekable();
404
405    while let Some(character) = chars.next() {
406        match character {
407            '"' if quoted => {
408                if chars.peek() == Some(&'"') {
409                    cell.push('"');
410                    chars.next();
411                } else {
412                    quoted = false;
413                }
414            }
415            '"' => quoted = true,
416            ',' if !quoted => {
417                row.push(Json::String(cell.clone()));
418                cell.clear();
419            }
420            '\n' if !quoted => {
421                row.push(Json::String(cell.clone()));
422                cell.clear();
423                rows.push(Json::Array(std::mem::take(&mut row)));
424            }
425            '\r' => {}
426            other => cell.push(other),
427        }
428    }
429    if !cell.is_empty() || !row.is_empty() {
430        row.push(Json::String(cell));
431        rows.push(Json::Array(row));
432    }
433    rows
434}
435
436/// Quote a cell if it needs it.
437fn quote(text: &str) -> String {
438    if text.contains([',', '"', '\n']) {
439        format!("\"{}\"", text.replace('"', "\"\""))
440    } else {
441        text.to_string()
442    }
443}