Skip to main content

zoi_lua/api/
parse.rs

1use mlua::{self, Lua, LuaSerdeExt, Table};
2
3/// Exposes data parsing utilities to the Lua environment.
4///
5/// These helpers allow package scripts to easily consume structured data
6/// commonly found in upstream projects:
7/// - `json`/`yaml`/`toml`: Parsers for structured configuration files.
8/// - `checksumFile`: A specialized parser for standard checksum files (e.g. `sha256sums`).
9///
10/// These utilities return native Lua tables, allowing for idiomatic manipulation
11/// of complex data within the package script.
12pub fn add_parse_util(lua: &Lua) -> Result<(), mlua::Error> {
13    let parse_table = lua.create_table()?;
14
15    let json_fn = lua.create_function(|lua, json_str: String| {
16        let value: serde_json::Value = serde_json::from_str(&json_str)
17            .map_err(|e| mlua::Error::RuntimeError(e.to_string()))?;
18        lua.to_value(&value)
19    })?;
20    parse_table.set("json", json_fn)?;
21
22    let yaml_fn = lua.create_function(|lua, yaml_str: String| {
23        let value: serde_yaml::Value = serde_yaml::from_str(&yaml_str)
24            .map_err(|e| mlua::Error::RuntimeError(e.to_string()))?;
25        lua.to_value(&value)
26    })?;
27    parse_table.set("yaml", yaml_fn)?;
28
29    let toml_fn = lua.create_function(|lua, toml_str: String| {
30        let value: toml::Value =
31            toml::from_str(&toml_str).map_err(|e| mlua::Error::RuntimeError(e.to_string()))?;
32        lua.to_value(&value)
33    })?;
34    parse_table.set("toml", toml_fn)?;
35
36    let checksum_fn = lua.create_function(|_, (content, file_name): (String, String)| {
37        for line in content.lines() {
38            let parts: Vec<&str> = line.split_whitespace().collect();
39            if parts.len() == 2 && parts[1] == file_name {
40                return Ok(Some(parts[0].to_string()));
41            }
42        }
43        Ok(None)
44    })?;
45    parse_table.set("checksumFile", checksum_fn)?;
46
47    let utils_table: Table = lua.globals().get("UTILS")?;
48    utils_table.set("PARSE", parse_table)?;
49
50    Ok(())
51}