use crate::types::format::TomlFields;
use crate::types::hooks::lua::LuaHook;
use crate::types::hooks::message::MessageHook;
use crate::types::manifest::ManifestError;
use crate::types::name::BinaryName;
use crate::types::tokens::LocatedToken;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum HookAction {
Message(MessageHook),
Lua(LuaHook),
}
impl HookAction {
pub const KEYS: [&'static str; 5] = ["text", "run", "args", "grants", "may_block"];
pub(in crate::types) fn read(
fields: &mut TomlFields,
binaries: &[BinaryName],
tokens: &mut Vec<LocatedToken>,
) -> Option<Self> {
let kind = fields.required_string("kind")?;
match kind.as_str() {
"message" => MessageHook::read(fields, tokens).map(Self::Message),
"lua" => LuaHook::read(fields, binaries, tokens).map(Self::Lua),
_ => {
fields.refuse("kind", ManifestError::KindUnknown { text: kind });
None
}
}
}
}
#[cfg(test)]
mod tests {
use std::path::Path;
use super::*;
use crate::types::format::parse_toml_document;
type TestResult = Result<(), Box<dyn std::error::Error>>;
fn read(text: &str) -> Result<(Option<HookAction>, Vec<String>), Box<dyn std::error::Error>> {
let file = Path::new("packs/core/pack.toml");
let table = parse_toml_document(file, text).map_err(|d| d.to_string())?;
let mut fields = TomlFields::new(file, "hooks[0]", table);
let action = HookAction::read(&mut fields, &[], &mut Vec::new());
let shown = fields
.into_diagnostics()
.into_sorted()
.iter()
.map(ToString::to_string)
.collect();
Ok((action, shown))
}
#[test]
fn hook_action_dispatches_on_kind() -> TestResult {
let (message, shown) = read("kind = \"message\"\ntext = \"hi\"")?;
assert!(shown.is_empty(), "{shown:?}");
assert!(matches!(message, Some(HookAction::Message(_))));
let (lua, shown) = read("kind = \"lua\"\nrun = \"hooks/x.lua\"")?;
assert!(shown.is_empty(), "{shown:?}");
assert!(matches!(lua, Some(HookAction::Lua(_))));
Ok(())
}
#[test]
fn hook_action_refuses_a_missing_or_unknown_kind() -> TestResult {
let (action, shown) = read("kind = \"sh\"\nrun = \"x.sh\"\ntext = \"x\"")?;
assert!(action.is_none());
assert_eq!(
shown,
["packs/core/pack.toml: hooks[0].kind: \"sh\" (expected message, lua)"]
);
let (action, shown) = read("run = \"x.sh\"\ntext = \"x\"")?;
assert!(action.is_none());
assert_eq!(shown, ["packs/core/pack.toml: hooks[0].kind: required"]);
Ok(())
}
#[test]
fn hook_action_keys_name_every_kind_specific_key() {
assert_eq!(
HookAction::KEYS,
["text", "run", "args", "grants", "may_block"]
);
}
}