1 /// This build script checks for env vars to build ouch with shell completions.
3 /// # How to generate shell completions:
5 /// Set `OUCH_COMPLETIONS_FOLDER` to the name of the destination folder:
8 /// OUCH_COMPLETIONS_FOLDER=my-folder cargo build
11 /// All completion files will be generated inside of the folder "my-folder".
13 /// If the folder does not exist, it will be created.
15 /// We recommend you naming this folder "completions" for the sake of consistency.
18 /// OUCH_COMPLETIONS_FOLDER=completions cargo build
21 /// # Retrocompatibility
23 /// The old method that still works so it does not break older packages.
25 /// Using `GEN_COMPLETIONS=1` still works for those packages who need it,
29 /// GEN_COMPLETIONS=1 cargo build
32 /// Will generate completions to a cargo target default folder, for example:
33 /// - `target/debug/build/ouch-195b34a8adca6ec3/out/completions`
35 /// The _"195b34a8adca6ec3"_ part is a hash that might change between runs.
36 use std::{env, fs::create_dir_all, path::Path};
38 use clap::{ArgEnum, IntoApp};
39 use clap_complete::{generate_to, Shell};
41 include!("src/opts.rs");
44 println!("cargo:rerun-if-env-changed=GEN_COMPLETIONS");
46 if let Some(completions_output_directory) = detect_completions_output_directory() {
47 create_dir_all(&completions_output_directory).expect("Could not create shell completions output folder.");
48 let app = &mut Opts::command();
50 for shell in Shell::value_variants() {
51 generate_to(*shell, app, "ouch", &completions_output_directory)
52 .unwrap_or_else(|err| panic!("Failed to generate shell completions for {}: {}.", shell, err));
57 /// Decide whether or not to generate completions, and the destination.
59 /// Note that `OUCH_COMPLETIONS_FOLDER` is checked before `GEN_COMPLETIONS`.
60 fn detect_completions_output_directory() -> Option<PathBuf> {
61 // Get directory from var
62 if let Some(dir) = env::var_os("OUCH_COMPLETIONS_FOLDER") {
63 return Some(dir.into());
66 // If set, directory goes inside of cargo's `target/`
67 let gen_completions = env::var_os("GEN_COMPLETIONS").map(|var| &var == "1").unwrap_or(false);
69 let out_dir = env::var_os("OUT_DIR").unwrap();
70 let dir = Path::new(&out_dir).join("completions");