Add PathBuf to clap_generate::generate_to

This commit is contained in:
dalance 2021-04-05 10:24:09 +09:00
parent 8b721a2bcd
commit 35c3814419

View file

@ -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::<Bash, _, _>(
/// &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::<Bash, _, _>(
/// &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<G, S, T>(app: &mut clap::App, bin_name: S, out_dir: T)
pub fn generate_to<G, S, T>(app: &mut clap::App, bin_name: S, out_dir: T) -> Result<PathBuf, Error>
where
G: Generator,
S: Into<String>,
T: Into<OsString>,
{
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::<G, S>(app, bin_name, &mut file)
_generate::<G, S>(app, &mut file);
Ok(path)
}
/// Generate a completions file for a specified shell at runtime.
@ -185,7 +197,14 @@ where
S: Into<String>,
{
app.set_bin_name(bin_name);
_generate::<G, S>(app, buf)
}
fn _generate<G, S>(app: &mut clap::App, buf: &mut dyn Write)
where
G: Generator,
S: Into<String>,
{
// TODO: All the subcommands need to be built instead of just the top one
app._build();
app._build_bin_names();