Commands Guide

Defining commands and subcommands with XaCLI derive macros

Commands Guide

Application Definition

use xacli::derive::{App, Command};
use xacli::Context;

#[derive(App)]
#[app(
    name = "myapp",
    version = "1.0.0",
    title = "My App",
    description = "A CLI application"
)]
struct MyApp {
    #[command(subcommands)]
    commands: Commands,
}

Subcommands (Enum)

#[derive(Command)]
enum Commands {
    /// Add a new item
    Add(AddCmd),
    /// Remove an item  
    Remove(RemoveCmd),
}

Leaf Command (Struct)

#[derive(Command)]
#[command(description = "Add an item")]
struct AddCmd {
    #[arg(short = 'n', long = "name")]
    name: bool,
}

impl AddCmd {
    fn run(&self, ctx: &mut dyn Context) -> xacli::Result<()> {
        use std::io::Write;
        writeln!(ctx.stdout(), "Adding item...")?;
        Ok(())
    }
}

Nested Command Groups

#[derive(Command)]
#[command(description = "Database commands")]
struct DbCmd {
    #[command(subcommands)]
    action: DbActions,
}

#[derive(Command)]
enum DbActions {
    Migrate(MigrateCmd),
    Seed(SeedCmd),
}

Attribute Reference

#[app(...)] - Application

AttributeDescription
nameCLI name
versionVersion string
titleDisplay title
descriptionHelp text

#[command(...)] - Commands

AttributeDescription
descriptionCommand help
nameOverride name
subcommandsMark as container

#[arg(...)] - Arguments

AttributeDescription
shortShort flag (-x)
longLong flag (--name)
positionalPositional arg

Execution

fn main() {
    if let Err(e) = MyApp::execute() {
        eprintln!("Error: {}", e);
        std::process::exit(1);
    }
}