#![allow(clippy::result_unwrap_used)]
use log::{info, trace};
use crate::cache::File as FileCache;
use crate::errors::*;
use crate::{helpers, template::GithubTemplates};
use directories::ProjectDirs;
use std::{env, path::PathBuf};
use structopt::StructOpt;
pub const HELP_TEMPLATE: &str = "{bin} {version}
{about}
USAGE:
{usage}
{all-args}
";
#[derive(StructOpt, Debug)]
#[structopt(rename_all = "kebab-case")]
pub struct BoilerplateOpts {
#[structopt(short, long, parse(from_occurrences))]
pub quiet: u64,
#[structopt(short, long, parse(from_occurrences))]
pub verbose: u64,
#[structopt(short, long, value_name = "resolution")]
pub timestamp: Option<stderrlog::Timestamp>,
}
fn has_git_dir(path: &PathBuf) -> Result<bool> {
trace!("Checking for git root in {:?}", &path);
let mut git: PathBuf = path.clone();
git.push(".git");
for entry in path.read_dir().chain_err(|| "Reading contents of dir")? {
if let Ok(entry) = entry {
if entry.path() == git {
return Ok(true);
}
}
}
Ok(false)
}
pub fn git_dir() -> Result<Option<PathBuf>> {
let mut cwd: Option<PathBuf> =
Some(std::env::current_dir().chain_err(|| "Error with current dir")?);
while cwd.is_some() {
let c = cwd.ok_or("Should not have been none, as checked before in if")?;
if has_git_dir(&c)? {
return Ok(Some(c));
}
cwd = c.parent().map(PathBuf::from);
}
info!("Arrived at filesystem root while checking for git folder");
Ok(None)
}
pub fn cache_root() -> PathBuf {
match ProjectDirs::from("org", "webschneider", env!("CARGO_PKG_NAME")) {
Some(dirs) => PathBuf::from(dirs.cache_dir()),
None => "/tmp".into(),
}
}
pub fn default_cache() -> Result<FileCache> {
let cache_root = crate::helpers::cache_root();
FileCache::new(&cache_root, std::time::Duration::from_secs(60 * 24 * 2))
}
pub fn get_templates() -> Result<GithubTemplates> {
let cache = helpers::default_cache().chain_err(|| "Error while creating cache")?;
let tmpl = if cache.exists("templates.json") {
cache.get("templates.json")?
} else {
let tmpls = GithubTemplates::new().chain_err(|| "Error while getting Templates")?;
cache
.set("templates.json", &tmpls)
.chain_err(|| "Error while writing templates to cache")?;
tmpls
};
Ok(tmpl)
}