summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorNora <nora.widdecke@tu-bs.de>2019-01-09 22:37:03 +0100
committerNora <nora.widdecke@tu-bs.de>2019-01-11 19:02:48 +0100
commit373ceb68ee851199c7913d1ada4d950548a9b543 (patch)
tree8cbc33644d1f5aea86be63de5ac305da8ea57c9a
parent40d94368e21e9136b31356799ed1755cb6f96f71 (diff)
split off misc from fileutils
-rw-r--r--src/bucketable.rs4
-rw-r--r--src/cal.rs6
-rw-r--r--src/copy.rs9
-rw-r--r--src/edit.rs4
-rw-r--r--src/index.rs6
-rw-r--r--src/new.rs7
-rw-r--r--src/selectors/daterange.rs5
-rw-r--r--src/show.rs7
-rw-r--r--src/utils/fileutil.rs33
-rw-r--r--src/utils/misc.rs61
-rw-r--r--src/utils/mod.rs3
11 files changed, 91 insertions, 54 deletions
diff --git a/src/bucketable.rs b/src/bucketable.rs
index 180e970..6fac49e 100644
--- a/src/bucketable.rs
+++ b/src/bucketable.rs
@@ -3,7 +3,7 @@ use std::collections::HashMap;
use std::{hash, cmp};
use icalwrap::{IcalVEvent, IcalVCalendar};
-use utils::fileutil as utils;
+use utils::misc;
pub trait Bucketable {
fn get_buckets(&self) -> Result<HashMap<String, Vec<String>>, String>;
@@ -12,7 +12,7 @@ pub trait Bucketable {
let mut buckets = Vec::new();
while start.iso_week() <= end.iso_week() {
- let bucket = utils::get_bucket_for_date(start);
+ let bucket = misc::get_bucket_for_date(start);
buckets.push(bucket);
start = start.checked_add_signed(Duration::days(7)).unwrap();
}
diff --git a/src/cal.rs b/src/cal.rs
index 5a8c335..a23be91 100644
--- a/src/cal.rs
+++ b/src/cal.rs
@@ -2,7 +2,7 @@ use chrono::Duration;
use chrono::prelude::*;
use yansi::{Style,Color};
-use utils::fileutil as utils;
+use utils::misc;
struct Cell {
date: NaiveDate,
@@ -15,8 +15,8 @@ pub fn printcal() {
let b = cal_month(now.with_month(now.month() + 1).unwrap());
let c = cal_month(now.with_month(now.month() + 2).unwrap());
- let joined = utils::joinlines(&a, &b);
- let joined = utils::joinlines(&joined, &c);
+ let joined = misc::joinlines(&a, &b);
+ let joined = misc::joinlines(&joined, &c);
println!("{}", joined);
}
diff --git a/src/copy.rs b/src/copy.rs
index 9386c2e..5ed7aef 100644
--- a/src/copy.rs
+++ b/src/copy.rs
@@ -1,4 +1,5 @@
-use utils::fileutil as utils;
+use utils::fileutil;
+use utils::misc;
pub fn do_copy(lines: &mut Iterator<Item = String>, _args: &[String]) {
@@ -8,14 +9,14 @@ pub fn do_copy(lines: &mut Iterator<Item = String>, _args: &[String]) {
return;
};
- let cal = match utils::read_khaleesi_line(&lines[0]) {
+ let cal = match fileutil::read_khaleesi_line(&lines[0]) {
Ok(calendar) => calendar,
Err(error) => {
error!("{}", error);
return
},
};
- let new_cal = match cal.with_uid(&utils::make_new_uid()) {
+ let new_cal = match cal.with_uid(&misc::make_new_uid()) {
Ok(new_cal) => new_cal,
Err(error) => {
error!("{}", error);
@@ -24,7 +25,7 @@ pub fn do_copy(lines: &mut Iterator<Item = String>, _args: &[String]) {
};
let new_cal = new_cal.with_dtstamp_now();
- match utils::write_cal(&new_cal) {
+ match fileutil::write_cal(&new_cal) {
Ok(_) => info!("Successfully wrote file: {}", new_cal.get_path().unwrap().display()),
Err(error) => {
error!("{}", error);
diff --git a/src/edit.rs b/src/edit.rs
index c5ed46f..d7a03bb 100644
--- a/src/edit.rs
+++ b/src/edit.rs
@@ -2,13 +2,13 @@ use std::env;
use std::fs;
use std::process::Command;
-use utils::fileutil as utils;
+use utils::misc;
pub fn do_edit(filenames: &mut Iterator<Item = String>, _args: &[String]) {
let mut paths: Vec<String> = filenames.map( |line| {
let parts: Vec<&str> = line.splitn(2, ' ').collect();
- match utils::datetime_from_timestamp(parts[0]) {
+ match misc::datetime_from_timestamp(parts[0]) {
Some(_) => parts[1].to_string(),
None => parts[0].to_string(),
}
diff --git a/src/index.rs b/src/index.rs
index d990143..445e4c0 100644
--- a/src/index.rs
+++ b/src/index.rs
@@ -7,10 +7,12 @@ use walkdir::DirEntry;
use defaults::*;
use utils::lock;
-use utils::fileutil;
+//use utils::fileutil;
use chrono::prelude::*;
use indextime;
+use utils::fileutil;
+use utils::misc;
fn add_buckets_for_calendar(buckets: &mut HashMap<String, Vec<String>>, cal: &IcalVCalendar) {
use bucketable::Bucketable;
@@ -70,7 +72,7 @@ pub fn index_dir(dir: &Path, reindex: bool) {
}
write_index(&indexdir, &buckets);
- info!("Index written in {}ms", fileutil::format_duration(&now.elapsed()));
+ info!("Index written in {}ms", misc::format_duration(&now.elapsed()));
indextime::write_index_time(&start_time);
}
diff --git a/src/new.rs b/src/new.rs
index 175c4c5..c46629d 100644
--- a/src/new.rs
+++ b/src/new.rs
@@ -1,10 +1,11 @@
-use utils::fileutil as utils;
+use utils::fileutil;
+use utils::misc;
use icalwrap::IcalVCalendar;
use defaults;
pub fn do_new(_lines: &mut Iterator<Item = String>, _args: &[String]) {
- let uid = utils::make_new_uid();
+ let uid = misc::make_new_uid();
let path = defaults::get_datafile(&(uid.clone() + ".ics"));
let new_cal = match IcalVCalendar::from_str(TEMPLATE_EVENT, Some(path)).unwrap().with_uid(&uid) {
@@ -16,7 +17,7 @@ pub fn do_new(_lines: &mut Iterator<Item = String>, _args: &[String]) {
};
let new_cal = new_cal.with_dtstamp_now();
- match utils::write_cal(&new_cal) {
+ match fileutil::write_cal(&new_cal) {
Ok(_) => info!("Successfully wrote file: {}", new_cal.get_path().unwrap().display()),
Err(error) => {
error!("{}", error);
diff --git a/src/selectors/daterange.rs b/src/selectors/daterange.rs
index 05ed7a2..62302ca 100644
--- a/src/selectors/daterange.rs
+++ b/src/selectors/daterange.rs
@@ -5,6 +5,7 @@ use std::str::FromStr;
use super::*;
use utils::dateutil;
+use utils::misc;
pub struct SelectFilterFrom {
pub date: Option<Date<Local>>,
@@ -22,7 +23,7 @@ impl SelectFilterFrom {
}
fn from_date(date: Option<Date<Local>>) -> Self {
- Self { date, bucket: date.map(utils::get_bucket_for_date) }
+ Self { date, bucket: date.map(misc::get_bucket_for_date) }
}
pub fn combine_with(self, other: &Self) -> Self {
@@ -41,7 +42,7 @@ impl SelectFilterTo {
}
fn from_date(date: Option<Date<Local>>) -> Self {
- Self { date, bucket: date.map(utils::get_bucket_for_date) }
+ Self { date, bucket: date.map(misc::get_bucket_for_date) }
}
pub fn combine_with(self, other: &Self) -> Self {
diff --git a/src/show.rs b/src/show.rs
index a18e701..6b8cfdd 100644
--- a/src/show.rs
+++ b/src/show.rs
@@ -1,17 +1,18 @@
use std::path::Path;
-use utils::fileutil as utils;
+use utils::fileutil;
+use utils::misc;
pub fn do_show(filenames: &mut Iterator<Item = String>, _args: &[String]) {
info!("do_show");
for line in filenames {
let parts: Vec<&str> = line.splitn(2, ' ').collect();
- let path = match utils::datetime_from_timestamp(parts[0]) {
+ let path = match misc::datetime_from_timestamp(parts[0]) {
Some(_) => Path::new(parts[1]),
None => Path::new(parts[0]),
};
- let output = utils::read_file_to_string(path).unwrap();
+ let output = fileutil::read_file_to_string(path).unwrap();
println!("{}", output);
}
}
diff --git a/src/utils/fileutil.rs b/src/utils/fileutil.rs
index add762b..dc84723 100644
--- a/src/utils/fileutil.rs
+++ b/src/utils/fileutil.rs
@@ -1,5 +1,4 @@
-use chrono::*;
-use std::fmt::Display;
+use super::misc;
use std::io::prelude::*;
use std::io::{BufRead, BufReader};
use std::path::{Path, PathBuf};
@@ -8,19 +7,6 @@ use std::fs::OpenOptions;
use icalwrap::IcalVCalendar;
-pub fn joinlines(first: &str, second: &str) -> String {
- use itertools::Itertools;
-
- let first = first.split(|x| x == '\n');
- let second = second.split(|x| x == '\n');
- let maxlen = first.clone().map(|x| x.len()).max().unwrap();
-
- first
- .zip(second)
- .map(|(fst, snd)| format!("{:width$} {}", fst, snd, width = maxlen))
- .join("\n")
-}
-
pub fn file_iter(dir: &Path) -> impl Iterator<Item = PathBuf> {
use walkdir::WalkDir;
@@ -109,7 +95,7 @@ pub fn read_calendars_from_files(files: &mut Iterator<Item = String>) -> Result<
pub fn read_khaleesi_line(kline: &str) -> Result<IcalVCalendar, String> {
let parts: Vec<&str> = kline.splitn(2, ' ').collect();
- if let Some(timestamp) = datetime_from_timestamp(parts[0]) {
+ if let Some(timestamp) = misc::datetime_from_timestamp(parts[0]) {
let path = Path::new(parts[1]);
let calendar = read_calendar_from_path(path)?;
let calendar = calendar.with_internal_timestamp(timestamp);
@@ -121,21 +107,6 @@ pub fn read_khaleesi_line(kline: &str) -> Result<IcalVCalendar, String> {
}
}
-pub fn datetime_from_timestamp(timestamp: &str) -> Option<DateTime<Utc>> {
- let timestamp_i64 = timestamp.parse::<i64>().ok()?;
- let naive_datetime = NaiveDateTime::from_timestamp_opt(timestamp_i64, 0)?;
- Some(DateTime::from_utc(naive_datetime, Utc))
-}
-
-pub fn format_duration(duration: &time::Duration) -> impl Display {
- //TODO replace this with duration.as_millis() when it becomes stable
- duration.as_secs() * 1000 + u64::from(duration.subsec_millis())
-}
-
-pub fn get_bucket_for_date(date: Date<Local>) -> String {
- date.format("%G-W%V").to_string()
-}
-
pub fn print_cals(cals: impl Iterator<Item = IcalVCalendar>) {
for cal in cals {
if let Some(line) = cal.get_principal_event().get_khaleesi_line() {
diff --git a/src/utils/misc.rs b/src/utils/misc.rs
new file mode 100644
index 0000000..a11b21e
--- /dev/null
+++ b/src/utils/misc.rs
@@ -0,0 +1,61 @@
+use chrono::*;
+use std::fmt::Display;
+use std::time;
+
+pub fn joinlines(first: &str, second: &str) -> String {
+ use itertools::Itertools;
+
+ let first = first.split(|x| x == '\n');
+ let second = second.split(|x| x == '\n');
+ let maxlen = first.clone().map(|x| x.len()).max().unwrap();
+
+ first
+ .zip(second)
+ .map(|(fst, snd)| format!("{:width$} {}", fst, snd, width = maxlen))
+ .join("\n")
+}
+
+pub fn datetime_from_timestamp(timestamp: &str) -> Option<DateTime<Utc>> {
+ let timestamp_i64 = timestamp.parse::<i64>().ok()?;
+ let naive_datetime = NaiveDateTime::from_timestamp_opt(timestamp_i64, 0)?;
+ Some(DateTime::from_utc(naive_datetime, Utc))
+}
+
+pub fn format_duration(duration: &time::Duration) -> impl Display {
+ //TODO replace this with duration.as_millis() when it becomes stable
+ duration.as_secs() * 1000 + u64::from(duration.subsec_millis())
+}
+
+pub fn get_bucket_for_date(date: Date<Local>) -> String {
+ date.format("%G-W%V").to_string()
+}
+
+pub fn make_new_uid() -> String {
+ use uuid::Uuid;
+
+ let suffix = "@khaleesi";
+ format!("{}{}", Uuid::new_v4().to_hyphenated_ref(), suffix)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn make_new_uid_test() {
+ let mut uid = make_new_uid();
+ assert_eq!(45, uid.len());
+ assert_eq!("@khaleesi".to_string(), uid.split_off(36));
+ }
+
+ #[test]
+ fn joinlines_test() {
+ let first = ["123", "ß", "1234"].join("\n");
+ let second = ["abc", "1", "Otto"].join("\n");
+ let expected = indoc!("
+ 123 abc
+ ß 1
+ 1234 Otto");
+ assert_eq!(expected, joinlines(first.as_str(), second.as_str()));
+ }
+}
diff --git a/src/utils/mod.rs b/src/utils/mod.rs
index b3e6fd7..113294c 100644
--- a/src/utils/mod.rs
+++ b/src/utils/mod.rs
@@ -2,6 +2,5 @@ pub mod calutil;
pub mod dateutil;
pub mod lock;
pub mod fileutil;
+pub mod misc;
-//pub use self::icalvcalendar::IcalVCalendar;
-//pub use self::calutil;