Skip to content

Commit

Permalink
Merge pull request #17 from perryrh0dan/dev
Browse files Browse the repository at this point in the history
Dev
  • Loading branch information
perryrh0dan authored Aug 21, 2020
2 parents e7ab5e5 + ec67593 commit 3b6c211
Show file tree
Hide file tree
Showing 16 changed files with 346 additions and 397 deletions.
3 changes: 0 additions & 3 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,6 @@
"program": "${workspaceRoot}/target/debug/tmpo",
// "args": ["init", "-r", "https://github.com/perryrh0dan/templates", "-t", "typescript"],
// "args": ["repository", "remove"],
"args": [
"update"
],
"cwd": "${workspaceRoot}",
}
]
Expand Down
274 changes: 215 additions & 59 deletions Cargo.lock

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "tmpo"
version = "1.1.1"
version = "1.1.2"
authors = ["Thomas Pöhlmann <thomaspoehlmann96@googlemail.com>"]
edition = "2018"

Expand All @@ -12,7 +12,7 @@ serde_json = "1.0.48"
serde_yaml = "0.8.13"
dirs = "2.0.2"
log = "0.4.8"
env_logger = "0.7.1"
log4rs = "0.13.0"
git2 = "0.12"
custom_error = "1.7.1"
colored = "1.9.3"
Expand Down
1 change: 0 additions & 1 deletion src/action/default/init.rs
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,6 @@ pub fn init(config: &Config, args: &ArgMatches) {
repository: Some(String::from(&workspace_repository)),
username: username,
email: email,
replace: false,
};

//// Copy the template
Expand Down
30 changes: 15 additions & 15 deletions src/action/default/update.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,19 +10,18 @@ use clap::{crate_version};
use tar::Archive;
use flate2::read::GzDecoder;


