use std::fmt;
use std::future::Future;
use std::sync::Arc;
use crate::{AppContext, BoxError, BoxFuture, GraphReport};
pub type CommandFn =
Arc<dyn Fn(AppContext, Vec<String>) -> BoxFuture<'static, Result<(), BoxError>> + Send + Sync>;
#[derive(Clone)]
pub struct CommandSpec {
pub name: &'static str,
pub about: &'static str,
pub run: CommandFn,
pub stdio: bool,
pub offline: bool,
}
impl CommandSpec {
pub fn new<F, Fut>(name: &'static str, about: &'static str, f: F) -> Self
where
F: Fn(AppContext, Vec<String>) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<(), BoxError>> + Send + 'static,
{
Self {
name,
about,
run: Arc::new(move |ctx, args| Box::pin(f(ctx, args))),
stdio: false,
offline: false,
}
}
pub fn stdio(mut self) -> Self {
self.stdio = true;
self
}
pub fn offline(mut self) -> Self {
self.offline = true;
self
}
}
impl fmt::Debug for CommandSpec {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("CommandSpec")
.field("name", &self.name)
.field("about", &self.about)
.field("stdio", &self.stdio)
.field("offline", &self.offline)
.finish_non_exhaustive()
}
}
pub(crate) const BUILT_INS: [(&str, &str); 5] = [
(
"check [--graph]",
"Validate the module graph without constructing providers",
),
("help", "List the available commands"),
(
"introspect --json",
"Print the module graph and commands as JSON without constructing providers",
),
(
"plugins [--json]",
"List the plugins and what each adds, without constructing providers",
),
(
"plugin:publish <plugin> [options]",
"Copy a plugin's templates, translations, config or files into the app",
),
];
pub(crate) const YIELDING: [&str; 2] = ["plugins", "plugin:publish"];
pub(crate) const FRAMEWORK_COMMANDS: [&str; 8] = [
"--help",
"-h",
"check",
"help",
"introspect",
"list",
"plugin:publish",
"plugins",
];
pub(crate) fn built_ins(
report: &GraphReport,
) -> impl Iterator<Item = (&'static str, &'static str)> + '_ {
BUILT_INS.into_iter().filter(move |&(usage, _)| {
let name = usage.split_whitespace().next().unwrap_or(usage);
!(YIELDING.contains(&name) && report.has_command(name))
})
}
pub(crate) fn help_text(report: &GraphReport) -> String {
let listed: Vec<(&str, &str)> = built_ins(report).collect();
let commands: Vec<(&str, &str)> = report
.modules
.iter()
.flat_map(|m| m.commands.iter().map(|c| (c.name, c.about)))
.collect();
let width = listed
.iter()
.chain(commands.iter())
.map(|(name, _)| name.len())
.max()
.unwrap_or(0);
let mut out = String::from("Usage: <command> [args...]\n\nBuilt-in commands:\n");
for (name, about) in listed {
out.push_str(&format!(" {name:width$} {about}\n"));
}
if !commands.is_empty() {
out.push_str("\nCommands:\n");
for (name, about) in commands {
out.push_str(&format!(" {name:width$} {about}\n"));
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{CommandInfo, ModuleReport};
#[test]
fn help_leaves_out_a_built_in_that_yields() {
struct Mine;
let own = GraphReport {
modules: vec![ModuleReport {
id: crate::ModuleId::of::<Mine>(),
name: "Mine",
global: false,
imports: Vec::new(),
providers: Vec::new(),
exports: Vec::new(),
commands: vec![CommandInfo {
name: "plugins",
about: "The app's own list",
}],
}],
};
let text = help_text(&own);
assert!(!text.contains("plugins [--json]"), "{text}");
assert!(
text.lines().any(
|l| l.trim_start().starts_with("plugins ") && l.ends_with("The app's own list")
),
"{text}"
);
assert!(
help_text(&GraphReport {
modules: Vec::new()
})
.contains("plugins [--json]")
);
}
}