0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

トナカイ 一頭Advent Calendar 2024

Day 7

Rustのclap(v4)でcliツール作成を触ってみた

Last updated at Posted at 2024-12-07

コードサンプル

バージョン

[dependencies]
clap = { version = "4.5.23", features = ["derive"] }

clapとは

引数パースを簡単にしてくれるクレート

clapのArgAction

  • ArgAction::SetTrue フラグをセット
  • ArgAction::SetFalse フラグをリセット
  • ArgAction::Set 値をセット
  • ArgAction::Append 値を追加
  • ArgAction::Count オプションが出た回数をカウント

位置引数

.required(true)をつける

オプショナル引数

.short.longをつける

ArgAction::Appendの複数受け取り

.num_args(1..)

コード例

use clap::{Arg, ArgAction, Command};

fn main() {
    // CLIの構成
    let matches = Command::new("Clap Sample")
        .version("1.0")
        .author("Your Name <youremail@example.com>")
        .about("A simple CLI example using clap")
        .arg(
            Arg::new("first")
                .help("The First Positional Argument")
                .required(true) // 必須の位置引数
        )
        .arg(
            Arg::new("second")
                .help("The Second Positional Argument")
                .required(false), // 任意の位置引数
        )
        .arg(
            Arg::new("name")
                .short('n')
                .long("name")
                .value_name("NAME")
                .help("Sets a custom name")
                .action(ArgAction::Set),
        )
        .arg(
            Arg::new("debug")
                .short('d')
                .long("debug")
                .value_name("DEBUG")
                .help("Enables debug mode")
                .action(ArgAction::SetTrue),
        )
        .arg(
            Arg::new("list")
                .short('l')
                .long("list")
                .value_name("List")
                .help("List")
                .action(ArgAction::Append)
                .num_args(1..), // 1つ以上の値を受け取る
        )
        .get_matches();
    ...
}

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?