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
#![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;
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();
}
pub fn freeze() {
io::stdin().read_line(&mut String::new()).unwrap();
}
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())
}
pub fn ls(path:&str){
println!("find {}", path);
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());
}
pub fn replace_home_tilde(p:&Path) -> PathBuf{
let path = p.to_str().unwrap();
PathBuf::from( path.replace("~",home_dir().unwrap().to_str().unwrap()))
}
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();
}
}
}
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(())}
}
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}
}
pub fn exit(status:ExitStatus) -> !{
process::exit(status.code().unwrap_or(1));
}
use bill::Currency;
pub fn currency_to_string(currency:&Currency) -> String {
currency.postfix().to_string()
}
pub fn to_currency(f: f64) -> Currency {
Currency{ symbol: ::CONFIG.get_char("currency"), value: (f * 1000.0) as i64} / 10
}
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"));
}