iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🎮

Implementing Subcommands with clap in Rust

に公開

clap

Structure

List subcommands in an enum, define the subcommands themselves (arguments, options, etc.) in separate structs, and place the subcommand structs into each variant of the enum that lists the subcommands.

#[derive(Debug, Parser)]
struct Cli {
    #[command(subcommand)]
    subcommand: Commands,
}

#[derive(Debug, Subcommand)]
enum Commands {
    /// initialize
    Init(Init),
    /// create new
    Create(Create),
    /// delete
    Delete(Delete),
    /// show list
    List(List),
}

#[derive(Debug, Args)]
struct Init {
    name: Option<String>,

    #[arg(short = 'p', long = "path")]
    path: Option<String>,
}

#[derive(Debug, Args)]
struct Create {
    name: String,
}

#[derive(Debug, Args)]
struct Delete {
    issue_num: u64,

    #[arg(short = 'u', long = "unresolved")]
    unresolved: bool,
}

#[derive(Debug, Args)]
struct List {
    target_title: Option<String>
}

Rough notes

https://zenn.dev/uliboooo/scraps/872cd14704506c

References

https://koralle.hateblo.jp/entry/2023/12/07/000624

Discussion