Skip to main content

CommandBuilder

Struct CommandBuilder 

Source
pub struct CommandBuilder { /* private fields */ }
Expand description

Consuming builder for Command.

Obtain an instance via Command::builder. All setter methods consume and return self to allow method chaining. Call CommandBuilder::build to produce a Command.

§Examples

let cmd = Command::builder("run")
    .alias("r")
    .summary("Run the pipeline")
    .flag(Flag::builder("verbose").short('v').build().unwrap())
    .build()
    .unwrap();

assert_eq!(cmd.canonical, "run");
assert_eq!(cmd.aliases, vec!["r"]);

Implementations§

Source§

impl CommandBuilder

Source

pub fn aliases( self, aliases: impl IntoIterator<Item = impl Into<String>>, ) -> Self

Replace the entire alias list with the given collection.

To add a single alias use CommandBuilder::alias.

Source

pub fn alias(self, alias: impl Into<String>) -> Self

Append a single alias.

Source

pub fn spellings( self, spellings: impl IntoIterator<Item = impl Into<String>>, ) -> Self

Replace the entire spelling list with the given collection.

Spellings are silent typo-corrections or abbreviated forms that the resolver accepts but does not advertise in help text. They differ from aliases in that they will never appear in the --help aliases line, and they are excluded from prefix-match ambiguity candidates.

To add a single spelling use CommandBuilder::spelling.

Source

pub fn spelling(self, s: impl Into<String>) -> Self

Register a common misspelling or abbreviated form that resolves to this command.

Unlike CommandBuilder::alias, spellings are not shown in help text. They serve as silent typo-correction or shorthand that resolves to the canonical command name without advertising the alternative.

§Difference from alias
Featurealiasspelling
Shown in --helpYesNo
Resolver exact matchYesYes
Resolver prefix matchYesNo
Appears in aliases fieldYesNo (goes in spellings)
§Examples
let cmd = Command::builder("deploy")
    .alias("release")           // shown in help: "deploy (release)"
    .alias("ship")              // shown in help
    .spelling("deply")          // silent typo correction
    .spelling("delpoy")         // silent typo correction
    .build().unwrap();

assert!(cmd.aliases.contains(&"release".to_string()));
assert!(cmd.spellings.contains(&"deply".to_string()));
Source

pub fn summary(self, s: impl Into<String>) -> Self

Set the one-line summary shown in command listings.

Source

pub fn description(self, d: impl Into<String>) -> Self

Set the full prose description shown in detailed help output.

Source

pub fn argument(self, arg: Argument) -> Self

Append a positional Argument definition.

Arguments are bound in declaration order when the command is parsed.

Source

pub fn flag(self, flag: Flag) -> Self

Append a Flag definition.

Source

pub fn example(self, example: Example) -> Self

Append a usage Example.

Source

pub fn subcommand(self, cmd: Command) -> Self

Append a subcommand.

Subcommands are resolved before positional arguments during parsing, so a token that matches a subcommand name is consumed as the subcommand selector, not as a positional value.

Source

pub fn best_practice(self, bp: impl Into<String>) -> Self

Append a best-practice tip surfaced to AI agents.

Source

pub fn anti_pattern(self, ap: impl Into<String>) -> Self

Append an anti-pattern warning surfaced to AI agents.

Source

pub fn semantic_aliases( self, aliases: impl IntoIterator<Item = impl Into<String>>, ) -> Self

Replace the entire semantic alias list with the given collection.

Semantic aliases are natural-language phrases used for intent-based discovery but are not shown in help text.

To add a single semantic alias use CommandBuilder::semantic_alias.

Source

pub fn semantic_alias(self, s: impl Into<String>) -> Self

Append a single natural-language phrase for intent-based discovery.

Unlike CommandBuilder::alias, semantic aliases are natural-language phrases describing what the command does (e.g. "release to production", "push to environment"). They are used by crate::query::Registry::match_intent but are not shown in help text.

§Examples
let cmd = Command::builder("deploy")
    .semantic_alias("release to production")
    .semantic_alias("push to environment")
    .build().unwrap();

assert_eq!(cmd.semantic_aliases, vec!["release to production", "push to environment"]);
Source

pub fn handler(self, h: HandlerFn) -> Self

Set the runtime handler invoked when this command is dispatched.

The handler receives a ParsedCommand and should return Ok(()) on success or a boxed error on failure.

Source

pub fn async_handler(self, h: AsyncHandlerFn) -> Self

Register an async handler for this command (feature: async).

The handler receives a ParsedCommand and returns a boxed future. Use crate::Cli::run_async to dispatch async handlers.

§Examples
use std::sync::Arc;
use argot_cmd::Command;

let cmd = Command::builder("deploy")
    .async_handler(Arc::new(|parsed| Box::pin(async move {
        println!("deployed!");
        Ok(())
    })))
    .build()
    .unwrap();
Source

pub fn meta(self, key: impl Into<String>, value: Value) -> Self

Set an arbitrary metadata entry on this command.

§Examples
let cmd = Command::builder("deploy")
    .meta("category", json!("infrastructure"))
    .meta("min_role", json!("ops"))
    .build()
    .unwrap();

assert_eq!(cmd.extra["category"], json!("infrastructure"));
Source

pub fn exclusive( self, flags: impl IntoIterator<Item = impl Into<String>>, ) -> Self

Declare a group of mutually exclusive flags.

At most one flag from flags may be provided in a single invocation. The parser returns crate::ParseError::MutuallyExclusive if two or more flags from the same group are present.

§Panics (at build time via BuildError)

CommandBuilder::build returns an error if:

  • The group has fewer than 2 flags.
  • Any flag name in the group is not defined on this command.
§Examples
let cmd = Command::builder("export")
    .flag(Flag::builder("json").build().unwrap())
    .flag(Flag::builder("yaml").build().unwrap())
    .flag(Flag::builder("csv").build().unwrap())
    .exclusive(["json", "yaml", "csv"])
    .build()
    .unwrap();
assert_eq!(cmd.exclusive_groups.len(), 1);
Source

pub fn mutating(self) -> Self

Mark this command as mutating (i.e., it modifies state).

Mutating commands are flagged in help output and JSON schema so that AI agents know they should exercise caution — typically by running a --dry-run first — before dispatching the command.

§Examples
let cmd = Command::builder("delete")
    .summary("Delete a resource")
    .mutating()
    .build()
    .unwrap();

assert!(cmd.mutating);
Source

pub fn build(self) -> Result<Command, BuildError>

Consume the builder and return a Command.

§Errors
§Examples
assert!(Command::builder("ok").build().is_ok());
assert_eq!(Command::builder("").build().unwrap_err(), BuildError::EmptyCanonical);

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.