1

我想安排子命令,例如:

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

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

我有一些非常类似于以下内容:

main.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),
}

状态.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(),
        }
    }
}
4

1 回答 1

0

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

Option不是 trait文档索引中的 "optional subcommand" 有一个示例

它只是和你做同样的事情,Opts但让[structopt(subcommand)]成员 aOption<T>而不是 a 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 {},
    ...

我有一些非常类似于以下内容:

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

于 2021-01-15T06:56:10.603 回答