Browse Source

Start with getting templates

master
Schneider 5 years ago
parent
commit
792f6dc5c3
  1. 41
      src/app.rs
  2. 8
      src/errors.rs
  3. 34
      src/helpers.rs
  4. 7
      src/template.rs

41
src/app.rs

@ -5,7 +5,6 @@
use std::path::PathBuf; use std::path::PathBuf;
// 3rd-party crate imports // 3rd-party crate imports
use directories::ProjectDirs;
use structopt::StructOpt; use structopt::StructOpt;
use log::{debug, info, trace}; use log::{debug, info, trace};
@ -14,6 +13,7 @@ use log::{debug, info, trace};
use crate::cache::File as FileCache; use crate::cache::File as FileCache;
use crate::errors::*; use crate::errors::*;
use crate::gitignore::Gitignore; use crate::gitignore::Gitignore;
use crate::helpers;
use crate::helpers::{git_dir, BoilerplateOpts, HELP_TEMPLATE}; use crate::helpers::{git_dir, BoilerplateOpts, HELP_TEMPLATE};
use crate::template::*; use crate::template::*;
@ -96,29 +96,32 @@ fn run_add(glob: &str) -> Result<()> {
/// Runs the command `get` /// Runs the command `get`
fn run_get(lang: &str) -> Result<()> { fn run_get(lang: &str) -> Result<()> {
trace!("Run command `get` with lang {}", &lang); trace!("Run command `get` with lang {}", &lang);
unimplemented!();
let root = match git_dir()? {
Some(r) => r,
None => return Err(ErrorKind::NoGitRootFound.into()),
};
info!("Working with git root in {:?}", root);
let tmpls = helpers::get_templates()?;
let tmpl: &Template =
tmpls.get(lang).ok_or_else(|| ErrorKind::TemplateNotFound(lang.to_string()))?;
debug!("Found a template for {}", lang);
let url = tmpl
.download_url
.as_ref()
.ok_or_else(|| ErrorKind::TemplateNoDownloadUrl(lang.to_string()))?;
trace!("Getting template for {} from {}", tmpl.pretty_name(), url);
todo!();
Ok(())
} }
/// Runs the command `list-templates` /// Runs the command `list-templates`
#[allow(clippy::print_stdout)] #[allow(clippy::print_stdout)]
fn run_list_templates() -> Result<()> { fn run_list_templates() -> Result<()> {
let cache_root: PathBuf = match ProjectDirs::from("org", "webschneider", env!("CARGO_PKG_NAME"))
{
Some(dirs) => PathBuf::from(dirs.cache_dir()),
None => "/tmp".into(),
};
let cache: FileCache = FileCache::new(&cache_root, std::time::Duration::from_secs(60 * 24 * 2))
.chain_err(|| "Error while creating FileCache")?;
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
};
let tmpl = helpers::get_templates()?;
let names = tmpl.list_names(); let names = tmpl.list_names();
println!("{}", names.join("\n")); println!("{}", names.join("\n"));
Ok(()) Ok(())

8
src/errors.rs

@ -7,5 +7,13 @@ error_chain! {
NoGitRootFound { NoGitRootFound {
description("no git root found"), description("no git root found"),
} }
TemplateNotFound(t: String) {
description("could not find template"),
display("could not find a template for {}", t),
}
TemplateNoDownloadUrl(name: String) {
description("template has no download url"),
display("template {} has no download url", name)
}
} }
} }

34
src/helpers.rs

@ -7,8 +7,11 @@
#![allow(clippy::result_unwrap_used)] #![allow(clippy::result_unwrap_used)]
use log::{info, trace}; use log::{info, trace};
use crate::cache::File as FileCache;
use crate::errors::*; use crate::errors::*;
use crate::{helpers, template::GithubTemplates};
use directories::ProjectDirs;
use std::path::PathBuf; use std::path::PathBuf;
use structopt::{clap, StructOpt}; use structopt::{clap, StructOpt};
@ -97,3 +100,34 @@ pub fn git_dir() -> Result<Option<PathBuf>> {
info!("Arrived at filesystem root while checking for git folder"); info!("Arrived at filesystem root while checking for git folder");
Ok(None) Ok(None)
} }
/// Returns a `PathBuf` to the cache root for this project
///
/// This will be either the appropriate cache dir according to XDG or as a fallback `/tmp`.
pub fn chache_root() -> PathBuf {
match ProjectDirs::from("org", "webschneider", env!("CARGO_PKG_NAME")) {
Some(dirs) => PathBuf::from(dirs.cache_dir()),
None => "/tmp".into(),
}
}
/// Returns a default file cache
pub fn default_cache() -> Result<FileCache> {
let cache_root = crate::helpers::chache_root();
FileCache::new(&cache_root, std::time::Duration::from_secs(60 * 24 * 2))
}
/// Returns a `GithubTemplates` struct with all available templates
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)
}

7
src/template.rs

@ -95,4 +95,11 @@ impl GithubTemplates {
.map(Template::pretty_name) .map(Template::pretty_name)
.collect() .collect()
} }
/// Returns the template for the given name, if found
pub fn get(&self, name: &str) -> Option<&Template> {
// names have all a .gitignore suffix
let name = format!("{}.gitignore", name);
self.templates.iter().find(|t| t.name.eq_ignore_ascii_case(&name))
}
} }
Loading…
Cancel
Save