1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate lazy_static;

use std::fs;
use std::path::PathBuf;

use crate::core::DBRoot;
use chrono::prelude::*;
use clap;
use clap::{App, AppSettings, Arg, ArgMatches, SubCommand};
use config::{Config, File};
use crossterm_style::Color::*;
use dirs;
use termimad::*;

mod commands;
mod core;
mod errors;
mod format;
mod history;
mod history_storage;
mod parse;
mod print;
mod report;
mod storage;
mod style;

use errors::*;
pub(crate) use format::*;
use history::DBWatcher;
pub use print::*;
use storage::sqlite::DB;
pub(crate) use style::*;

pub struct CrateInfo<'a> {
    pub name: &'a str,
    pub version: &'a str,
    pub authors: &'a str,
    pub description: &'a str,
}

pub struct AppContext<'a, T, P>
where
    T: DBRoot,
    P: Printer,
{
    pub args: ArgMatches<'a>,
    pub conf: AppConfig,
    pub root: PathBuf,
    pub printer: P,
    pub db: T,
}

#[derive(Debug, Deserialize)]
pub struct AppConfig {
    pub db_path: String,
    pub history_db_path: String,
}
impl Default for AppConfig {
    fn default() -> Self {
        let db_path = String::from("yatt.db");
        let history_db_path = String::from("yatt_history.db");
        AppConfig {
            db_path,
            history_db_path,
        }
    }
}

fn parse_config(base_path: &PathBuf) -> CliResult<AppConfig> {
    let mut s = Config::new();
    let path = base_path.join("config");
    if s.merge(File::with_name(path.to_str().unwrap())).is_err() {
        return Ok(AppConfig::default());
    }
    match s.try_into() {
        Ok(res) => Ok(res),
        Err(e) => Err(CliError::Config { source: e }),
    }
}

fn make_args<'a>(info: &CrateInfo<'a>) -> ArgMatches<'a> {
    let app = App::new(info.name)
        .version(info.version)
        .author(info.authors)
        .about(info.description)
        .setting(AppSettings::ArgRequiredElseHelp);

    commands::register(app).get_matches()
}

fn app_dir(name: &str) -> CliResult<PathBuf> {
    if let Some(p) = dirs::config_dir() {
        return Ok(p.join(name));
    }
    Err(CliError::AppDir {
        message: "Unable to resolve os config directory path".to_string(),
    })
}

pub fn run(info: CrateInfo) -> CliResult<()> {
    let base_path = app_dir(info.name)?;
    if !base_path.exists() {
        if let Err(e) = fs::create_dir_all(&base_path) {
            return Err(CliError::Io { source: e });
        }
    } else if !base_path.is_dir() {
        return Err(CliError::AppDir {
            message: format!("{} is not a directory", base_path.to_str().unwrap_or("")),
        });
    }

    let mut conf = parse_config(&base_path)?;

    #[cfg(debug_assertions)]
    debug_config(&mut conf);

    let db = match DB::new(base_path.join(&conf.db_path)) {
        Ok(db) => db,
        Err(e) => return Err(CliError::DB { source: e }),
    };

    let history_db_path = base_path.join(&conf.history_db_path);
    if history_db_path.exists() {
        let hs = {
            match history_storage::sqlite::DB::new(history_db_path) {
                Ok(db) => db,
                Err(e) => return Err(CliError::DB { source: e }),
            }
        };
        let db = DBWatcher::new(db, hs);
        run_app(db, base_path, &info, conf)
    } else {
        run_app(db, base_path, &info, conf)
    }
}

fn run_app<T: DBRoot>(
    db: T,
    base_path: PathBuf,
    info: &CrateInfo,
    conf: AppConfig,
) -> CliResult<()> {
    let mut skin = MadSkin::default();
    skin.set_headers_fg(rgb(255, 187, 0));
    skin.bold.set_fg(Yellow);
    skin.italic.set_fgbg(Magenta, rgb(30, 30, 40));
    skin.bullet = StyledChar::from_fg_char(Yellow, '⟡');
    skin.quote_mark.set_fg(Yellow);

    let printer = TermPrinter::default();
    let app = AppContext {
        args: make_args(info),
        conf,
        root: base_path,
        printer,
        db,
    };
    let res = commands::exec(&app);
    if res.is_err() {
        print_error(res.as_ref().unwrap_err(), &app.printer);
    }

    res
}

fn print_error<T: Printer>(e: &CliError, p: &T) {
    if let CliError::Task { source } = e {
        match source {
            TaskError::Cmd { message } => p.error(message),
            TaskError::CmdTaskInterval {
                message,
                interval,
                task,
            } => p.interval_error(
                &IntervalData {
                    interval,
                    task,
                    title: IntervalData::default_title(),
                },
                message,
            ),
        }
        return;
    }

    p.error(&e.to_string());
}

fn debug_config(conf: &mut AppConfig) {
    conf.db_path = "yatt_debug.db".to_string();
}