use shep_core::dogs::manifest::{MAX_EXAMPLES, Subcommand, Verb};
const EXAMPLES_HEADING: &str = "Examples:";
const EXAMPLE_PREFIX: &str = "$ ";
const EXAMPLE_INDENT: &str = " ";
pub fn render_examples(examples: impl IntoIterator<Item = impl AsRef<str>>) -> String {
let mut block = String::new();
for example in examples {
let line = example.as_ref().trim();
if line.is_empty() {
continue;
}
if block.is_empty() {
block.push_str(EXAMPLES_HEADING);
}
block.push('\n');
block.push_str(EXAMPLE_INDENT);
block.push_str(EXAMPLE_PREFIX);
block.push_str(line);
}
block
}
pub trait FromClap: Sized {
fn from_clap(command: &clap::Command) -> Result<Self, VerbClapError>;
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum VerbClapError {
TooManyExamples {
command: String,
examples: usize,
},
}
impl core::fmt::Display for VerbClapError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::TooManyExamples { command, examples } => write!(
f,
"`{command}` carries {examples} examples, and a manifest declares at most \
{MAX_EXAMPLES}"
),
}
}
}
impl core::error::Error for VerbClapError {}
impl FromClap for Verb {
fn from_clap(command: &clap::Command) -> Result<Self, VerbClapError> {
let examples = examples(command);
if examples.len() > MAX_EXAMPLES {
return Err(VerbClapError::TooManyExamples {
command: command.get_name().to_owned(),
examples: examples.len(),
});
}
let mut verb = Verb::new(about(command)).with_examples(examples);
verb.subcommands = command
.get_subcommands()
.filter(|sub| !sub.is_hide_set())
.map(|sub| match sub.get_overridden_usage() {
Some(usage) => Subcommand::new(sub.get_name(), about(sub))
.with_usage(usage.to_string().trim().to_owned()),
None => Subcommand::new(sub.get_name(), about(sub)),
})
.collect();
Ok(verb)
}
}
fn about(command: &clap::Command) -> String {
command
.get_about()
.map(ToString::to_string)
.unwrap_or_default()
}
fn examples(command: &clap::Command) -> Vec<String> {
let Some(after) = command.get_after_help() else {
return Vec::new();
};
let mut under_heading = false;
let mut lines = Vec::new();
for line in after.to_string().lines().map(str::trim) {
if !under_heading {
under_heading = line == EXAMPLES_HEADING;
continue;
}
let Some(example) = line.strip_prefix(EXAMPLE_PREFIX) else {
break;
};
lines.push(example.trim().to_owned());
}
lines
}
#[cfg(test)]
mod tests {
use clap::Command;
use super::*;
#[test]
fn a_clap_tree_becomes_a_verb() {
let command = Command::new("shep-kelpie")
.about("Run agents on a ticket board")
.subcommand(Command::new("board").about("Show the board"))
.subcommand(
Command::new("rule")
.about("Answer a ruling")
.override_usage("<id> yes|no <note>"),
)
.subcommand(Command::new("draft").about("Draft a card").hide(true))
.after_help(
"Examples:\n $ shep kelpie board\n $ shep kelpie rule 42 yes looks good\n\
Anything after `shep kelpie` goes to the dog.",
);
let verb = Verb::from_clap(&command).unwrap();
assert_eq!(verb.description, "Run agents on a ticket board");
assert_eq!(
verb.subcommands,
vec![
Subcommand::new("board", "Show the board"),
Subcommand::new("rule", "Answer a ruling").with_usage("<id> yes|no <note>"),
]
);
assert_eq!(
verb.examples,
["shep kelpie board", "shep kelpie rule 42 yes looks good"]
);
}
#[test]
fn four_examples_are_refused() {
let command = Command::new("shep-otel")
.about("Export metrics")
.after_help("Examples:\n $ a\n $ b\n $ c\n $ d");
let refused = Verb::from_clap(&command).expect_err("four examples is more than three");
assert_eq!(
refused,
VerbClapError::TooManyExamples {
command: "shep-otel".to_owned(),
examples: 4,
}
);
assert_eq!(
refused.to_string(),
"`shep-otel` carries 4 examples, and a manifest declares at most 3"
);
}
#[test]
fn a_tree_with_no_examples_declares_none() {
let verb = Verb::from_clap(&Command::new("shep-otel").about("Export metrics")).unwrap();
assert!(verb.examples.is_empty());
assert!(verb.subcommands.is_empty());
}
#[test]
fn render_examples_writes_the_block_from_clap_reads() {
let lines = ["shep kelpie board", "shep kelpie rule 42 yes looks good"];
let command = Command::new("shep-kelpie")
.about("Run agents on a ticket board")
.after_help(render_examples(lines));
assert_eq!(
command.get_after_help().unwrap().to_string(),
"Examples:\n $ shep kelpie board\n $ shep kelpie rule 42 yes looks good"
);
assert_eq!(Verb::from_clap(&command).unwrap().examples, lines);
}
#[test]
fn render_examples_writes_no_block_for_nothing_to_write() {
assert_eq!(render_examples([] as [&str; 0]), "");
assert_eq!(render_examples([" ", ""]), "");
assert_eq!(
render_examples(&["shep ping".to_owned()]),
"Examples:\n $ shep ping"
);
}
}