Files
ScaenaPublic/crates/scaena-core/src/hooks.rs
T

236 lines
8.5 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// SPDX-License-Identifier: CPAL-1.0
// Copyright (c) 2026 Marek Novák. Exhibit A notice: LICENSE at the repository root.
//! Hook templates: `brand/hooks.md` lines `- [H<n>] <template>` with slots from a fixed set.
use std::collections::{BTreeMap, BTreeSet};
use serde::{Deserialize, Serialize};
use unicode_segmentation::UnicodeSegmentation;
use crate::text::{self, ItemLine, LineError};
/// The only slot names a template may use.
pub const SLOTS: [&str; 7] = [
"app", "feature", "pain", "number", "platform", "clicks", "audience",
];
/// Largest hooks file accepted, in bytes.
pub const MAX_FILE_BYTES: usize = 64 * 1024;
/// One hook template. `id` is `H<n>`; `slots` are unique, in order of first use.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct HookTemplate {
pub id: String,
pub text: String,
pub slots: Vec<String>,
pub genome: Genome,
}
/// How a hook opens.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Opening {
Question,
Statement,
Number,
Command,
}
/// A simple genome derived from a hook's text (Day 4 evolves it).
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Genome {
pub opening: Opening,
/// Words, a slot counts as one.
pub words: usize,
/// A digit or the `{number}` slot.
pub has_number: bool,
/// The first word, lowercased, when the hook opens with a command.
pub lead_verb: Option<String>,
}
/// Imperative openers recognised as commands.
const COMMAND_VERBS: &[&str] = &[
"ask", "build", "check", "discover", "ditch", "do", "don't", "dont", "download", "find",
"forget", "get", "give", "grab", "imagine", "install", "join", "keep", "learn", "let", "make",
"meet", "never", "open", "picture", "plan", "quit", "read", "save", "say", "see", "skip",
"start", "stop", "switch", "take", "track", "try", "turn", "use", "watch", "write",
];
impl Genome {
/// Derive the genome from a template or a filled hook.
///
/// Opening, in this order: starts with a digit or `{number}` → number; first sentence ends with `?` →
/// question; first word is a known imperative verb → command; otherwise statement.
pub fn of(text: &str) -> Genome {
let words: Vec<&str> = text.unicode_words().collect();
let has_number = text.chars().any(char::is_numeric) || text.contains("{number}");
let lead = text
.trim_start()
.trim_start_matches(|c: char| !c.is_alphanumeric() && c != '{');
let first_word = words.first().map(|w| w.to_lowercase().replace('’', "'"));
let opening = if lead.starts_with(|c: char| c.is_numeric()) || lead.starts_with("{number}")
{
Opening::Number
} else if first_sentence_is_question(text) {
Opening::Question
} else if first_word
.as_deref()
.is_some_and(|w| COMMAND_VERBS.contains(&w))
&& !lead.starts_with('{')
{
Opening::Command
} else {
Opening::Statement
};
let lead_verb = if opening == Opening::Command {
first_word
} else {
None
};
Genome {
opening,
words: words.len(),
has_number,
lead_verb,
}
}
}
fn first_sentence_is_question(text: &str) -> bool {
let chars: Vec<char> = text.chars().collect();
for (i, &c) in chars.iter().enumerate() {
if matches!(c, '.' | '!' | '?' | '…') && chars.get(i + 1).is_none_or(|n| n.is_whitespace())
{
return c == '?';
}
}
false
}
/// A hooks file error.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum HookError {
#[error("the file is {bytes} bytes; the limit is 65536")]
TooLarge { bytes: usize },
#[error(
"line {line}: forbidden character U+{codepoint:04X} (control, hidden or direction-changing)"
)]
ForbiddenCharacter { line: usize, codepoint: u32 },
#[error("line {line}: a carriage return that is not part of a CRLF line ending")]
LoneCarriageReturn { line: usize },
#[error("line {line}: a line starting '- [H' must be '- [H<n>] <template>'")]
Malformed { line: usize },
#[error("line {line}: hook number must be 1-9999 without leading zeros")]
IdOutOfRange { line: usize },
#[error("line {line}: hook {id} appears twice")]
Duplicate { line: usize, id: String },
#[error("line {line}: unknown slot '{{{slot}}}'")]
UnknownSlot { line: usize, slot: String },
#[error("line {line}: unbalanced '{{' or '}}'")]
UnbalancedBrace { line: usize },
#[error("line {line}: hook has no text")]
Empty { line: usize },
#[error("no value for slot '{{{slot}}}'")]
MissingValue { slot: String },
}
/// The slots of a template, unique, in order of first use.
fn slots_of(template: &str, line: usize) -> Result<Vec<String>, HookError> {
let mut slots: Vec<String> = Vec::new();
let mut rest = template;
while let Some(i) = rest.find(['{', '}']) {
if rest[i..].starts_with('}') {
return Err(HookError::UnbalancedBrace { line });
}
let after = &rest[i + 1..];
let Some(j) = after.find(['{', '}']) else {
return Err(HookError::UnbalancedBrace { line });
};
if after[j..].starts_with('{') {
return Err(HookError::UnbalancedBrace { line });
}
let name = &after[..j];
if !SLOTS.contains(&name) {
return Err(HookError::UnknownSlot {
line,
slot: name.to_string(),
});
}
if !slots.iter().any(|s| s == name) {
slots.push(name.to_string());
}
rest = &after[j + 1..];
}
Ok(slots)
}
/// Parse `brand/hooks.md`. Lines that do not start `- [H` are ignored (headings, prose).
///
/// Strict like the canon: a bullet line starting `[H` must be exactly `- [H<n>] <template>`; a leading BOM and CRLF
/// are tolerated; control, hidden and direction-changing characters are errors; 64 KiB at most.
pub fn parse(md: &str) -> Result<Vec<HookTemplate>, HookError> {
if md.len() > MAX_FILE_BYTES {
return Err(HookError::TooLarge { bytes: md.len() });
}
let lines = text::clean_lines(md).map_err(|(line, e)| match e {
LineError::LoneCr => HookError::LoneCarriageReturn { line },
LineError::Forbidden(codepoint) => HookError::ForbiddenCharacter { line, codepoint },
})?;
let mut out = Vec::new();
let mut seen = BTreeSet::new();
for (i, &l) in lines.iter().enumerate() {
let line = i + 1;
match text::item_line(l, 'H') {
ItemLine::No => {}
ItemLine::Malformed => return Err(HookError::Malformed { line }),
ItemLine::IdOutOfRange => return Err(HookError::IdOutOfRange { line }),
ItemLine::Item { id, text } => {
let text = text.trim();
if text.is_empty() {
return Err(HookError::Empty { line });
}
let id = format!("H{id}");
if !seen.insert(id.clone()) {
return Err(HookError::Duplicate { line, id });
}
let slots = slots_of(text, line)?;
out.push(HookTemplate {
id,
text: text.to_string(),
slots,
genome: Genome::of(text),
});
}
}
}
Ok(out)
}
impl HookTemplate {
/// Fill every slot. A missing value is an error; braces inside values are not expanded again.
/// Extra values are ignored.
pub fn fill(&self, values: &BTreeMap<String, String>) -> Result<String, HookError> {
let mut out = String::with_capacity(self.text.len() + 32);
let mut rest = self.text.as_str();
while let Some(i) = rest.find('{') {
out.push_str(&rest[..i]);
let after = &rest[i + 1..];
// Templates are validated at parse time; a hand-built one with a stray brace keeps it literally.
let Some(j) = after.find('}') else {
out.push_str(&rest[i..]);
return Ok(out);
};
let name = &after[..j];
let value = values.get(name).ok_or_else(|| HookError::MissingValue {
slot: name.to_string(),
})?;
out.push_str(value);
rest = &after[j + 1..];
}
out.push_str(rest);
Ok(out)
}
}