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::GraphReport;
7use crate::command::BUILT_INS;
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", "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`. `commands` lists the built-ins (`module: null`), then every
29    /// module's commands. Nothing is constructed to produce it.
30    pub fn to_json(&self) -> String {
31        let mut out = String::from("{\"navree\":");
32        string(&mut out, env!("CARGO_PKG_VERSION"));
33        out.push_str(",\"modules\":[");
34        let root = self.modules.len().saturating_sub(1);
35        for (i, module) in self.modules.iter().enumerate() {
36            if i > 0 {
37                out.push(',');
38            }
39            out.push_str("{\"name\":");
40            string(&mut out, module.name);
41            let _ = write!(
42                out,
43                ",\"global\":{},\"root\":{},\"imports\":",
44                module.global,
45                i == root
46            );
47            strings(&mut out, module.imports.iter().copied());
48            out.push_str(",\"exports\":");
49            strings(&mut out, module.exports.iter().map(String::as_str));
50            out.push_str(",\"providers\":[");
51            for (j, provider) in module.providers.iter().enumerate() {
52                if j > 0 {
53                    out.push(',');
54                }
55                out.push_str("{\"type\":");
56                string(&mut out, &provider.key);
57                let _ = write!(
58                    out,
59                    ",\"scope\":\"{}\",\"exported\":{},\"multi\":{},\"dependencies\":",
60                    provider.scope,
61                    module.exports.contains(&provider.key),
62                    provider.multi
63                );
64                strings(&mut out, provider.dependencies.iter().map(String::as_str));
65                out.push('}');
66            }
67            out.push_str("],\"commands\":[");
68            for (j, command) in module.commands.iter().enumerate() {
69                if j > 0 {
70                    out.push(',');
71                }
72                command_object(&mut out, command.name, command.about, None);
73            }
74            out.push_str("]}");
75        }
76        out.push_str("],\"commands\":[");
77        let built_ins = BUILT_INS.iter().map(|(usage, about)| {
78            let name = usage.split_whitespace().next().unwrap_or(usage);
79            (name, *about, None)
80        });
81        let registered = self.modules.iter().flat_map(|m| {
82            m.commands
83                .iter()
84                .map(move |c| (c.name, c.about, Some(m.name)))
85        });
86        for (i, (name, about, module)) in built_ins.chain(registered).enumerate() {
87            if i > 0 {
88                out.push(',');
89            }
90            command_object(&mut out, name, about, Some(module));
91        }
92        out.push_str("]}");
93        out
94    }
95}
96
97/// `{"name":..,"about":..}`, plus `"module"` when `module` is given.
98fn command_object(out: &mut String, name: &str, about: &str, module: Option<Option<&str>>) {
99    out.push_str("{\"name\":");
100    string(out, name);
101    out.push_str(",\"about\":");
102    string(out, about);
103    if let Some(module) = module {
104        out.push_str(",\"module\":");
105        match module {
106            Some(module) => string(out, module),
107            None => out.push_str("null"),
108        }
109    }
110    out.push('}');
111}
112
113/// A JSON array of strings.
114fn strings<'a>(out: &mut String, items: impl Iterator<Item = &'a str>) {
115    out.push('[');
116    for (i, item) in items.enumerate() {
117        if i > 0 {
118            out.push(',');
119        }
120        string(out, item);
121    }
122    out.push(']');
123}
124
125/// A JSON string literal.
126fn string(out: &mut String, s: &str) {
127    out.push('"');
128    for c in s.chars() {
129        match c {
130            '"' => out.push_str("\\\""),
131            '\\' => out.push_str("\\\\"),
132            '\n' => out.push_str("\\n"),
133            '\r' => out.push_str("\\r"),
134            '\t' => out.push_str("\\t"),
135            c if u32::from(c) < 0x20 => {
136                let _ = write!(out, "\\u{:04x}", u32::from(c));
137            }
138            c => out.push(c),
139        }
140    }
141    out.push('"');
142}