navree_kernel/report.rs
1//! [`PluginsReport`]: every plugin of an app and what its modules add, what
2//! the `plugins` command prints.
3
4use std::fmt::{self, Write};
5
6use crate::introspect::{string, strings};
7use crate::key::short_type_name;
8use crate::{ModuleId, PluginInfo, PublishTag};
9
10/// Every plugin of an app and what each of its modules adds: what the
11/// `plugins` command prints (its [`Display`](fmt::Display) text, or
12/// [`to_json`](PluginsReport::to_json) with `--json`). Read from the module
13/// graph; nothing is built to make it.
14///
15/// ```
16/// use navree_kernel::Navree;
17///
18/// let report = Navree::app().plugin_report()?;
19/// assert!(report.plugins.is_empty());
20/// assert_eq!(report.to_string(), "No plugins: no module of this app calls m.plugin(..).");
21/// # Ok::<(), navree_kernel::BootErrors>(())
22/// ```
23#[derive(Clone, Debug, Default)]
24#[non_exhaustive]
25pub struct PluginsReport {
26 /// Every plugin, by name.
27 pub plugins: Vec<PluginReport>,
28}
29
30/// One plugin of a [`PluginsReport`].
31///
32/// ```no_run
33/// use navree_kernel::{Module, ModuleBuilder, Navree};
34///
35/// struct AnnouncementsModule;
36///
37/// impl Module for AnnouncementsModule {
38/// fn register(&self, m: &mut ModuleBuilder) {
39/// m.plugin(navree_kernel::plugin_info!(title = "Announcements"));
40/// }
41/// }
42///
43/// let report = Navree::app().module(AnnouncementsModule).plugin_report()?;
44/// for plugin in &report.plugins {
45/// println!("{} {} ({} modules)", plugin.info.name, plugin.info.version, plugin.modules.len());
46/// }
47/// # Ok::<(), navree_kernel::BootErrors>(())
48/// ```
49#[derive(Clone, Debug)]
50#[non_exhaustive]
51pub struct PluginReport {
52 /// What the plugin says about itself (its first module's
53 /// [`PluginInfo`], in dependency order).
54 pub info: PluginInfo,
55 /// Whether the kernel finds the plugin first-party: one of the
56 /// framework's own packages, at the kernel's version, every module a type
57 /// of that package. The JSON's `"first_party"`.
58 pub first_party: bool,
59 /// Its modules, in dependency order: every module that acts for the
60 /// plugin. That is a module that names it, a module of its crate, and a
61 /// generic module that no module of the app imports directly, such as the
62 /// module `AccessModule::for_policy` makes for a policy only the plugin
63 /// imports.
64 pub modules: Vec<PluginModuleReport>,
65}
66
67/// One module of a [`PluginReport`].
68///
69/// ```no_run
70/// use navree_kernel::{Module, ModuleBuilder, Navree};
71///
72/// struct AnnouncementsModule;
73///
74/// impl Module for AnnouncementsModule {
75/// fn register(&self, m: &mut ModuleBuilder) {
76/// m.plugin(navree_kernel::plugin_info!(title = "Announcements"));
77/// }
78/// }
79///
80/// let report = Navree::app().module(AnnouncementsModule).plugin_report()?;
81/// let module = &report.plugins[0].modules[0];
82/// assert_eq!(module.id.name(), "AnnouncementsModule");
83/// assert!(module.commands.is_empty() && module.publishable.is_empty());
84/// # Ok::<(), navree_kernel::BootErrors>(())
85/// ```
86#[derive(Clone, Debug)]
87#[non_exhaustive]
88pub struct PluginModuleReport {
89 /// The module's id: [`ModuleId::name`] and [`ModuleId::type_name`] name it.
90 pub id: ModuleId,
91 /// The commands it registers, in registration order.
92 pub commands: Vec<&'static str>,
93 /// How many values of each type it contributes, by full type name, in
94 /// name order. `type` and the keys of `contributions` are
95 /// `std::any::type_name` output: for reading, not for matching; they may
96 /// change in any release.
97 pub contributions: Vec<(&'static str, usize)>,
98 /// How many files it can publish, per tag, in [`PublishTag::ALL`] order
99 /// (a tag without files is left out).
100 pub publishable: Vec<(PublishTag, usize)>,
101}
102
103impl PluginsReport {
104 /// The report as one JSON object, what `plugins --json` prints:
105 ///
106 /// ```json
107 /// {
108 /// "navree": "1.3.0",
109 /// "plugins": [
110 /// {"name": "navree-plugin-announcements", "namespace": "announcements",
111 /// "version": "1.0.0", "title": "Announcements", "description": null,
112 /// "homepage": null, "repository": null, "license": "MIT OR Apache-2.0",
113 /// "first_party": false,
114 /// "modules": [
115 /// {"name": "AnnouncementsModule",
116 /// "type": "navree_plugin_announcements::AnnouncementsModule",
117 /// "commands": ["announcements:prune"],
118 /// "contributions": {"navree_kernel::plugin::Publishable": 2},
119 /// "publishable": {"views": 3, "locales": 2}}
120 /// ]}
121 /// ]
122 /// }
123 /// ```
124 ///
125 /// Plugins come by name, their modules in dependency order. Keys may be
126 /// added in later releases, never removed. `type` and the keys of
127 /// `contributions` are `std::any::type_name` output: for reading, not for
128 /// matching; they may change in any release.
129 pub fn to_json(&self) -> String {
130 let mut out = String::from("{\"navree\":");
131 string(&mut out, env!("CARGO_PKG_VERSION"));
132 out.push_str(",\"plugins\":");
133 self.write_plugins_array(&mut out);
134 out.push('}');
135 out
136 }
137
138 /// Writes the JSON array of plugins alone (also `introspect`'s
139 /// `"plugins"`).
140 pub(crate) fn write_plugins_array(&self, out: &mut String) {
141 out.push('[');
142 for (i, plugin) in self.plugins.iter().enumerate() {
143 if i > 0 {
144 out.push(',');
145 }
146 let info = &plugin.info;
147 out.push_str("{\"name\":");
148 string(out, info.name);
149 out.push_str(",\"namespace\":");
150 string(out, info.namespace);
151 out.push_str(",\"version\":");
152 string(out, info.version);
153 for (key, value) in [
154 ("title", info.title),
155 ("description", info.description),
156 ("homepage", info.homepage),
157 ("repository", info.repository),
158 ("license", info.license),
159 ] {
160 let _ = write!(out, ",\"{key}\":");
161 match value {
162 Some(value) => string(out, value),
163 None => out.push_str("null"),
164 }
165 }
166 let _ = write!(out, ",\"first_party\":{},\"modules\":[", plugin.first_party);
167 for (j, module) in plugin.modules.iter().enumerate() {
168 if j > 0 {
169 out.push(',');
170 }
171 out.push_str("{\"name\":");
172 string(out, module.id.name());
173 out.push_str(",\"type\":");
174 string(out, module.id.type_name());
175 out.push_str(",\"commands\":");
176 strings(out, module.commands.iter().copied());
177 out.push_str(",\"contributions\":{");
178 for (k, (name, count)) in module.contributions.iter().enumerate() {
179 if k > 0 {
180 out.push(',');
181 }
182 string(out, name);
183 let _ = write!(out, ":{count}");
184 }
185 out.push_str("},\"publishable\":{");
186 for (k, (tag, count)) in module.publishable.iter().enumerate() {
187 if k > 0 {
188 out.push(',');
189 }
190 string(out, tag.as_str());
191 let _ = write!(out, ":{count}");
192 }
193 out.push_str("}}");
194 }
195 out.push_str("]}");
196 }
197 out.push(']');
198 }
199}
200
201/// What `plugins` prints: one block per plugin, blocks parted by an empty
202/// line. A block's first line is the namespace, the name and version, and the
203/// title when there is one; then, per module, its name and type, the commands
204/// it registers, what it adds (counts by short type name) and the files it
205/// publishes, each line left out when empty:
206///
207/// ```text
208/// announcements navree-plugin-announcements 1.0.0 Announcements
209/// AnnouncementsModule navree_plugin_announcements::AnnouncementsModule
210/// commands announcements:prune
211/// adds 1 ControllerRegistration, 1 MigrationSet, 2 Publishable
212/// publishes 3 views, 2 locales
213/// ```
214impl fmt::Display for PluginsReport {
215 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
216 if self.plugins.is_empty() {
217 return f.write_str("No plugins: no module of this app calls m.plugin(..).");
218 }
219 let mut lines: Vec<String> = Vec::new();
220 for (i, plugin) in self.plugins.iter().enumerate() {
221 if i > 0 {
222 lines.push(String::new());
223 }
224 let info = &plugin.info;
225 let mut head = format!("{} {} {}", info.namespace, info.name, info.version);
226 if let Some(title) = info.title {
227 head.push_str(" ");
228 head.push_str(title);
229 }
230 lines.push(head);
231 for module in &plugin.modules {
232 lines.push(format!(" {} {}", module.id.name(), module.id.type_name()));
233 if !module.commands.is_empty() {
234 lines.push(format!(" commands {}", module.commands.join(", ")));
235 }
236 if !module.contributions.is_empty() {
237 let mut adds: Vec<(&str, usize)> = module
238 .contributions
239 .iter()
240 .map(|&(name, count)| (short_type_name(name), count))
241 .collect();
242 adds.sort_by_key(|&(name, _)| name);
243 let adds: Vec<String> = adds
244 .iter()
245 .map(|(name, count)| format!("{count} {name}"))
246 .collect();
247 lines.push(format!(" adds {}", adds.join(", ")));
248 }
249 if !module.publishable.is_empty() {
250 let files: Vec<String> = module
251 .publishable
252 .iter()
253 .map(|(tag, count)| format!("{count} {}", tag.as_str()))
254 .collect();
255 lines.push(format!(" publishes {}", files.join(", ")));
256 }
257 }
258 }
259 f.write_str(&lines.join("\n"))
260 }
261}
262
263#[cfg(test)]
264mod tests {
265 use super::*;
266
267 struct AnnouncementsModule;
268 struct WeatherModule;
269
270 /// Two plugins built by hand: `navree-plugin-announcements` with the
271 /// documented values, and `navree-plugin-weather`, whose module adds
272 /// nothing.
273 fn announcements() -> PluginsReport {
274 let info = PluginInfo::new(
275 "navree-plugin-announcements",
276 "navree_plugin_announcements",
277 "announcements",
278 "1.0.0",
279 )
280 .title("Announcements")
281 .description("Notices for every member of a workspace, by Simran Kaur's team in Ludhiana.")
282 .repository("https://code.ludhiana.example/navree-plugin-announcements")
283 .license("MIT OR Apache-2.0");
284 let weather = PluginInfo::new(
285 "navree-plugin-weather",
286 "navree_plugin_weather",
287 "weather",
288 "0.4.0",
289 );
290 PluginsReport {
291 plugins: vec![
292 PluginReport {
293 info,
294 first_party: false,
295 modules: vec![PluginModuleReport {
296 id: ModuleId::of::<AnnouncementsModule>(),
297 commands: vec!["announcements:prune"],
298 contributions: vec![
299 ("navree_config::registry::SectionRegistration", 1),
300 ("navree_contracts::permissions::Permissions", 1),
301 ("navree_http::controller::ControllerRegistration", 1),
302 ("navree_kernel::plugin::Publishable", 2),
303 ("navree_schema::migration::MigrationSet", 1),
304 ],
305 publishable: vec![(PublishTag::Views, 3), (PublishTag::Locales, 2)],
306 }],
307 },
308 PluginReport {
309 info: weather,
310 first_party: false,
311 modules: vec![PluginModuleReport {
312 id: ModuleId::of::<WeatherModule>(),
313 commands: Vec::new(),
314 contributions: Vec::new(),
315 publishable: Vec::new(),
316 }],
317 },
318 ],
319 }
320 }
321
322 #[test]
323 fn the_plugins_json_has_the_documented_shape() {
324 let mut report = announcements();
325 report.plugins.truncate(1);
326 let json: serde_json::Value = serde_json::from_str(&report.to_json()).expect("JSON");
327 assert_eq!(
328 json,
329 serde_json::json!({
330 "navree": env!("CARGO_PKG_VERSION"),
331 "plugins": [{
332 "name": "navree-plugin-announcements",
333 "namespace": "announcements",
334 "version": "1.0.0",
335 "title": "Announcements",
336 "description": "Notices for every member of a workspace, by Simran Kaur's team in Ludhiana.",
337 "homepage": null,
338 "repository": "https://code.ludhiana.example/navree-plugin-announcements",
339 "license": "MIT OR Apache-2.0",
340 "first_party": false,
341 "modules": [{
342 "name": "AnnouncementsModule",
343 "type": std::any::type_name::<AnnouncementsModule>(),
344 "commands": ["announcements:prune"],
345 "contributions": {
346 "navree_config::registry::SectionRegistration": 1,
347 "navree_contracts::permissions::Permissions": 1,
348 "navree_http::controller::ControllerRegistration": 1,
349 "navree_kernel::plugin::Publishable": 2,
350 "navree_schema::migration::MigrationSet": 1
351 },
352 "publishable": {"views": 3, "locales": 2}
353 }]
354 }]
355 })
356 );
357 }
358
359 #[test]
360 fn the_plugins_text_lists_commands_contributions_and_files() {
361 let expected = format!(
362 "announcements navree-plugin-announcements 1.0.0 Announcements\n\
363 \x20 AnnouncementsModule {}\n\
364 \x20 commands announcements:prune\n\
365 \x20 adds 1 ControllerRegistration, 1 MigrationSet, 1 Permissions, 2 Publishable, 1 SectionRegistration\n\
366 \x20 publishes 3 views, 2 locales\n\
367 \n\
368 weather navree-plugin-weather 0.4.0\n\
369 \x20 WeatherModule {}",
370 std::any::type_name::<AnnouncementsModule>(),
371 std::any::type_name::<WeatherModule>(),
372 );
373 assert_eq!(announcements().to_string(), expected);
374 assert_eq!(
375 PluginsReport::default().to_string(),
376 "No plugins: no module of this app calls m.plugin(..)."
377 );
378 }
379}