1 //! How to use `required_if` with structopt.
2 //!
3 //! Running this example with --help prints this message:
4 //! -----------------------------------------------------
5 //! structopt 0.3.25
6 //!
7 //! USAGE:
8 //! required_if -o <out-type> [FILE]
9 //!
10 //! FLAGS:
11 //! -h, --help Prints help information
12 //! -V, --version Prints version information
13 //!
14 //! OPTIONS:
15 //! -o <out-type> Where to write the output: to `stdout` or `file`
16 //!
17 //! ARGS:
18 //! <FILE> File name: only required when `out-type` is set to `file`
19 //! -----------------------------------------------------
20
21 use structopt::StructOpt;
22
23 #[derive(Debug, StructOpt, PartialEq)]
24 struct Opt {
25 /// Where to write the output: to `stdout` or `file`
26 #[structopt(short)]
27 out_type: String,
28
29 /// File name: only required when `out-type` is set to `file`
30 #[structopt(name = "FILE", required_if("out-type", "file"))]
31 file_name: Option<String>,
32 }
33
main()34 fn main() {
35 let opt = Opt::from_args();
36 println!("{:?}", opt);
37 }
38
39 #[cfg(test)]
40 mod tests {
41 use super::*;
42
43 #[test]
test_opt_out_type_file_without_file_name_returns_err()44 fn test_opt_out_type_file_without_file_name_returns_err() {
45 let opt = Opt::from_iter_safe(&["test", "-o", "file"]);
46 let err = opt.unwrap_err();
47 assert_eq!(err.kind, clap::ErrorKind::MissingRequiredArgument);
48 }
49
50 #[test]
test_opt_out_type_file_with_file_name_returns_ok()51 fn test_opt_out_type_file_with_file_name_returns_ok() {
52 let opt = Opt::from_iter_safe(&["test", "-o", "file", "filename"]);
53 let opt = opt.unwrap();
54 assert_eq!(
55 opt,
56 Opt {
57 out_type: "file".into(),
58 file_name: Some("filename".into()),
59 }
60 );
61 }
62 }
63