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
18type HandlerFn = fn(&[Token]) -> Verdict;
19
20static CMD_HANDLERS: LazyLock<HashMap<&'static str, HandlerFn>> =
21    LazyLock::new(crate::handlers::custom_cmd_handlers);
22
23static SUB_HANDLERS: LazyLock<HashMap<&'static str, HandlerFn>> =
24    LazyLock::new(crate::handlers::custom_sub_handlers);
25
26static TOML_REGISTRY: LazyLock<HashMap<String, CommandSpec>> = LazyLock::new(||
27    include!(concat!(env!("OUT_DIR"), "/toml_includes.rs"))
28);
29
30static CUSTOM_REGISTRY: LazyLock<HashMap<String, CommandSpec>> = LazyLock::new(|| {
31    let mut map = HashMap::new();
32    custom::apply_custom(&mut map);
33    map
34});
35
36pub fn toml_dispatch(tokens: &[Token]) -> Option<Verdict> {
37    let cmd = tokens[0].command_name();
38    TOML_REGISTRY.get(cmd).map(|spec| dispatch_spec(tokens, spec))
39}
40
41/// Looks up the command in the runtime custom registry (project-local
42/// `.safe-chains.toml`, then user-level `~/.config/safe-chains.toml`).
43/// A match here wins over the built-in hardcoded handlers, which is how
44/// an override of `gh` takes effect.
45pub fn custom_dispatch(tokens: &[Token]) -> Option<Verdict> {
46    let cmd = tokens[0].command_name();
47    CUSTOM_REGISTRY.get(cmd).map(|spec| dispatch_spec(tokens, spec))
48}
49
50pub fn toml_command_names() -> Vec<&'static str> {
51    TOML_REGISTRY
52        .keys()
53        .map(|k| k.as_str())
54        .collect()
55}
56
57pub fn toml_command_docs() -> Vec<crate::docs::CommandDoc> {
58    TOML_REGISTRY
59        .iter()
60        .filter(|(key, spec)| *key == &spec.name)
61        .map(|(_, spec)| spec.to_command_doc())
62        .collect()
63}
64
65#[cfg(test)]
66mod tests;