Skip to content

Commit

Permalink
Add required_if example
Browse files Browse the repository at this point in the history
  • Loading branch information
rgardner authored and CreepySkeleton committed Jul 10, 2020
1 parent c7d028a commit e47d78c
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
4 changes: 4 additions & 0 deletions examples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,10 @@ How to completely remove version.

How `#[structopt(rename_all)]` works.

### [Required If](required_if.rs)

How to use `#[structopt(required_if)]`.

### [Skip](skip.rs)

How to use `#[structopt(skip)]`.
Expand Down
43 changes: 43 additions & 0 deletions examples/required_if.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
//! How to use `required_if` with structopt.
use structopt::StructOpt;

#[derive(Debug, StructOpt, PartialEq)]
struct Opt {
/// Where to write the output: to `stdout` or `file`
#[structopt(short)]
out_type: String,

/// File name: only required when `out-type` is set to `file`
#[structopt(name = "FILE", required_if("out-type", "file"))]
file_name: Option<String>,
}

fn main() {
let opt = Opt::from_args();
println!("{:?}", opt);
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn test_opt_out_type_file_without_file_name_returns_err() {
let opt = Opt::from_iter_safe(&["test", "-o", "file"]);
let err = opt.unwrap_err();
assert_eq!(err.kind, clap::ErrorKind::MissingRequiredArgument);
}

#[test]
fn test_opt_out_type_file_with_file_name_returns_ok() {
let opt = Opt::from_iter_safe(&["test", "-o", "file", "filename"]);
let opt = opt.unwrap();
assert_eq!(
opt,
Opt {
out_type: "file".into(),
file_name: Some("filename".into()),
}
);
}
}

0 comments on commit e47d78c

Please sign in to comment.