• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //! Shell completion machinery
2 
3 pub mod utils;
4 
5 use std::ffi::OsString;
6 use std::fs::File;
7 use std::io::Error;
8 use std::io::Write;
9 use std::path::PathBuf;
10 
11 use clap::Command;
12 
13 /// Generator trait which can be used to write generators
14 pub trait Generator {
15     /// Returns the file name that is created when this generator is called during compile time.
16     ///
17     /// # Panics
18     ///
19     /// May panic when called outside of the context of [`generate`] or [`generate_to`]
20     ///
21     /// # Examples
22     ///
23     /// ```
24     /// # use std::io::Write;
25     /// # use clap::Command;
26     /// use clap_complete::Generator;
27     ///
28     /// pub struct Fish;
29     ///
30     /// impl Generator for Fish {
31     /// #   fn generate(&self, cmd: &Command, buf: &mut dyn Write) {}
32     ///     fn file_name(&self, name: &str) -> String {
33     ///         format!("{}.fish", name)
34     ///     }
35     /// }
36     /// ```
file_name(&self, name: &str) -> String37     fn file_name(&self, name: &str) -> String;
38 
39     /// Generates output out of [`clap::Command`](Command).
40     ///
41     /// # Panics
42     ///
43     /// May panic when called outside of the context of [`generate`] or [`generate_to`]
44     ///
45     /// # Examples
46     ///
47     /// The following example generator displays the [`clap::Command`](Command)
48     /// as if it is printed using [`std::println`].
49     ///
50     /// ```
51     /// use std::{io::Write, fmt::write};
52     /// use clap::Command;
53     /// use clap_complete::Generator;
54     ///
55     /// pub struct ClapDebug;
56     ///
57     /// impl Generator for ClapDebug {
58     ///     fn generate(&self, cmd: &Command, buf: &mut dyn Write) {
59     ///         write!(buf, "{}", cmd).unwrap();
60     ///     }
61     /// #   fn file_name(&self, name: &str) -> String {
62     /// #    name.into()
63     /// #   }
64     /// }
65     /// ```
generate(&self, cmd: &Command, buf: &mut dyn Write)66     fn generate(&self, cmd: &Command, buf: &mut dyn Write);
67 }
68 
69 /// Generate a completions file for a specified shell at compile-time.
70 ///
71 /// **NOTE:** to generate the file at compile time you must use a `build.rs` "Build Script" or a
72 /// [`cargo-xtask`](https://github.com/matklad/cargo-xtask)
73 ///
74 /// # Examples
75 ///
76 /// The following example generates a bash completion script via a `build.rs` script. In this
77 /// simple example, we'll demo a very small application with only a single subcommand and two
78 /// args. Real applications could be many multiple levels deep in subcommands, and have tens or
79 /// potentially hundreds of arguments.
80 ///
81 /// First, it helps if we separate out our `Command` definition into a separate file. Whether you
82 /// do this as a function, or bare Command definition is a matter of personal preference.
83 ///
84 /// ```
85 /// // src/cli.rs
86 /// # use clap::{Command, Arg, ArgAction};
87 /// pub fn build_cli() -> Command {
88 ///     Command::new("compl")
89 ///         .about("Tests completions")
90 ///         .arg(Arg::new("file")
91 ///             .help("some input file"))
92 ///         .subcommand(Command::new("test")
93 ///             .about("tests things")
94 ///             .arg(Arg::new("case")
95 ///                 .long("case")
96 ///                 .action(ArgAction::Set)
97 ///                 .help("the case to test")))
98 /// }
99 /// ```
100 ///
101 /// In our regular code, we can simply call this `build_cli()` function, then call
102 /// `get_matches()`, or any of the other normal methods directly after. For example:
103 ///
104 /// ```ignore
105 /// // src/main.rs
106 ///
107 /// mod cli;
108 ///
109 /// fn main() {
110 ///     let _m = cli::build_cli().get_matches();
111 ///
112 ///     // normal logic continues...
113 /// }
114 /// ```
115 ///
116 /// Next, we set up our `Cargo.toml` to use a `build.rs` build script.
117 ///
118 /// ```toml
119 /// # Cargo.toml
120 /// build = "build.rs"
121 ///
122 /// [dependencies]
123 /// clap = "*"
124 ///
125 /// [build-dependencies]
126 /// clap = "*"
127 /// clap_complete = "*"
128 /// ```
129 ///
130 /// Next, we place a `build.rs` in our project root.
131 ///
132 /// ```ignore
133 /// use clap_complete::{generate_to, shells::Bash};
134 /// use std::env;
135 /// use std::io::Error;
136 ///
137 /// include!("src/cli.rs");
138 ///
139 /// fn main() -> Result<(), Error> {
140 ///     let outdir = match env::var_os("OUT_DIR") {
141 ///         None => return Ok(()),
142 ///         Some(outdir) => outdir,
143 ///     };
144 ///
145 ///     let mut cmd = build_cli();
146 ///     let path = generate_to(
147 ///         Bash,
148 ///         &mut cmd, // We need to specify what generator to use
149 ///         "myapp",  // We need to specify the bin name manually
150 ///         outdir,   // We need to specify where to write to
151 ///     )?;
152 ///
153 ///     println!("cargo:warning=completion file is generated: {:?}", path);
154 ///
155 ///     Ok(())
156 /// }
157 /// ```
158 ///
159 /// Now, once we compile there will be a `{bin_name}.bash` file in the directory.
160 /// Assuming we compiled with debug mode, it would be somewhere similar to
161 /// `<project>/target/debug/build/myapp-<hash>/out/myapp.bash`.
162 ///
163 /// **NOTE:** Please look at the individual [shells][crate::shells]
164 /// to see the name of the files generated.
generate_to<G, S, T>( gen: G, cmd: &mut clap::Command, bin_name: S, out_dir: T, ) -> Result<PathBuf, Error> where G: Generator, S: Into<String>, T: Into<OsString>,165 pub fn generate_to<G, S, T>(
166     gen: G,
167     cmd: &mut clap::Command,
168     bin_name: S,
169     out_dir: T,
170 ) -> Result<PathBuf, Error>
171 where
172     G: Generator,
173     S: Into<String>,
174     T: Into<OsString>,
175 {
176     cmd.set_bin_name(bin_name);
177 
178     let out_dir = PathBuf::from(out_dir.into());
179     let file_name = gen.file_name(cmd.get_bin_name().unwrap());
180 
181     let path = out_dir.join(file_name);
182     let mut file = File::create(&path)?;
183 
184     _generate::<G, S>(gen, cmd, &mut file);
185     Ok(path)
186 }
187 
188 /// Generate a completions file for a specified shell at runtime.
189 ///
190 /// Until `cargo install` can install extra files like a completion script, this may be
191 /// used e.g. in a command that outputs the contents of the completion script, to be
192 /// redirected into a file by the user.
193 ///
194 /// # Examples
195 ///
196 /// Assuming a separate `cli.rs` like the [`generate_to` example](generate_to()),
197 /// we can let users generate a completion script using a command:
198 ///
199 /// ```ignore
200 /// // src/main.rs
201 ///
202 /// mod cli;
203 /// use std::io;
204 /// use clap_complete::{generate, shells::Bash};
205 ///
206 /// fn main() {
207 ///     let matches = cli::build_cli().get_matches();
208 ///
209 ///     if matches.is_present("generate-bash-completions") {
210 ///         generate(Bash, &mut cli::build_cli(), "myapp", &mut io::stdout());
211 ///     }
212 ///
213 ///     // normal logic continues...
214 /// }
215 ///
216 /// ```
217 ///
218 /// Usage:
219 ///
220 /// ```shell
221 /// $ myapp generate-bash-completions > /usr/share/bash-completion/completions/myapp.bash
222 /// ```
generate<G, S>(gen: G, cmd: &mut clap::Command, bin_name: S, buf: &mut dyn Write) where G: Generator, S: Into<String>,223 pub fn generate<G, S>(gen: G, cmd: &mut clap::Command, bin_name: S, buf: &mut dyn Write)
224 where
225     G: Generator,
226     S: Into<String>,
227 {
228     cmd.set_bin_name(bin_name);
229     _generate::<G, S>(gen, cmd, buf)
230 }
231 
_generate<G, S>(gen: G, cmd: &mut clap::Command, buf: &mut dyn Write) where G: Generator, S: Into<String>,232 fn _generate<G, S>(gen: G, cmd: &mut clap::Command, buf: &mut dyn Write)
233 where
234     G: Generator,
235     S: Into<String>,
236 {
237     cmd.build();
238 
239     gen.generate(cmd, buf)
240 }
241