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 command a translated hook runs `mars` by: the program, then the words before
61 /// `mars`'s own arguments (`["meridian", "mars"]`, or the `mars` binary's absolute path
62 /// alone). Not a token: no authored text is substituted with it.
63 pub mars_command: &'a [String],
64 /// Where a translated hook's runner data is written, relative to the target root; the
65 /// hook's command names it. Set by [`HookDef::output`] from the target's row.
66 pub generated_file: &'a str,
67}
68
69impl Tokens<'_> {
70 /// `text` with every token replaced.
71 pub fn substitute(&self, text: &str) -> String {
72 text.replace(HOOK_DIR_TOKEN, self.hook_dir)
73 .replace(HOOK_TARGET_TOKEN, self.hook_target)
74 }
75
76 fn substitute_value(&self, value: &mut OrderedValue) {
77 match value {
78 OrderedValue::String(text) => *text = self.substitute(text),
79 OrderedValue::Array(values) => values.iter_mut().for_each(|v| self.substitute_value(v)),
80 OrderedValue::Object(values) => {
81 values.values_mut().for_each(|v| self.substitute_value(v))
82 }
83 _ => {}
84 }
85 }
86}
87
88/// One target's native hook table.
89#[derive(Debug, Clone, PartialEq, Eq)]
90pub struct NativeHook {
91 /// The native hook file in the hook's directory: the declared one, else `<target>.json`.
92 pub file: String,
93 unchecked: bool,
94}
95
96impl NativeHook {
97 /// `unchecked = true`: events the target does not list pass through verbatim.
98 pub fn is_unchecked(&self) -> bool {
99 self.unchecked
100 }
101}
102
103/// A `hook.toml`.
104#[derive(Debug, Clone)]
105pub struct HookDef {
106 pub name: String,
107 pub visibility: Visibility,
108 pub order: i32,
109 targets: BTreeMap<String, NativeHook>,
110 portable: Option<PortableHooks>,
111 skip_targets: BTreeSet<String>,
112}
113
114impl HookDef {
115 /// The native hook table this hook declares for `target_root`.
116 pub fn native_hook(&self, target_root: &str) -> Option<&NativeHook> {
117 self.targets.get(target_root)
118 }
119
120 /// Every declared native hook table, by target root.
121 pub fn native_hooks(&self) -> impl Iterator<Item = (&str, &NativeHook)> {
122 self.targets.iter().map(|(root, f)| (root.as_str(), f))
123 }
124
125 /// The `[hooks]` table, if the hook has one.
126 pub fn portable(&self) -> Option<&PortableHooks> {
127 self.portable.as_ref()
128 }
129
130 /// Whether `[hooks]` generates entries for `target_root`: it is not in `skip-targets`.
131 fn generates_for(&self, target_root: &str) -> bool {
132 self.portable.is_some() && !self.skip_targets.contains(target_root)
133 }
134
135 /// The managed target roots this hook is installed for: those where `[hooks]` renders at
136 /// least one event (unless in `skip-targets`) and those with a native hook table. A native hook
137 /// on a skipped target still installs; `skip-targets` only turns the generated entries
138 /// off.
139 pub fn select<'a>(&'a self, managed_targets: &'a [String]) -> Vec<&'a str> {
140 managed_targets
141 .iter()
142 .map(String::as_str)
143 .filter(|root| {
144 self.targets.contains_key(*root)
145 || (self.generates_for(root)
146 && targets::target(root).is_some_and(|target| {
147 self.portable
148 .as_ref()
149 .is_some_and(|p| p.renders_on(&target.profile))
150 }))
151 })
152 .collect()
153 }
154
155 /// What `[hooks]` leaves out on `target_root` when nothing there overrides it; empty
156 /// for a target in `skip-targets` and for a hook with no `[hooks]`.
157 pub fn skips_for(&self, target_root: &str) -> Vec<Skip> {
158 match (&self.portable, targets::target(target_root)) {
159 (Some(portable), Some(target)) if self.generates_for(target_root) => {
160 portable.render(&target.profile, &Tokens::default()).skips
161 }
162 _ => Vec::new(),
163 }
164 }
165}