1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
#![warn(clippy::all, clippy::pedantic)]
#![allow(clippy::missing_errors_doc)]
#![doc = include_str!("../README.md")]

use std::{
    error::Error,
    fs,
    ops::Deref,
    path::{Path, PathBuf},
};

#[cfg(feature = "mangen")]
use {clap_mangen::Man, std::io};

#[cfg(feature = "complete")]
use {
    clap_complete::{generate_to, shells},
    clap_complete_nushell::Nushell,
};

/// a command installer
pub struct Bootstrap {
    name: String,
    cli: clap::Command,
}

impl Bootstrap {
    #[must_use]
    pub fn new(name: &str, cli: clap::Command) -> Self {
        Self {
            name: name.to_string(),
            cli,
        }
    }

    #[cfg(feature = "complete")]
    fn gencomp(&self, outdir: PathBuf, gen: &str) -> Result<(), Box<dyn Error>> {
        let mut cmd = self.cli.clone();
        let path = match gen {
            "bash" => generate_to(shells::Bash, &mut cmd, &self.name, outdir)?,
            "fish" => generate_to(shells::Fish, &mut cmd, &self.name, outdir)?,
            "nu" => generate_to(Nushell, &mut cmd, &self.name, outdir)?,
            "pwsh" => generate_to(shells::PowerShell, &mut cmd, &self.name, outdir)?,
            "zsh" => generate_to(shells::Zsh, &mut cmd, &self.name, outdir)?,
            "elvish" => generate_to(shells::Elvish, &mut cmd, &self.name, outdir)?,
            _ => unimplemented!(),
        };
        println!("    {}", path.display());
        Ok(())
    }

    #[cfg(feature = "complete")]
    /// Generates and installs shell completions for all supported shells into
    /// `dir`.
    /// ## Examples
    /// To install shell completions under /usr:
    /// ```no_run
    /// use package_bootstrap::Bootstrap;
    /// 
    /// fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     Bootstrap::new("foo", clap::Command::new("foo"))
    ///         .completions(std::path::Path::new("/usr"))?;
    ///     Ok(())
    /// }
    /// ```
    /// To install into a staging directory for packaging purposes:
    /// ```no_run
    /// use package_bootstrap::Bootstrap;
    /// 
    /// fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     Bootstrap::new("foo", clap::Command::new("foo"))
    ///         .completions(std::path::Path::new("staging/usr"))?;
    ///     Ok(())
    /// }
    pub fn completions<P: Deref<Target = Path>>(&self, dir: P) -> Result<(), Box<dyn Error>> {
        println!("Generating completions:");
        ["bash", "fish", "nu", "pwsh", "zsh", "elvish"]
            .iter()
            .try_for_each(|gen| {
                let mut outdir = dir.to_path_buf();
                let base = match *gen {
                    "bash" => ["share", "bash-completion", "completions"],
                    "zsh" => ["share", "zsh", "site-functions"],
                    "nu" => ["share", "nu", "completions"],
                    "pwsh" => ["share", "pwsh", "completions"],
                    "fish" => ["share", "fish", "completions"],
                    "elvish" => ["share", "elvish", "completions"],
                    _ => unimplemented!(),
                };
                base.iter().for_each(|d| outdir.push(d));
                if !outdir.exists() {
                    fs::create_dir_all(&outdir)?;
                }
                self.gencomp(outdir, gen)
            })?;
        Ok(())
    }

    fn copy_bin<P: Deref<Target = Path>>(
        &self,
        dir: P,
        arch: Option<String>,
    ) -> Result<(), Box<dyn Error>> {
        println!("Copying binary:");
        let mut bindir = dir.to_path_buf();
        bindir.push("bin");
        if !bindir.exists() {
            fs::create_dir_all(&bindir)?;
        }
        let mut outfile = bindir;
        outfile.push("hpk");
        let infile: PathBuf = if let Some(arch) = arch {
            ["target", &arch, "release", &self.name].iter().collect()
        } else {
            ["target", "release", &self.name].iter().collect()
        };
        if !infile.exists() {
            eprintln!("Error: you must run \"cargo build --release\" first");
        }
        fs::copy(&infile, &outfile)?;
        println!("    {} -> {}", infile.display(), outfile.display());
        Ok(())
    }

    #[cfg(feature = "mangen")]
    /// Install a Unix man page base on the given `clap::Command` struct.
    /// ## Example
    /// Install a manual page for this command into /usr, in the man1 section:
    /// ```no_run
    /// use package_bootstrap::Bootstrap;
    ///
    /// fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     Bootstrap::new("foo", clap::Command::new("foo"))
    ///         .manpage(std::path::Path::new("/usr"), 1)?;
    ///     Ok(())
    /// }
    /// ```
    /// Install a manual page into a staging directory in the man8 section:
    /// ```no_run
    /// use package_bootstrap::Bootstrap;
    ///
    /// fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     Bootstrap::new("foo", clap::Command::new("foo"))
    ///         .manpage(std::path::Path::new("pkg/usr"), 8)?;
    ///     Ok(())
    /// }
    pub fn manpage<P: Deref<Target = Path>>(
        &self,
        dir: P,
        section: u8
    ) -> Result<(), io::Error> {
        let fname = format!("{}.{section}", &self.name);
        println!("Generating manpage {fname}:");
        let command = self.cli.clone();
        let mut outdir: PathBuf = dir.to_path_buf();
        ["share", "man", &format!("man.{section}")]
            .iter()
            .for_each(|d| outdir.push(d));
        if !outdir.exists() {
            fs::create_dir_all(&outdir)?;
        }
        let mut outfile = outdir;
        outfile.push(fname);
        let man = Man::new(command);
        let mut buffer: Vec<u8> = vec![];
        man.render(&mut buffer)?;
        fs::write(&outfile, buffer)?;
        println!("    {}", outfile.display());
        Ok(())
    }

    pub fn install(
        &self,
        dir: &Path,
        arch: Option<String>,
        #[cfg(feature = "mangen")]
        section: u8,
    ) -> Result<(), Box<dyn Error>> {
        self.copy_bin(dir, arch)?;
        #[cfg(feature = "complete")]
        self.completions(dir)?;
        #[cfg(feature = "mangen")]
        self.manpage(dir, section)?;
        Ok(())
    }
}