Something went wrong. Try again.
personal ssg
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177//! External-process hooks.//!//! A hook is a configured command run as a child process. There is no plugin//! API, no dynamic loading and no shell: the configured value is split on//! whitespace into argv.//!//! The implemented phase is `context`: once per page, with the page's source//! path and route appended as the last two arguments. The command writes//! `key<TAB>value` lines to stdout; those values are merged into the page's//! template context.
use std::path::{Path, PathBuf};use std::process::{Command, Stdio};
/// Run the `pre_build` hook before scanning.////// The hook receives the project root and content directory as the last two/// arguments. Its stdout may contain one path to a content directory to use/// instead; an empty stdout keeps the configured content directory.pub fn pre_build(argv: &[String], root: &Path, content: &Path) -> Result<Option<PathBuf>, String> { let Some(program) = argv.first() else { return Ok(None); };
let output = Command::new(program) .args(&argv[1..]) .arg(root) .arg(content) .stdin(Stdio::null()) .stdout(Stdio::piped()) .stderr(Stdio::inherit()) .output() .map_err(|error| format!("pre_build hook {program}: {error}"))?;
if !output.status.success() { return Err(format!( "pre_build hook {program}: exited with {}", output.status )); }
let text = String::from_utf8(output.stdout) .map_err(|error| format!("pre_build hook {program}: {error}"))?; let mut lines = text.lines().filter(|line| !line.trim().is_empty()); let Some(line) = lines.next() else { return Ok(None); }; if lines.next().is_some() { return Err(format!( "pre_build hook {program}: stdout must be one path or empty" )); } let path = PathBuf::from(line.trim()); if path.is_absolute() { Ok(Some(path)) } else { Ok(Some(root.join(path))) }}
/// Run the `context` hook for one page and parse its `key<TAB>value` lines.pub fn context( argv: &[String], source: &Path, route: &str,) -> Result<Vec<(String, String)>, String> { let Some(program) = argv.first() else { return Ok(Vec::new()); };
let output = Command::new(program) .args(&argv[1..]) .arg(source) .arg(route) .stdin(Stdio::null()) .stdout(Stdio::piped()) .stderr(Stdio::inherit()) .output() .map_err(|error| format!("context hook {program}: {error}"))?;
if !output.status.success() { return Err(format!( "context hook {program}: exited with {}", output.status )); }
let text = String::from_utf8(output.stdout) .map_err(|error| format!("context hook {program}: {error}"))?; parse(&text, program)}
fn parse(text: &str, name: &str) -> Result<Vec<(String, String)>, String> { let mut pairs = Vec::new(); for (index, raw) in text.lines().enumerate() { let line = raw.strip_suffix('\r').unwrap_or(raw); let trimmed = line.trim(); if trimmed.is_empty() || trimmed.starts_with('#') { continue; } let Some((key, value)) = line.split_once('\t') else { return Err(format!("{name}:{}: expected key<TAB>value", index + 1)); }; let key = key.trim(); if key.is_empty() { return Err(format!("{name}:{}: empty key", index + 1)); } pairs.push((key.to_string(), value.to_string())); } Ok(pairs)}
#[cfg(test)]mod tests { use super::*;
#[test] fn parses_key_value_lines() { let pairs = parse("# comment\nwords\t42\n\nsection\tnotes\n", "hook").unwrap(); assert_eq!( pairs, vec![ ("words".to_string(), "42".to_string()), ("section".to_string(), "notes".to_string()) ] ); }
#[test] fn rejects_lines_without_a_tab() { let error = parse("words 42\n", "hook").unwrap_err(); assert!(error.contains("expected key<TAB>value")); }
#[test] fn rejects_an_empty_key() { let error = parse("\t42\n", "hook").unwrap_err(); assert!(error.contains("empty key")); }
#[test] fn runs_a_command_and_parses_output() { let argv = vec![ "sh".to_string(), "-c".to_string(), "printf 'words\\t42\\n'".to_string(), ]; let pairs = context(&argv, Path::new("/tmp/page.md"), "/page/").unwrap(); assert_eq!(pairs, vec![("words".to_string(), "42".to_string())]); }
#[test] fn passes_source_and_route_as_arguments() { let argv = vec![ "sh".to_string(), "-c".to_string(), "printf 'args\\t%s|%s\\n' \"$0\" \"$1\"".to_string(), ]; let pairs = context(&argv, Path::new("/tmp/page.md"), "/page/").unwrap(); assert_eq!(pairs[0].1, "/tmp/page.md|/page/"); }
#[test] fn non_zero_exit_is_an_error() { let argv = vec!["sh".to_string(), "-c".to_string(), "exit 3".to_string()]; let error = context(&argv, Path::new("x"), "/").unwrap_err(); assert!(error.contains("exited with")); }
#[test] fn missing_program_is_an_error() { let argv = vec!["/nonexistent/uteri-hook".to_string()]; let error = context(&argv, Path::new("x"), "/").unwrap_err(); assert!(error.contains("context hook")); }}