use crate::Result;
use mlua::{Lua, Table};
pub fn init_module(lua: &Lua, _runtime_context: &crate::run::RuntimeContext) -> Result<Table> {
let table = lua.create_table()?;
table.set("comment_line", lua.create_function(comment_line)?)?;
Ok(table)
}
fn comment_line(_lua: &Lua, (lang_ext, comment_content): (String, String)) -> mlua::Result<String> {
let ext = lang_ext.trim().to_lowercase();
let comment = match ext.as_str() {
"lua" | "sql" => format!("-- {}", comment_content),
"html" => format!("<!-- {} -->", comment_content),
"css" | "pcss" => format!("/* {} */", comment_content),
"py" => format!("# {}", comment_content),
_ => format!("// {}", comment_content),
};
Ok(comment)
}
#[cfg(test)]
mod tests {
type Result<T> = core::result::Result<T, Box<dyn std::error::Error>>;
use crate::_test_support::{eval_lua, setup_lua};
#[test]
fn test_code_comment_line_simple() -> Result<()> {
let lua = setup_lua(super::init_module, "code")?;
let test_cases = [
("rs", "Rust comment", "// Rust comment"),
("lua", "Lua comment", "-- Lua comment"),
("sql", "SQL comment", "-- SQL comment"),
("html", "HTML comment", "<!-- HTML comment -->"),
("css", "CSS comment", "/* CSS comment */"),
("pcss", "PCSS comment", "/* PCSS comment */"),
("py", "Python comment", "# Python comment"),
("js", "JavaScript comment", "// JavaScript comment"),
];
for (lang, content, expected) in test_cases.iter() {
let script = format!("return utils.code.comment_line({:?}, {:?})", lang, content);
let res = eval_lua(&lua, &script)?;
let res_str = res.as_str().ok_or("Expected a string result")?;
assert_eq!(
res_str, *expected,
"Failed for lang_ext: {} with content: {}",
lang, content
);
}
Ok(())
}
}