Skip to main content

navree_kernel/
introspect.rs

1//! The `introspect --json` built-in: a [`GraphReport`] as JSON, for tools
2//! that look at an app from outside (Navigator, `navree mcp`).
3
4use std::fmt::Write;
5
6use crate::command::built_ins;
7use crate::{GraphReport, PluginsReport};
8
9impl GraphReport {
10    /// The report as one JSON object, what `introspect --json` prints:
11    ///
12    /// ```json
13    /// {
14    ///   "navree": "1.0.0",
15    ///   "modules": [
16    ///     {"name": "DealsModule", "type": "crm::DealsModule", "global": false, "root": false,
17    ///      "imports": ["DatabaseModule"], "exports": ["crm::DealService"],
18    ///      "providers": [{"type": "crm::DealService", "scope": "singleton",
19    ///                     "exported": true, "multi": false, "dependencies": ["navree_db::Db"]}],
20    ///      "commands": [{"name": "crm:close", "about": "Close stale deals"}]}
21    ///   ],
22    ///   "commands": [{"name": "check", "about": "...", "module": null}, ...]
23    /// }
24    /// ```
25    ///
26    /// Modules come in dependency order (imports first); the implicit app
27    /// root, which imports the app's root modules, is last with `"root":
28    /// true`. A module's `type` is its full type path
29    /// ([`ModuleId::type_name`](crate::ModuleId::type_name)): for reading, not
30    /// for matching. `commands` lists the built-ins (`module: null`), then
31    /// every module's commands; a built-in that yields to a module command of
32    /// its name (`plugins`, `plugin:publish`) is left out. Nothing is
33    /// constructed to produce it.
34    /// The `introspect` command adds a `"plugins"` array, as
35    /// [`PluginsReport::to_json`] writes it.
36    pub fn to_json(&self) -> String {
37        let mut out = String::from("{\"navree\":");
38        string(&mut out, env!("CARGO_PKG_VERSION"));
39        out.push_str(",\"modules\":[");
40        let root = self.modules.len().saturating_sub(1);
41        for (i, module) in self.modules.iter().enumerate() {
42            if i > 0 {
43                out.push(',');
44            }
45            out.push_str("{\"name\":");
46            string(&mut out, module.name);
47            out.push_str(",\"type\":");
48            string(&mut out, module.id.type_name());
49            let _ = write!(
50                out,
51                ",\"global\":{},\"root\":{},\"imports\":",
52                module.global,
53                i == root
54            );
55            strings(&mut out, module.imports.iter().copied());
56            out.push_str(",\"exports\":");
57            strings(&mut out, module.exports.iter().map(String::as_str));
58            out.push_str(",\"providers\":[");
59            for (j, provider) in module.providers.iter().enumerate() {
60                if j > 0 {
61                    out.push(',');
62                }
63                out.push_str("{\"type\":");
64                string(&mut out, &provider.key);
65                let _ = write!(
66                    out,
67                    ",\"scope\":\"{}\",\"exported\":{},\"multi\":{},\"dependencies\":",
68                    provider.scope,
69                    module.exports.contains(&provider.key),
70                    provider.multi
71                );
72                strings(&mut out, provider.dependencies.iter().map(String::as_str));
73                out.push('}');
74            }
75            out.push_str("],\"commands\":[");
76            for (j, command) in module.commands.iter().enumerate() {
77                if j > 0 {
78                    out.push(',');
79                }
80                command_object(&mut out, command.name, command.about, None);
81            }
82            out.push_str("]}");
83        }
84        out.push_str("],\"commands\":[");
85        let listed = built_ins(self).map(|(usage, about)| {
86            let name = usage.split_whitespace().next().unwrap_or(usage);
87            (name, about, None)
88        });
89        let registered = self.modules.iter().flat_map(|m| {
90            m.commands
91                .iter()
92                .map(move |c| (c.name, c.about, Some(m.name)))
93        });
94        for (i, (name, about, module)) in listed.chain(registered).enumerate() {
95            if i > 0 {
96                out.push(',');
97            }
98            command_object(&mut out, name, about, Some(module));
99        }
100        out.push_str("]}");
101        out
102    }
103}
104
105/// What the `introspect` built-in prints: [`GraphReport::to_json`] with
106/// `"plugins"` added to the outer object, the array of
107/// [`PluginsReport::to_json`].
108pub(crate) fn introspect_json(report: &GraphReport, plugins: &PluginsReport) -> String {
109    let mut out = report.to_json();
110    // `to_json` ends with the outer object's closing brace.
111    let closing = out.pop();
112    debug_assert_eq!(closing, Some('}'));
113    out.push_str(",\"plugins\":");
114    plugins.write_plugins_array(&mut out);
115    out.push('}');
116    out
117}
118
119/// `{"name":..,"about":..}`, plus `"module"` when `module` is given.
120fn command_object(out: &mut String, name: &str, about: &str, module: Option<Option<&str>>) {
121    out.push_str("{\"name\":");
122    string(out, name);
123    out.push_str(",\"about\":");
124    string(out, about);
125    if let Some(module) = module {
126        out.push_str(",\"module\":");
127        match module {
128            Some(module) => string(out, module),
129            None => out.push_str("null"),
130        }
131    }
132    out.push('}');
133}
134
135/// A JSON array of strings.
136pub(crate) fn strings<'a>(out: &mut String, items: impl Iterator<Item = &'a str>) {
137    out.push('[');
138    for (i, item) in items.enumerate() {
139        if i > 0 {
140            out.push(',');
141        }
142        string(out, item);
143    }
144    out.push(']');
145}
146
147/// A JSON string literal.
148pub(crate) fn string(out: &mut String, s: &str) {
149    out.push('"');
150    for c in s.chars() {
151        match c {
152            '"' => out.push_str("\\\""),
153            '\\' => out.push_str("\\\\"),
154            '\n' => out.push_str("\\n"),
155            '\r' => out.push_str("\\r"),
156            '\t' => out.push_str("\\t"),
157            c if u32::from(c) < 0x20 => {
158                let _ = write!(out, "\\u{:04x}", u32::from(c));
159            }
160            c => out.push(c),
161        }
162    }
163    out.push('"');
164}
165
166#[cfg(test)]
167mod tests {
168    use super::*;
169
170    #[test]
171    fn introspect_adds_the_type_and_the_plugins_and_keeps_every_key() {
172        struct Notices;
173        impl crate::Module for Notices {
174            fn register(&self, m: &mut crate::ModuleBuilder) {
175                m.plugin(crate::plugin_info!(namespace = "announcements"));
176            }
177        }
178        let roots: Vec<Box<dyn crate::Module>> = vec![Box::new(Notices)];
179        let graph = crate::graph::Graph::build(&roots, &[]).expect("valid");
180        let text = introspect_json(&graph.report(), &graph.plugins_report());
181        let json: serde_json::Value = serde_json::from_str(&text).expect("JSON");
182        let keys = |v: &serde_json::Value| {
183            let mut k: Vec<String> = v.as_object().unwrap().keys().cloned().collect();
184            k.sort();
185            k
186        };
187        assert_eq!(keys(&json), ["commands", "modules", "navree", "plugins"]);
188        for module in json["modules"].as_array().unwrap() {
189            assert_eq!(
190                keys(module),
191                [
192                    "commands",
193                    "exports",
194                    "global",
195                    "imports",
196                    "name",
197                    "providers",
198                    "root",
199                    "type",
200                ]
201            );
202        }
203        assert_eq!(json["modules"][0]["type"], std::any::type_name::<Notices>());
204        let alone: serde_json::Value =
205            serde_json::from_str(&graph.plugins_report().to_json()).unwrap();
206        assert_eq!(json["plugins"], alone["plugins"]);
207        let report_only: serde_json::Value =
208            serde_json::from_str(&graph.report().to_json()).unwrap();
209        assert!(
210            report_only.get("plugins").is_none(),
211            "GraphReport::to_json has no plugins"
212        );
213    }
214}