Skip to main content

safe_chains/registry/
mod.rs

1mod build;
2mod custom;
3mod dispatch;
4mod docs;
5mod policy;
6pub(crate) mod types;
7
8use std::collections::HashMap;
9use std::sync::LazyLock;
10
11use crate::parse::Token;
12use crate::verdict::Verdict;
13
14pub use build::{build_registry, load_toml};
15pub use dispatch::dispatch_spec;
16pub use types::{CommandSpec, OwnedPolicy};
17
18use types::DispatchKind;
19
20type HandlerFn = fn(&[Token]) -> Verdict;
21
22static CMD_HANDLERS: LazyLock<HashMap<&'static str, HandlerFn>> =
23    LazyLock::new(crate::handlers::custom_cmd_handlers);
24
25static SUB_HANDLERS: LazyLock<HashMap<&'static str, HandlerFn>> =
26    LazyLock::new(crate::handlers::custom_sub_handlers);
27
28static TOML_REGISTRY: LazyLock<HashMap<String, CommandSpec>> = LazyLock::new(||
29    include!(concat!(env!("OUT_DIR"), "/toml_includes.rs"))
30);
31
32static CUSTOM_REGISTRY: LazyLock<HashMap<String, CommandSpec>> = LazyLock::new(|| {
33    let mut map = HashMap::new();
34    custom::apply_custom(&mut map);
35    map
36});
37
38pub fn toml_dispatch(tokens: &[Token]) -> Option<Verdict> {
39    let cmd = tokens[0].command_name();
40    TOML_REGISTRY.get(cmd).map(|spec| dispatch_spec(tokens, spec))
41}
42
43/// Looks up the command in the runtime custom registry (project-local
44/// `.safe-chains.toml`, then user-level `~/.config/safe-chains.toml`).
45/// A match here wins over the built-in hardcoded handlers, which is how
46/// an override of `gh` takes effect.
47pub fn custom_dispatch(tokens: &[Token]) -> Option<Verdict> {
48    let cmd = tokens[0].command_name();
49    CUSTOM_REGISTRY.get(cmd).map(|spec| dispatch_spec(tokens, spec))
50}
51
52pub fn toml_command_names() -> Vec<&'static str> {
53    TOML_REGISTRY
54        .keys()
55        .map(|k| k.as_str())
56        .collect()
57}
58
59/// Look up `cmd_name`'s TOML-declared subs (set via `[[command.sub]]`
60/// blocks alongside `handler = "..."`) and dispatch the one whose name
61/// matches `tokens[1]`. Returns `None` if no sub matched, so the
62/// handler can fall through to its fallback grammar (or deny).
63pub fn try_sub_dispatch(cmd_name: &str, tokens: &[Token]) -> Option<Verdict> {
64    let spec = handler_spec(cmd_name)?;
65    let DispatchKind::Custom { subs, .. } = &spec.kind else {
66        return None;
67    };
68    let arg = tokens.get(1)?.as_str();
69    let sub = subs.iter().find(|s| s.name == arg)?;
70    Some(dispatch::dispatch_sub_kind(&tokens[1..], &sub.kind))
71}
72
73/// Apply `cmd_name`'s TOML-declared `[command.fallback]` grammar.
74/// Returns `None` if no fallback is declared.
75pub fn try_fallback_grammar(cmd_name: &str, tokens: &[Token]) -> Option<Verdict> {
76    let spec = handler_spec(cmd_name)?;
77    let DispatchKind::Custom { fallback, .. } = &spec.kind else {
78        return None;
79    };
80    let f = fallback.as_ref()?;
81    Some(dispatch::dispatch_fallback(tokens, f))
82}
83
84/// Dispatch `tokens` against `cmd_name`'s `[[command.matrix]]`
85/// blocks. Looks at `tokens[1]` (parent) and `tokens[2]` (action),
86/// finds the first matrix whose `parents` contains the parent and
87/// whose `actions` map contains the action, then validates
88/// `tokens[2..]` against the named policy (and a guard flag if the
89/// matrix entry declared one). Returns `None` if no matrix matched —
90/// the handler can then fall through to its remaining special cases
91/// or deny.
92pub fn try_matrix_dispatch(cmd_name: &str, tokens: &[Token]) -> Option<Verdict> {
93    let spec = handler_spec(cmd_name)?;
94    let DispatchKind::Custom { matrices, handler_policies, .. } = &spec.kind else {
95        return None;
96    };
97    let parent = tokens.get(1)?.as_str();
98    let action = tokens.get(2)?.as_str();
99    for matrix in matrices {
100        if !matrix.parents.iter().any(|p| p == parent) {
101            continue;
102        }
103        let Some(action_spec) = matrix.actions.get(action) else { continue; };
104        if let Some(long) = action_spec.guard.as_deref()
105            && !crate::parse::has_flag(&tokens[2..], action_spec.guard_short.as_deref(), Some(long))
106        {
107            return Some(Verdict::Denied);
108        }
109        let Some(policy) = handler_policies.get(&action_spec.policy_key) else {
110            return Some(Verdict::Denied);
111        };
112        return Some(dispatch::dispatch_matrix_action(&tokens[2..], policy, matrix.level));
113    }
114    None
115}
116
117/// Validate `tokens` against `cmd_name`'s named flag policy declared
118/// in a `[command.handler_policy.KEY]` block. Returns `false` if no
119/// such policy is declared or the tokens fail it. Used by handlers
120/// whose dispatch logic genuinely can't move to TOML (e.g. gh's
121/// sub × action matrix) but whose per-policy WordSets should live
122/// in TOML rather than as Rust `WordSet` constants.
123pub fn check_handler_policy(cmd_name: &str, key: &str, tokens: &[Token]) -> bool {
124    let Some(spec) = handler_spec(cmd_name) else { return false; };
125    let DispatchKind::Custom { handler_policies, .. } = &spec.kind else {
126        return false;
127    };
128    let Some(policy) = handler_policies.get(key) else { return false; };
129    dispatch::check_handler_policy_owned(tokens, policy)
130}
131
132fn handler_spec(cmd_name: &str) -> Option<&'static CommandSpec> {
133    CUSTOM_REGISTRY
134        .get(cmd_name)
135        .or_else(|| TOML_REGISTRY.get(cmd_name))
136}
137
138pub fn toml_command_docs() -> Vec<crate::docs::CommandDoc> {
139    TOML_REGISTRY
140        .iter()
141        .filter(|(key, spec)| *key == &spec.name)
142        .map(|(_, spec)| spec.to_command_doc())
143        .collect()
144}
145
146#[cfg(test)]
147mod tests;