Clap completion question

⚓ Rust    📅 2026-04-17    👤 surdeus    👁️ 3      

surdeus

Info

This post is auto-generated from RSS feed The Rust Programming Language Forum - Latest topics. Source: Clap completion question

Let's say I have a program claptest like this:

Test program for clap --ignore flag and shell completion

Usage: claptest [OPTIONS]

Options:
      --ignore <IGNORE>...
          Comma-separated list of things to ignore: blabla, something, other
          
          [possible values: blabla, something, other]

      --completion <SHELL>
          Generate shell completion script and print to stdout.
          
          Examples: claptest --completion fish > ~/.config/fish/completions/claptest.fish claptest --completion bash > ~/.bash_completion.d/claptest claptest --completion zsh  > ~/.zsh/completions/_claptest
          
          [possible values: bash, elvish, fish, powershell, zsh]

  -h, --help
          Print help (see a summary with '-h')

I like to have completion for a call to claptest like this claptest --ignore blabla,something
I get completion only for one of blabla, something or `other'

Here my source

use std::io;

use clap::{CommandFactory, Parser, ValueEnum};
use clap_complete::{Shell, generate};

// ── Ignore values ─────────────────────────────────────────────────────────────

#[derive(Debug, Clone, ValueEnum, PartialEq)]
enum Ignore {
    Blabla,
    Something,
    Other,
}

// ── CLI definition ────────────────────────────────────────────────────────────

#[derive(Parser, Debug)]
#[command(
    name = "claptest",
    about = "Test program for clap --ignore flag and shell completion"
)]
struct Args {
    /// Comma-separated list of things to ignore: blabla, something, other
    #[arg(long, value_delimiter = ',', num_args = 1..)]
    ignore: Vec<Ignore>,

    /// Generate shell completion script and print to stdout.
    ///
    /// Examples:
    ///   claptest --completion fish > ~/.config/fish/completions/claptest.fish
    ///   claptest --completion bash > ~/.bash_completion.d/claptest
    ///   claptest --completion zsh  > ~/.zsh/completions/_claptest
    #[arg(long, value_name = "SHELL")]
    completion: Option<Shell>,
}

// ── Main ──────────────────────────────────────────────────────────────────────

fn main() {
    let args = Args::parse();

    if let Some(shell) = args.completion {
        let mut cmd = Args::command();
        generate(shell, &mut cmd, "claptest", &mut io::stdout());
        return;
    }

    println!(
        "ignore_dupes:      {}",
        args.ignore.contains(&Ignore::Blabla)
    );
    println!(
        "ignore_same_named: {}",
        args.ignore.contains(&Ignore::Something)
    );
    println!(
        "ignore_tmpfiles:   {}",
        args.ignore.contains(&Ignore::Other)
    );
}

Any help appreciated.

1 post - 1 participant

Read full topic

🏷️ Rust_feed