mars_schema/hooks/mod.rs
1//! The `hook.toml` definition and every per-target hook rule.
2//!
3//! A hook is written once as Claude's hooks JSON in TOML (`[hooks]`, see `portable`), a
4//! native hook per target (`[targets]`), or both. This module owns what is authored
5//! (`HookDef`) and which targets receive it (`HookDef::select`); `read` turns text into a
6//! `HookDef`, `output` says what it installs on one target, `targets` is the per-target
7//! table and `render` turns a `[hooks]` table into a profile's entries.
8//! Nothing here touches the filesystem: the caller reads the bytes and places the result,
9//! and adds the location (a path, or a package and version) to the path-free diagnostics.
10
11pub mod agy;
12mod output;
13pub mod portable;
14mod read;
15pub mod render;
16pub mod targets;
17#[cfg(test)]
18mod tests;
19mod typescript;
20
21use std::collections::{BTreeMap, BTreeSet};
22
23use crate::ordered::OrderedValue;
24use crate::visibility::Visibility;
25use portable::PortableHooks;
26use render::Skip;
27
28pub use output::{FileOutput, HookOutput, MergeOutput, NativeHookError, OutputFile};
29pub use read::{HookRead, REMOVED_SCHEMA_CODE, REMOVED_SCHEMA_MESSAGE, read, uses_removed_schema};
30
31/// The authored placeholder for the directory a hook's files are installed in.
32pub const HOOK_DIR_TOKEN: &str = "${MARS_HOOK_DIR}";
33
34/// Hook names ending in this are reserved for files Mars generates beside authored ones.
35pub(crate) const RESERVED_NAME_SUFFIX: &str = ".hooks";
36
37/// Where a `hook.toml` came from. The project's own is strict. A dependency's is lenient
38/// where one author's slip should not stop a sync: an unknown top-level key is ignored and
39/// a merge native hook's unknown event is skipped, each with a warning.
40#[derive(Debug, Clone, Copy, PartialEq, Eq)]
41pub enum Origin {
42 Local,
43 Dependency,
44}
45
46/// The authored placeholder for the target a hook is installed for.
47pub const HOOK_TARGET_TOKEN: &str = "${MARS_HOOK_TARGET}";
48
49/// The values a hook's text is substituted with.
50#[derive(Debug, Clone, Copy, Default)]
51pub struct Tokens<'a> {
52 /// Replaces [`HOOK_DIR_TOKEN`]: where the hook's directory is installed.
53 pub hook_dir: &'a str,
54 /// Replaces [`HOOK_TARGET_TOKEN`]: the target root (`.claude`, `.codex`, …), or `plugin`
55 /// in a plugin build's shared tree.
56 pub hook_target: &'a str,
57 /// The hook's name, which a generated file carries as its identity. Not a token: no
58 /// authored text is substituted with it.
59 pub hook_name: &'a str,
60 /// The `mars` binary a translated hook's command runs, by absolute path. Not a token:
61 /// no authored text is substituted with it.
62 pub mars_exe: &'a str,
63 /// Where a translated hook's runner data is written, relative to the target root; the
64 /// hook's command names it. Set by [`HookDef::output`] from the target's row.
65 pub generated_file: &'a str,
66}
67
68impl Tokens<'_> {
69 /// `text` with every token replaced.
70 pub fn substitute(&self, text: &str) -> String {
71 text.replace(HOOK_DIR_TOKEN, self.hook_dir)
72 .replace(HOOK_TARGET_TOKEN, self.hook_target)
73 }
74
75 fn substitute_value(&self, value: &mut OrderedValue) {
76 match value {
77 OrderedValue::String(text) => *text = self.substitute(text),
78 OrderedValue::Array(values) => values.iter_mut().for_each(|v| self.substitute_value(v)),
79 OrderedValue::Object(values) => {
80 values.values_mut().for_each(|v| self.substitute_value(v))
81 }
82 _ => {}
83 }
84 }
85}
86
87/// One target's native hook table.
88#[derive(Debug, Clone, PartialEq, Eq)]
89pub struct NativeHook {
90 /// The native hook file in the hook's directory: the declared one, else `<target>.json`.
91 pub file: String,
92 unchecked: bool,
93}
94
95impl NativeHook {
96 /// `unchecked = true`: events the target does not list pass through verbatim.
97 pub fn is_unchecked(&self) -> bool {
98 self.unchecked
99 }
100}
101
102/// A `hook.toml`.
103#[derive(Debug, Clone)]
104pub struct HookDef {
105 pub name: String,
106 pub visibility: Visibility,
107 pub order: i32,
108 targets: BTreeMap<String, NativeHook>,
109 portable: Option<PortableHooks>,
110 skip_targets: BTreeSet<String>,
111}
112
113impl HookDef {
114 /// The native hook table this hook declares for `target_root`.
115 pub fn native_hook(&self, target_root: &str) -> Option<&NativeHook> {
116 self.targets.get(target_root)
117 }
118
119 /// Every declared native hook table, by target root.
120 pub fn native_hooks(&self) -> impl Iterator<Item = (&str, &NativeHook)> {
121 self.targets.iter().map(|(root, f)| (root.as_str(), f))
122 }
123
124 /// The `[hooks]` table, if the hook has one.
125 pub fn portable(&self) -> Option<&PortableHooks> {
126 self.portable.as_ref()
127 }
128
129 /// Whether `[hooks]` generates entries for `target_root`: it is not in `skip-targets`.
130 fn generates_for(&self, target_root: &str) -> bool {
131 self.portable.is_some() && !self.skip_targets.contains(target_root)
132 }
133
134 /// The managed target roots this hook is installed for: those where `[hooks]` renders at
135 /// least one event (unless in `skip-targets`) and those with a native hook table. A native hook
136 /// on a skipped target still installs; `skip-targets` only turns the generated entries
137 /// off.
138 pub fn select<'a>(&'a self, managed_targets: &'a [String]) -> Vec<&'a str> {
139 managed_targets
140 .iter()
141 .map(String::as_str)
142 .filter(|root| {
143 self.targets.contains_key(*root)
144 || (self.generates_for(root)
145 && targets::target(root).is_some_and(|target| {
146 self.portable
147 .as_ref()
148 .is_some_and(|p| p.renders_on(&target.profile))
149 }))
150 })
151 .collect()
152 }
153
154 /// What `[hooks]` leaves out on `target_root` when nothing there overrides it; empty
155 /// for a target in `skip-targets` and for a hook with no `[hooks]`.
156 pub fn skips_for(&self, target_root: &str) -> Vec<Skip> {
157 match (&self.portable, targets::target(target_root)) {
158 (Some(portable), Some(target)) if self.generates_for(target_root) => {
159 portable.render(&target.profile, &Tokens::default()).skips
160 }
161 _ => Vec::new(),
162 }
163 }
164}