pub fn update() -> Result<(), Box<::std::error::Error>> {
pub fn update(interactive: bool) {
let releases = self_update::backends::github::ReleaseList::configure()
.repo_owner("perryrh0dan")
.repo_name("tmpo")
.build()?
.fetch()?;
.build().unwrap()
.fetch().unwrap();

// check version
let version = crate_version!();
if releases[0].version == version {
out::no_app_update();
return Ok(());
if interactive { out::no_app_update() };
return;
}

println!("Checking target-arch: {}", &self_update::get_target());
Expand All @@ -33,23 +32,25 @@ pub fn update() -> Result<(), Box<::std::error::Error>> {
Some(value) => value,
None => {
println!("New release is not compatible");
return Ok(());
return;
}
};

println!("New release is compatible");
println!();

// user input
let update = confirm("The new release will be downloaded/extraced and the existing binary will be replaced.\nDo you want to continue?");

if !update {
return Ok(());
if interactive {
let update = confirm("The new release will be downloaded/extraced and the existing binary will be replaced.\nDo you want to continue?");

if !update {
return;
}
}

let tmp_dir = tempfile::Builder::new().tempdir_in(::std::env::current_dir()?)?;
let tmp_dir = tempfile::Builder::new().tempdir_in(::std::env::current_dir().unwrap()).unwrap();
let tmp_tarball_path = tmp_dir.path().join(&asset.name);
std::fs::File::create(&tmp_tarball_path)?;
std::fs::File::create(&tmp_tarball_path).unwrap();
let tmp_tarball = std::fs::OpenOptions::new().create(true).append(true).open(&tmp_tarball_path).unwrap();

// download asset
Expand All @@ -75,7 +76,7 @@ pub fn update() -> Result<(), Box<::std::error::Error>> {
let bin_path = tmp_dir.path().join(bin_name);
self_update::Move::from_source(&bin_path)
.replace_using_temp(&tmp_file)
.to_dest(&::std::env::current_exe()?)?;
.to_dest(&::std::env::current_exe().unwrap()).unwrap();

// remove tmp folder
match std::fs::remove_dir_all(tmp_dir) {
Expand All @@ -84,5 +85,4 @@ pub fn update() -> Result<(), Box<::std::error::Error>> {
};

out::success_update_app();
Ok(())
}
4 changes: 3 additions & 1 deletion src/config/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ extern crate serde_yaml;

#[derive(serde::Serialize, serde::Deserialize, Debug)]
pub struct Config {
pub auto_update: bool,
pub templates_dir: String,
pub templates_repositories: Vec<RepositoryOptions>,
}
Expand Down Expand Up @@ -126,6 +127,7 @@ fn get_default_config() -> Config {
});

let config = Config {
auto_update: true,
templates_dir: template_dir,
templates_repositories: repo_options,
};
Expand All @@ -144,7 +146,7 @@ fn config_location() -> PathBuf {
return dir;
}

fn directory() -> PathBuf {
pub fn directory() -> PathBuf {
let mut path = config_location();
path.pop();

Expand Down
18 changes: 8 additions & 10 deletions src/git/mod.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,6 @@
use std::str;
use std::path::Path;

use crate::out;

#[macro_use]
use log::debug;
use std::str;
use log;

extern crate custom_error;
extern crate git2;
Expand Down Expand Up @@ -99,6 +95,9 @@ fn do_fetch<'a>(
opts: &GitOptions,
) -> Result<git2::AnnotatedCommit<'a>, git2::Error> {
// token needs to be declared here to live longer than the fetchOptions

log::info!("Fetching repository");

let token;
let mut fo = git2::FetchOptions::new();
let mut callbacks = git2::RemoteCallbacks::new();
Expand All @@ -115,17 +114,17 @@ fn do_fetch<'a>(
// )
// });
} else if auth == "token" {
debug!("[git]: authentication using token");
log::debug!("[git]: authentication using token");
if opts.token.is_none() {
out::errors::missing_token();
log::error!("No token was provided");
return Err(git2::Error::from_str("missing auth token"));
}
token = opts.token.clone().unwrap();
callbacks.credentials(|_url, _username_from_url, _allowed_types| {
git2::Cred::userpass_plaintext(&token, "")
});
} else {
debug!("[git]: no authentication");
log::debug!("[git]: no authentication");
}

// Always fetch all tags.
Expand Down Expand Up @@ -217,7 +216,6 @@ fn do_merge<'a>(
match repo.find_reference(&refname) {
Ok(mut r) => {
fast_forward(repo, &mut r, &fetch_commit)?;
out::success_update_templates()
}
Err(_) => {
// The branch doesn't exist so just set the reference to the
Expand Down
38 changes: 38 additions & 0 deletions src/logger/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
use log::LevelFilter;
use log4rs::{
append::{
console::{ConsoleAppender, Target},
file::FileAppender,
},
config::{Appender, Config, Root},
encode::pattern::PatternEncoder,
filter::threshold::ThresholdFilter,
};

use crate::config;

pub fn init() {
// Build a stderr logger.
let stderr = ConsoleAppender::builder()
.encoder(Box::new(PatternEncoder::new("{d(%Y-%m-%d %H:%M:%S)} {l} - {m}\n")))
.target(Target::Stderr)
.build();

// Logging to log file
let logfile_path = config::directory().join("log/output.log");

let logfile = FileAppender::builder()
.encoder(Box::new(PatternEncoder::new("{d(%Y-%m-%d %H:%M:%S)} {l} - {m}\n")))
.build(logfile_path).unwrap();


let config = Config::builder()
.appender(Appender::builder().build("logfile", Box::new(logfile)))
.appender(Appender::builder().filter(Box::new(ThresholdFilter::new(log::LevelFilter::Error))).build("stderr", Box::new(stderr)))
.build(Root::builder()
.appender("logfile")
.appender("stderr")
.build(LevelFilter::Info)).unwrap();

log4rs::init_config(config).unwrap();
}
17 changes: 11 additions & 6 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,20 @@ mod out;
mod repository;
mod template;
mod utils;
mod logger;

use clap::{crate_version, App, AppSettings, Arg};
use env_logger;

fn main() {
// initialize logger
env_logger::init();
// Initiate config
let mut config = config::init().unwrap();

// Initiate logger
logger::init();

if config.auto_update {
action::default::update::update(false);
}

let matches = App::new("tmpo")
.version(crate_version!())
Expand Down Expand Up @@ -94,8 +101,6 @@ fn main() {
)
.get_matches();

let mut config = config::init().unwrap();

match matches.subcommand() {
("init", Some(init_matches)) => {
action::default::init::init(&config, init_matches);
Expand All @@ -104,7 +109,7 @@ fn main() {
action::default::list::list(&config, list_matches);
}
("update", Some(_update_matches)) => {
action::default::update::update();
action::default::update::update(true);
}
("view", Some(view_matches)) => {
action::default::view::view(&config, view_matches);
Expand Down
15 changes: 0 additions & 15 deletions src/out/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,22 +44,7 @@ pub fn copy_template() {
println!("{}", text);
}

pub fn template_dir_not_found(dir: &str) {
let text = format!("{} {}", "Cant find template dir:", dir).red();
println!("{}", text);
}

pub fn template_dir_permission_denied(dir: &str) {
let text = format!("{} {}", "Cant read template dir:", dir).red();
println!("{}", text);
}

pub fn missing_token() {
let text = format!("Error fetching templates: authentication token is missing").red();
println!("{}", text);
}

pub fn unknown() {
let text = format!("Unknown error occured").red();
println!("{}", text);
}
17 changes: 1 addition & 16 deletions src/out/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ pub fn list_templates(templates: &Vec<String>) {
}

pub fn no_app_update() {
let text = format!("tmpo is alread up to date").green();
let text = format!("tmpo is already up to date").green();
println!("{}", text);
}

Expand All @@ -27,21 +27,6 @@ pub fn success_create(name: &str) {
println!("{}", text);
}

pub fn check_template_updates() {
let text = format!("Check for template updates");
println!("{}", text);
}

pub fn no_template_updates() {
let text = format!("No updates found").green();
println!("{}", text);
}

pub fn success_update_templates() {
let text = format!("Successful updated templates").green();
println!("{}", text);
}

pub fn display_template(template: &template::Template) {
println!("name: {}", template.name);
println!("path: {}", template.path);
Expand Down
6 changes: 0 additions & 6 deletions src/out/warnings.rs
Original file line number Diff line number Diff line change
@@ -1,6 +0,0 @@
use colored::Colorize;

pub fn no_subcommand() {
let text = format!("No subcommand was used").yellow();
println!("{}", text);
}
Loading

0 comments on commit 3b6c211

Please sign in to comment.