github_templates/
cli.rs

1use clap_flags;
2use failure::ResultExt;
3use std::io;
4use std::path::PathBuf;
5use structopt;
6
7/// Command line parser.
8#[derive(Debug, StructOpt)]
9#[structopt(
10  about = "Generate GitHub issue templates.",
11  raw(setting = "structopt::clap::AppSettings::ColoredHelp")
12)]
13pub struct Cli {
14  #[structopt(flatten)]
15  logger: clap_flags::Log,
16  #[structopt(flatten)]
17  verbosity: clap_flags::Verbosity,
18  /// Project name. Defaults to target directory name
19  #[structopt(short = "n", long = "name")]
20  name: Option<String>,
21  /// Target directory
22  #[structopt(default_value = ".")]
23  dir: String,
24}
25
26impl Cli {
27  /// Initialize a logger.
28  #[inline]
29  pub fn log(&self, name: &str) -> ::Result<()> {
30    self
31      .logger
32      .log(self.verbosity.log_level(), name)
33      .context(::ErrorKind::Log)?;
34    Ok(())
35  }
36
37  /// Access the dir. Checks if it's a directory on disk.
38  #[inline]
39  pub fn dir(&self) -> ::Result<PathBuf> {
40    let path: PathBuf = self.dir.clone().into();
41    if !path.is_dir() {
42      let err = io::Error::new(io::ErrorKind::InvalidInput, "");
43      Err(::ErrorKind::Io(err))?;
44    }
45    let path = path.canonicalize().context(::ErrorKind::Other)?;
46    Ok(path)
47  }
48
49  /// Access the directory name.
50  #[inline]
51  pub fn name(&self) -> ::Result<String> {
52    match &self.name {
53      Some(name) => Ok(name.to_string()),
54      None => {
55        let dir = self.dir().context(::ErrorKind::Other)?;
56        let dir = dir.iter().last().ok_or_else(|| ::ErrorKind::Other)?;
57        let dir = dir.to_str().ok_or_else(|| ::ErrorKind::Other)?;
58        Ok(dir.to_string())
59      }
60    }
61  }
62}