1 //! Example to test arguments with different ValueHint values.
2 //!
3 //! Usage with zsh:
4 //! ```sh
5 //! cargo run --example value_hints -- --generate=zsh > /usr/local/share/zsh/site-functions/_value_hints
6 //! compinit
7 //! ./target/debug/examples/value_hints --<TAB>
8 //! ```
9 //! fish:
10 //! ```sh
11 //! cargo run --example value_hints -- --generate=fish > value_hints.fish
12 //! . ./value_hints.fish
13 //! ./target/debug/examples/value_hints --<TAB>
14 //! ```
15 use clap::{value_parser, Arg, Command, ValueHint};
16 use clap_complete::{generate, Generator, Shell};
17 use std::io;
18
build_cli() -> Command19 fn build_cli() -> Command {
20 let value_hint_command = Command::new("value-hint")
21 .visible_alias("hint")
22 .arg(
23 Arg::new("unknown")
24 .long("unknown")
25 .value_hint(ValueHint::Unknown),
26 )
27 .arg(Arg::new("other").long("other").value_hint(ValueHint::Other))
28 .arg(
29 Arg::new("path")
30 .long("path")
31 .short('p')
32 .value_hint(ValueHint::AnyPath),
33 )
34 .arg(
35 Arg::new("file")
36 .long("file")
37 .short('f')
38 .value_hint(ValueHint::FilePath),
39 )
40 .arg(
41 Arg::new("dir")
42 .long("dir")
43 .short('d')
44 .value_hint(ValueHint::DirPath),
45 )
46 .arg(
47 Arg::new("exe")
48 .long("exe")
49 .short('e')
50 .value_hint(ValueHint::ExecutablePath),
51 )
52 .arg(
53 Arg::new("cmd_name")
54 .long("cmd-name")
55 .value_hint(ValueHint::CommandName),
56 )
57 .arg(
58 Arg::new("cmd")
59 .long("cmd")
60 .short('c')
61 .value_hint(ValueHint::CommandString),
62 )
63 .arg(
64 Arg::new("command_with_args")
65 .num_args(1..)
66 // AppSettings::TrailingVarArg is required to use ValueHint::CommandWithArguments
67 .trailing_var_arg(true)
68 .value_hint(ValueHint::CommandWithArguments),
69 )
70 .arg(
71 Arg::new("user")
72 .short('u')
73 .long("user")
74 .value_hint(ValueHint::Username),
75 )
76 .arg(
77 Arg::new("host")
78 .long("host")
79 .value_hint(ValueHint::Hostname),
80 )
81 .arg(Arg::new("url").long("url").value_hint(ValueHint::Url))
82 .arg(
83 Arg::new("email")
84 .long("email")
85 .value_hint(ValueHint::EmailAddress),
86 );
87
88 Command::new("completion")
89 .arg(
90 Arg::new("generator")
91 .long("generate")
92 .value_parser(value_parser!(Shell)),
93 )
94 .subcommand(value_hint_command)
95 }
96
print_completions<G: Generator>(gen: G, cmd: &mut Command)97 fn print_completions<G: Generator>(gen: G, cmd: &mut Command) {
98 generate(gen, cmd, cmd.get_name().to_string(), &mut io::stdout());
99 }
100
main()101 fn main() {
102 let matches = build_cli().get_matches();
103
104 if let Some(generator) = matches.get_one::<Shell>("generator") {
105 let mut cmd = build_cli();
106 eprintln!("Generating completion file for {generator}...");
107 print_completions(*generator, &mut cmd);
108 }
109 }
110