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
195
196
197
198
199
200
201
202
203
//! Utility functions that are needed all over the places.
#![allow(dead_code)]
use std::{io, fs};
use std::env::{self, home_dir, current_dir};
use std::ffi::OsStr;
use std::path::{Path, PathBuf};
use std::process::{self, Command, ExitStatus};
use chrono::NaiveTime;

use log::{LogRecord, LogLevelFilter};
use env_logger::LogBuilder;

use open;

pub mod yaml;

//#[export_macro]
macro_rules! try_some {
    ($expr:expr) => (match $expr {
        Some(val) => val,
        None => return None,
    });
}

pub fn setup_log() {
    let format = |record: &LogRecord| {
        let location = record.location();
        format!("{level}::{location}:  {args}",
        location = location.module_path(),
        level = record.level(),
        args  = record.args())
    };

    let mut builder = LogBuilder::new();
    builder
        .format(format)
        .filter(None, LogLevelFilter::Info);

    let log_var ="ASCIII_LOG";
    if env::var(log_var).is_ok() {
       builder.parse(&env::var(log_var).unwrap());
    }

    builder.init().unwrap();
}

/// Freezes the program until for inspection
pub fn freeze() {
    io::stdin().read_line(&mut String::new()).unwrap();
}

/// Asks for confirmation
pub fn really(msg:&str) -> bool {
    println!("{} ", msg);
    let mut answer = String::new();
    if io::stdin().read_line(&mut answer).is_err(){ return false; }
    ["yes", "y",
    "j", "ja",
    "oui", "si", "da"]
        .contains(&answer.trim())
}

/// Shells out to print directory structure
pub fn ls(path:&str){
    println!("find {}", path); // TODO implement in here with walkdir
    let output = Command::new("find")
        .arg(&path)
        .output()
        .unwrap_or_else(|e| { panic!("failed to execute process: {}", e) });
    println!("{}", String::from_utf8(output.stdout).unwrap());
}

/// Replaces `~` with `$HOME`, rust stdlib doesn't do this yet.
///
/// This is by far the most important function of all utility functions.
///
/// **TODO** add something like this to the stdlib
/// **TODO** ~ must be first character
pub fn replace_home_tilde(p:&Path) -> PathBuf{
    let path = p.to_str().unwrap();
    PathBuf::from( path.replace("~",home_dir().unwrap().to_str().unwrap()))
}

/// Opens the passed paths in the editor set int config.
///
/// This is by far the most important function of all utility functions.
//TODO use https://crates.io/crates/open (supports linux, windows, mac)
pub fn pass_to_command<T:AsRef<OsStr>>(editor:&Option<&str>, paths:&[T]) {

    let paths = paths.iter()
                      .map(|o|PathBuf::from(&o))
                      .filter(|p|p.exists())
                      .collect::<Vec<PathBuf>>();


    if paths.is_empty() {
        warn!("non of the provided paths could be found")
    } else if let Some(ref editor) = *editor {
        if paths.len() < 5 || really (&format!("you are about to open {} files\n{:#?}\nAre you sure about this?", paths.len(), paths))
        {
            let editor_config = editor
                .split_whitespace()
                .collect::<Vec<&str>>();

            let (editor_command,args) = editor_config.split_first().unwrap() ;
            info!("launching {:?} with {:?} and {:?}",
                  editor_command,
                  args.join(" "),
                  paths);

            Command::new(editor_command)
                .args(args)
                .args(&paths)
                .status()
                .unwrap_or_else(|e| { panic!("failed to execute process: {}", e) });

        }
    } else {
        for path in paths{
            open::that(path).unwrap();
        }
    }
}

/// Deletes the file if the passed in closure returns `true`
pub fn delete_file_if<F,P:AsRef<OsStr>>(path:P, confirmed:F) -> io::Result<()>
    where F: Fn()->bool
{
    let path = PathBuf::from(&path);
    if confirmed(){
        debug!("$ rm {}", path.display());
        fs::remove_file(&path)
    } else {Ok(())}
}

/// takes a path that could be relative or contains a `~` and turn it into a path that exists
pub fn get_valid_path<T:AsRef<OsStr>>(p:T) -> Option<PathBuf>{
    let path = replace_home_tilde(Path::new(&p));
    let path = if !path.is_absolute(){
        current_dir().unwrap().join(path)
    } else { path };

    if path.exists() {
        Some(path)
    } else {None}
}

/// Exits with the exit status of a child process.
pub fn exit(status:ExitStatus) -> !{
    process::exit(status.code().unwrap_or(1));
}

use bill::Currency;

/// One place to decide how to display currency
pub fn currency_to_string(currency:&Currency) -> String {
    currency.postfix().to_string()
}

// TODO there may be cases where an f64 can't be converted into Currency
pub fn to_currency(f: f64) -> Currency {
    Currency{ symbol: ::CONFIG.get_char("currency"), value: (f * 1000.0) as i64} / 10
}

// tiny little helper
pub fn to_local_file(file:&Path, ext:&str) -> PathBuf {
    let mut _tmpfile = file.to_owned();
    _tmpfile.set_extension(ext);
    Path::new(_tmpfile.file_name().unwrap()).to_owned()
}

pub fn naive_time_from_str(string:&str) -> Option<NaiveTime> {
    let t:Vec<u32> = string
        .splitn(2, |p| p == '.' || p == ':')
        .map(|s|s.parse().unwrap_or(0))
        .collect();

    if let (Some(h),m) = (t.get(0),t.get(1).unwrap_or(&0)){
        if *h < 24 && *m < 60 {
            return Some(NaiveTime::from_hms(*h,*m,0))
        }
    }

    None
}

#[test]
fn test_naive_time_from_str() {
    assert_eq!(Some(NaiveTime::from_hms(9,15,0)), naive_time_from_str("9.15"));
    assert_eq!(Some(NaiveTime::from_hms(9,0,0)),  naive_time_from_str("9."));
    assert_eq!(Some(NaiveTime::from_hms(9,0,0)),  naive_time_from_str("9"));
    assert_eq!(Some(NaiveTime::from_hms(23,0,0)), naive_time_from_str("23.0"));
    assert_eq!(Some(NaiveTime::from_hms(23,59,0)), naive_time_from_str("23.59"));
    assert_eq!(None, naive_time_from_str("24.0"));
    assert_eq!(None, naive_time_from_str("25.0"));
    assert_eq!(None, naive_time_from_str("0.60"));

    assert_eq!(Some(NaiveTime::from_hms(9,15,0)), naive_time_from_str("9:15"));
    assert_eq!(Some(NaiveTime::from_hms(9,0,0)),  naive_time_from_str("9:"));
    assert_eq!(Some(NaiveTime::from_hms(9,0,0)),  naive_time_from_str("9"));
    assert_eq!(Some(NaiveTime::from_hms(23,0,0)), naive_time_from_str("23:0"));
}