Browse Source

read template content from cache if available

master
Schneider 5 years ago
parent
commit
d4b0549769
  1. 2
      Cargo.lock
  2. 8
      Cargo.toml
  3. 24
      src/app.rs
  4. 8
      src/cache.rs
  5. 4
      src/main.rs
  6. 4
      src/template.rs

2
Cargo.lock

@ -325,7 +325,7 @@ dependencies = [
[[package]] [[package]]
name = "gitig" name = "gitig"
version = "0.1.0"
version = "0.1.1"
dependencies = [ dependencies = [
"directories", "directories",
"error-chain", "error-chain",

8
Cargo.toml

@ -1,6 +1,6 @@
[package] [package]
name = "gitig" name = "gitig"
version = "0.1.0"
version = "0.1.1"
authors = ["Marcel Schneider <marcel@webschneider.org>"] authors = ["Marcel Schneider <marcel@webschneider.org>"]
edition = "2018" edition = "2018"
@ -13,11 +13,11 @@ serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0" serde_json = "1.0"
directories = "2.0" directories = "2.0"
[target.'cfg(unix)'.dependencies]
libc = "0.2"
[dependencies.error-chain] [dependencies.error-chain]
version = "0.12" version = "0.12"
[target.'cfg(unix)'.dependencies]
libc = "0.2"
#default-features = false # disable pulling in backtrace #default-features = false # disable pulling in backtrace
[profile.release] [profile.release]

24
src/app.rs

@ -10,7 +10,7 @@ use structopt::StructOpt;
use log::{debug, info, trace}; use log::{debug, info, trace};
// Local Imports // Local Imports
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;
@ -58,7 +58,8 @@ pub struct CliOpts {
cmd: Command, cmd: Command,
} }
/// Subcommands
/// gitig lets you easily start with a fresh gitignore from a template and adds new lines as you
/// wish
#[derive(StructOpt, Debug)] #[derive(StructOpt, Debug)]
pub enum Command { pub enum Command {
/// Add a line to the gitignore /// Add a line to the gitignore
@ -69,6 +70,8 @@ pub enum Command {
/// Download a gitignore for a language /// Download a gitignore for a language
Get { Get {
/// The language for which the gitignore should be downloaded /// The language for which the gitignore should be downloaded
///
/// A list with all available languages and projects can be printed with `list-templates`.
lang: String, lang: String,
}, },
/// List all available templates that can be downloaded /// List all available templates that can be downloaded
@ -102,12 +105,19 @@ fn run_get(lang: &str) -> Result<()> {
}; };
info!("Working with git root in {:?}", root); info!("Working with git root in {:?}", root);
let mut tmpls = helpers::get_templates()?;
let tmpl: &mut Template =
tmpls.get(lang).ok_or_else(|| ErrorKind::TemplateNotFound(lang.to_string()))?;
debug!("Found a template for {}", lang);
let cache = helpers::default_cache()?;
let tmpl: Template = if cache.exists(lang) {
debug!("Found a template for {} in cache", lang);
cache.get(lang)?
} else {
let tmpls = helpers::get_templates()?;
let mut tmpl =
tmpls.get(lang).ok_or_else(|| ErrorKind::TemplateNotFound(lang.to_string()))?.clone();
tmpl.load_content()?; tmpl.load_content()?;
cache.set(lang, &tmpl)?;
tmpl
};
root.push(".gitignore"); root.push(".gitignore");
tmpl.write_to(&root)?; tmpl.write_to(&root)?;
trace!("Wrote template to file"); trace!("Wrote template to file");

8
src/cache.rs

@ -69,7 +69,8 @@ impl File {
} }
/// Stores a `data` under the specified `key` /// Stores a `data` under the specified `key`
pub fn set(&self, key: &str, data: &GithubTemplates) -> Result<()> {
pub fn set<T>(&self, key: &str, data: &T) -> Result<()>
where T: Serialize {
let mut path: PathBuf = self.root.clone(); let mut path: PathBuf = self.root.clone();
path.push(key); path.push(key);
trace!("Serializing data to cache file {}", path.to_string_lossy()); trace!("Serializing data to cache file {}", path.to_string_lossy());
@ -83,14 +84,15 @@ impl File {
} }
/// Retrieves data for `key` /// Retrieves data for `key`
pub fn get(&self, key: &str) -> Result<GithubTemplates> {
pub fn get<T>(&self, key: &str) -> Result<T>
where T: serde::de::DeserializeOwned {
let mut path = self.root.clone(); let mut path = self.root.clone();
path.push(key); path.push(key);
debug!("Retrieving {} from file cache", key); debug!("Retrieving {} from file cache", key);
let f = FsFile::open(path) let f = FsFile::open(path)
.chain_err(|| format!("Error while opening cache file for key {}", key))?; .chain_err(|| format!("Error while opening cache file for key {}", key))?;
let reader = BufReader::new(f); let reader = BufReader::new(f);
let obj: GithubTemplates = serde_json::from_reader(reader)
let obj: T = serde_json::from_reader(reader)
.chain_err(|| "Error while reading templates from file cache")?; .chain_err(|| "Error while reading templates from file cache")?;
debug!("Deserialized {} templates from file cache", "some"); debug!("Deserialized {} templates from file cache", "some");
Ok(obj) Ok(obj)

4
src/main.rs

@ -39,6 +39,7 @@ use std::io;
// 3rd-party imports // 3rd-party imports
mod errors; mod errors;
use log::{debug, trace};
use structopt::{clap, StructOpt}; use structopt::{clap, StructOpt};
// Local imports // Local imports
@ -75,9 +76,11 @@ fn main() {
.timestamp(opts.boilerplate.timestamp.unwrap_or(stderrlog::Timestamp::Off)) .timestamp(opts.boilerplate.timestamp.unwrap_or(stderrlog::Timestamp::Off))
.init() .init()
.expect("initializing logging output"); .expect("initializing logging output");
trace!("Initialized logging");
// If requested, generate shell completions and then exit with status of "success" // If requested, generate shell completions and then exit with status of "success"
if let Some(shell) = opts.boilerplate.dump_completions { if let Some(shell) = opts.boilerplate.dump_completions {
debug!("Request to dump completion for {}", shell);
app::CliOpts::clap().gen_completions_to( app::CliOpts::clap().gen_completions_to(
app::CliOpts::clap().get_bin_name().unwrap_or_else(|| clap::crate_name!()), app::CliOpts::clap().get_bin_name().unwrap_or_else(|| clap::crate_name!()),
shell, shell,
@ -86,6 +89,7 @@ fn main() {
std::process::exit(0); std::process::exit(0);
}; };
trace!("Starting with application");
if let Err(ref e) = app::main(opts) { if let Err(ref e) = app::main(opts) {
use std::io::prelude::*; use std::io::prelude::*;
let stderr = std::io::stderr(); let stderr = std::io::stderr();

4
src/template.rs

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