【问题标题】:How to create a StructOpt command where all subcomands are optional如何创建所有子命令都是可选的 StructOpt 命令
【发布时间】:2021-01-15 06:34:45
【问题描述】:

我想安排如下子命令:

  • mycmd status :打印一个简短的状态 - 不工作
  • mycmd status full:打印详细状态 - OK
  • mycmd status dump :将完整的调试状态转储到文件 - 好的

我无法实现简单的mycmd status,因为 StructOpt 认为我缺少必需的子命令(子子命令?)并打印使用情况。文档表明我需要以某种方式使用 Option<> 特征,但我无法弄清楚在这种情况下如何使用。

我有类似以下的东西:

ma​​in.rs

use structopt::StructOpt;
// ... other use cmds ...
#[derive(Debug, StructOpt)]
#[structopt(
    name = "mycmd",
    about = "A utility to do stuff."
)]
#[structopt(setting = structopt::clap::AppSettings::ColoredHelp)]
#[structopt(setting = structopt::clap::AppSettings::SubcommandRequired)]
struct Opts {
    #[structopt(short = "v", parse(from_occurrences))]
    /// Increase message verbosity
    verbosity: usize,
    #[structopt(subcommand)]
    cmd: Tool,
}

#[derive(Debug, StructOpt)]
enum Tool {
    #[structopt(name = "dofoo")]
    DoFoo(dofoo::Command),
    #[structopt(name = "status")]
    Status(status::Command),
}

status.rs

use structopt::StructOpt;

#[derive(Debug, StructOpt)]
#[structopt(name = "status", about = "Get the status of stuff.")]
#[structopt(setting = structopt::clap::AppSettings::ColoredHelp)]
#[structopt(max_term_width = 80)]
pub enum Command {
    #[structopt(name = "full")]
    /// Print full (i.e. verbose) status
    Full {},
    #[structopt(name = "dump")]
    /// Creates a zipped dump of the full system status to a file
    Dump {
        #[structopt(short = "o", long = "out", value_name = "FILE", parse(from_os_str))]
        /// Filename of the output file.
        out_fname: PathBuf,
    },
}

impl Command {
    pub fn execute(self) -> Result<()> {
        match self {
            Command::Full {} => cmd_do_verbose_print(),
            Command::Dump { out_fname } => cmd_do_file_dump(out_fname),
            // TODO: Bad. This is dead code.
            _ => cmd_do_print(),
        }
    }
}

【问题讨论】:

    标签: rust command-line-arguments clap structopt


    【解决方案1】:

    文档表明我需要以某种方式使用 Option&lt;&gt; 特征,但我无法弄清楚在这种情况下如何使用。

    Option is not a traitthere's an example right there in the documentation's index at "optional subcommand"

    它与您的Opts 做同样的事情,但将[structopt(subcommand)] 成员设为Option&lt;T&gt; 而不是T

        #[derive(Debug, StructOpt)]
        pub struct Command {
            #[structopt(subcommand)]
            cmd: Option<Cmd>,
        }
        #[derive(Debug, StructOpt)]
        pub enum Cmd {
            /// Print full (i.e. verbose) status
            Full {},
        ...
    

    我有类似以下的东西:

    当您遇到问题时,实际可运行的重现案例很有用...

    【讨论】:

      猜你喜欢
      • 2012-11-21
      • 2018-11-13
      • 2016-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-25
      • 1970-01-01
      相关资源
      最近更新 更多