Skip to content

Commit

Permalink
Merge pull request #2375 from dathere/luau_qsv_writejson
Browse files Browse the repository at this point in the history
`feat`: add `luau` qsv_writejson helper
  • Loading branch information
jqnatividad authored Dec 25, 2024
2 parents 36069bf + ea3592f commit f63864e
Show file tree
Hide file tree
Showing 3 changed files with 525 additions and 0 deletions.
77 changes: 77 additions & 0 deletions src/cmd/luau.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1827,6 +1827,83 @@ fn setup_helpers(
})?;
luau.globals().set("qsv_loadjson", qsv_loadjson)?;

// this is a helper function to save a Luau table to a JSON file.
//
// qsv_writejson(table_or_value: any, filepath: string, pretty: boolean)
// table_or_value: the Luau table or value to save as JSON
// filepath: the path of the JSON file to save
// pretty: whether to format the JSON with indentation (optional, defaults to false)
// returns: true if successful.
// A Luau runtime error if the filepath is invalid or JSON conversion fails.
//
let qsv_writejson = luau.create_function(
move |_, (table_or_value, filepath, pretty): (mlua::Value, String, Option<bool>)| {
use sanitize_filename::sanitize;

if filepath.is_empty() {
return helper_err!("qsv_writejson", "filepath cannot be empty.");
}

let sanitized_filename = sanitize(filepath);

// Convert Lua value to serde_json::Value using proper serialization
let json_value = if pretty.unwrap_or(false) {
match serde_json::to_string_pretty(&table_or_value) {
Ok(v) => v,
Err(e) => {
return helper_err!(
"qsv_writejson",
"Failed to convert Luau value to JSON: {e}"
);
},
}
} else {
match serde_json::to_string(&table_or_value) {
Ok(v) => v,
Err(e) => {
return helper_err!(
"qsv_writejson",
"Failed to convert Luau value to JSON: {e}"
);
},
}
};

// Create file
let file = match std::fs::OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.open(&sanitized_filename)
{
Ok(f) => f,
Err(e) => {
return helper_err!(
"qsv_writejson",
"Failed to create JSON file \"{sanitized_filename}\": {e}"
);
},
};
let mut file = std::io::BufWriter::with_capacity(DEFAULT_WTR_BUFFER_CAPACITY, file);

// Write JSON
if let Err(e) = file.write_all(json_value.as_bytes()) {
return helper_err!(
"qsv_writejson",
"Failed to write JSON to file \"{sanitized_filename}\": {e}"
);
}

info!(
"qsv_writejson() - saved {} bytes to file: {sanitized_filename}",
json_value.to_string().len()
);

Ok(true)
},
)?;
luau.globals().set("qsv_writejson", qsv_writejson)?;

// this is a helper function that can be called from the BEGIN, MAIN & END scripts to write to
// a file. The file will be created if it does not exist. The file will be appended to if it
// already exists. The filename will be sanitized and will be written to the current working
Expand Down
Loading

0 comments on commit f63864e

Please sign in to comment.