diff --git a/clap_generate/src/lib.rs b/clap_generate/src/lib.rs index e8532acf..8b88f09b 100644 --- a/clap_generate/src/lib.rs +++ b/clap_generate/src/lib.rs @@ -33,6 +33,7 @@ mod shell; use std::ffi::OsString; use std::fs::File; +use std::io::Error; use std::io::Write; use std::path::PathBuf; @@ -83,7 +84,7 @@ pub use shell::Shell; /// mod cli; /// /// fn main() { -/// let m = cli::build_cli().get_matches(); +/// let _m = cli::build_cli().get_matches(); /// /// // normal logic continues... /// } @@ -95,29 +96,39 @@ pub use shell::Shell; /// # Cargo.toml /// build = "build.rs" /// +/// [dependencies] +/// clap = "*" +/// /// [build-dependencies] /// clap = "*" +/// clap_generate = "*" /// ``` /// /// Next, we place a `build.rs` in our project root. /// /// ```ignore /// use clap_generate::{generate_to, generators::Bash}; +/// use std::env; +/// use std::io::Error; /// /// include!("src/cli.rs"); /// -/// fn main() { +/// fn main() -> Result<(), Error> { /// let outdir = match env::var_os("OUT_DIR") { -/// None => return, +/// None => return Ok(()), /// Some(outdir) => outdir, /// }; /// /// let mut app = build_cli(); -/// generate_to::( -/// &mut app, // We need to specify what generator to use -/// "myapp", // We need to specify the bin name manually -/// outdir, // We need to specify where to write to -/// ); +/// let path = generate_to::( +/// &mut app, // We need to specify what generator to use +/// "myapp", // We need to specify the bin name manually +/// outdir, // We need to specify where to write to +/// )?; +/// +/// println!("cargo:warning=completion file is generated: {:?}", path); +/// +/// Ok(()) /// } /// ``` /// @@ -127,21 +138,22 @@ pub use shell::Shell; /// /// **NOTE:** Please look at the individual [generators] /// to see the name of the files generated. -pub fn generate_to(app: &mut clap::App, bin_name: S, out_dir: T) +pub fn generate_to(app: &mut clap::App, bin_name: S, out_dir: T) -> Result where G: Generator, S: Into, T: Into, { + app.set_bin_name(bin_name); + let out_dir = PathBuf::from(out_dir.into()); let file_name = G::file_name(app.get_bin_name().unwrap()); - let mut file = match File::create(out_dir.join(file_name)) { - Err(why) => panic!("couldn't create completion file: {}", why), - Ok(file) => file, - }; + let path = out_dir.join(file_name); + let mut file = File::create(&path)?; - generate::(app, bin_name, &mut file) + _generate::(app, &mut file); + Ok(path) } /// Generate a completions file for a specified shell at runtime. @@ -185,7 +197,14 @@ where S: Into, { app.set_bin_name(bin_name); + _generate::(app, buf) +} +fn _generate(app: &mut clap::App, buf: &mut dyn Write) +where + G: Generator, + S: Into, +{ // TODO: All the subcommands need to be built instead of just the top one app._build(); app._build_bin_names();