Compare commits

..

No commits in common. "main" and "v0.0.3" have entirely different histories.
main ... v0.0.3

1 changed files with 293 additions and 394 deletions

View File

@ -1,12 +1,12 @@
use chrono::{Local, TimeZone, Timelike}; use serde::{Serialize, Deserialize};
use clap::Parser;
use regex::Regex;
use serde::{Deserialize, Serialize};
use serde_yaml::from_str;
use std::fs::File;
use std::io::{Read, Write}; use std::io::{Read, Write};
use std::fs::File;
use std::time::{SystemTime, UNIX_EPOCH, Duration};
use std::ops::{Add, Sub}; use std::ops::{Add, Sub};
use std::time::{Duration, SystemTime, UNIX_EPOCH}; use clap::Parser;
use chrono::{TimeZone, Local, Timelike};
use regex::Regex;
use serde_yaml::from_str;
#[derive(Debug, Parser)] #[derive(Debug, Parser)]
struct Flags { struct Flags {
@ -44,21 +44,9 @@ fn main() {
let duration = parse_duration(&flags.duration).unwrap(); let duration = parse_duration(&flags.duration).unwrap();
clock( clock(&flags.f, &(flags.clock || flags.duration.is_some()), &duration).unwrap();
&flags.f,
&(flags.clock || flags.duration.is_some()),
&duration,
)
.unwrap();
add(&flags.f, &flags.add, &flags.tag, &0).unwrap(); add(&flags.f, &flags.add, &flags.tag, &0).unwrap();
log( log(&flags.f, &flags.log, &flags.since, &flags.verbose, &flags.precision.unwrap_or(0)).unwrap();
&flags.f,
&flags.log,
&flags.since,
&flags.verbose,
&flags.precision.unwrap_or(0),
)
.unwrap();
} }
fn clock(f: &String, clock: &bool, duration: &u64) -> Result<(), String> { fn clock(f: &String, clock: &bool, duration: &u64) -> Result<(), String> {
@ -78,8 +66,8 @@ fn add(f: &String, x: &Option<String>, tag: &Option<String>, duration: &u64) ->
*duration, *duration,
); );
save(&f, tsheet)?; save(&f, tsheet)?;
} },
None => {} None => {},
}; };
Ok(()) Ok(())
} }
@ -96,44 +84,30 @@ struct LogX {
x: String, x: String,
} }
fn log( fn log(f: &String, enabled: &bool, since: &Option<String>, verbose: &bool, precision: &u32) -> Result<(), String> {
f: &String,
enabled: &bool,
since: &Option<String>,
verbose: &bool,
precision: &u32,
) -> Result<(), String> {
if !enabled { if !enabled {
return Ok(()); return Ok(());
} }
let since = parse_time(since)?; let since = parse_time(since)?;
if *verbose { if *verbose {
eprintln!( eprintln!("since = {} ({})", system_time_to_unix_seconds(&since), timestamp(&system_time_to_unix_seconds(&since)));
"since = {} ({})",
system_time_to_unix_seconds(&since),
timestamp(&system_time_to_unix_seconds(&since), &2)
);
} }
let tsheet = load(&f)?; let tsheet = load(&f)?;
let tsheet = tsheet.since(since); let tsheet = tsheet.since(since);
let tsheet = tsheet.sorted();
if *verbose { if *verbose {
eprintln!("tsheet = {:?}", &tsheet); eprintln!("tsheet = {:?}", &tsheet);
} }
let mut result = vec![]; let mut result = vec![];
let mut curr = Log { let mut curr = Log{t: "".to_string(), d: 0.0, xs: vec![]};
t: "".to_string(),
d: 0.0,
xs: vec![],
};
let mut currt = "".to_string();
for i in 0..tsheet.xs.len() { for i in 0..tsheet.xs.len() {
let x = &tsheet.xs[i]; let x = &tsheet.xs[i];
if *verbose { if *verbose {
eprintln!("{} != {}?", &curr.t, x.timestamp(&precision)); eprintln!("{} != {}?", &curr.t, x.timestamp());
} }
if currt != x.timestamp(&0) { if curr.t != x.timestamp() {
if curr.xs.len() > 0 { if curr.xs.len() > 0 {
if *verbose { if *verbose {
eprintln!("push {:?}", &curr.xs); eprintln!("push {:?}", &curr.xs);
@ -141,31 +115,24 @@ fn log(
result.push(curr.clone()); result.push(curr.clone());
} }
curr.xs.truncate(0); curr.xs.truncate(0);
curr.t = x.timestamp(&precision); curr.t = x.timestamp();
currt = x.timestamp(&0);
curr.d = 0.0; curr.d = 0.0;
} }
let mut d = 1.0; let mut d = 1.0;
if x.x.len() == 0 { if x.x.len() == 0 {
// clock ins get duration zero
d = 0.0; d = 0.0;
} else if i > 0 && tsheet.xs[i].timestamp(&0) == tsheet.xs[i - 1].timestamp(&0) { } else if i > 0 {
// if same day as previous then use elapsed as duration
d = ((tsheet.xs[i].t - tsheet.xs[i-1].t) as f32 / (60.0*60.0)) as f32; d = ((tsheet.xs[i].t - tsheet.xs[i-1].t) as f32 / (60.0*60.0)) as f32;
} }
if *verbose { if *verbose {
eprintln!("d={} x='{}'", &x.x, &d); eprintln!("d={} x='{}'", &x.x, &d);
} }
match x.x.len() { match x.x.len() {
0 => {} 0 => {},
_ => { _ => {
curr.t = x.timestamp(&precision); curr.t = x.timestamp();
currt = x.timestamp(&0); curr.xs.push(LogX{d: d, x: x.x.clone()});
curr.xs.push(LogX { },
d: d,
x: x.x.clone(),
});
}
}; };
} }
if curr.xs.len() > 0 { if curr.xs.len() > 0 {
@ -174,21 +141,15 @@ fn log(
} }
result.push(curr.clone()); result.push(curr.clone());
} }
let mut total_d = 0.0;
for i in result.iter_mut() { for i in result.iter_mut() {
i.d = i.xs.iter().map(|x| x.d).sum(); i.d = i.xs.iter().map(|x| x.d).sum();
total_d += i.d;
if *verbose { if *verbose {
eprintln!( eprintln!("{} = {:?}", &i.d, &i.xs.iter().map(|x| x.d).collect::<Vec<_>>());
"{} = {:?}",
&i.d,
&i.xs.iter().map(|x| x.d).collect::<Vec<_>>()
);
} }
} }
for log in &result { for log in result {
for x in log.xs.clone() { for x in log.xs {
if x.x.len() > 0 { if x.x.len() > 0 {
match precision { match precision {
0 => println!("{} ({:.0}) {} ({:.1})", log.t, log.d, x.x, x.d), 0 => println!("{} ({:.0}) {} ({:.1})", log.t, log.d, x.x, x.d),
@ -198,30 +159,6 @@ fn log(
} }
} }
} }
if result.len() > 1 {
match precision {
0 => eprintln!(
"({:.0}h of {}h over {} dates)",
total_d,
8 * result.len(),
result.len()
),
1 => eprintln!(
"({:.1}h of {}h over {} dates)",
total_d,
8 * result.len(),
result.len()
),
_ => eprintln!(
"({:.2}h of {}h over {} dates)",
total_d,
8 * result.len(),
result.len()
),
}
}
Ok(()) Ok(())
} }
@ -246,8 +183,7 @@ fn parse_duration(d: &Option<String>) -> Result<u64, String> {
match d { match d {
Some(d) => { Some(d) => {
let mut sum: u64 = 0; let mut sum: u64 = 0;
let re = Regex::new(r"^(?<hours>[0-9]+h)?(?<minutes>[0-9]+m)?(?<seconds>[0-9]+s)?$") let re = Regex::new(r"^(?<hours>[0-9]+h)?(?<minutes>[0-9]+m)?(?<seconds>[0-9]+s)?$").unwrap();
.unwrap();
match re.captures(d) { match re.captures(d) {
Some(captures) => { Some(captures) => {
match captures.name("seconds") { match captures.name("seconds") {
@ -255,47 +191,49 @@ fn parse_duration(d: &Option<String>) -> Result<u64, String> {
let n = n.as_str().to_string(); let n = n.as_str().to_string();
let n = n.trim_end_matches('s'); let n = n.trim_end_matches('s');
sum += from_str::<u64>(n).unwrap(); sum += from_str::<u64>(n).unwrap();
} },
None => {} None => {},
}; };
match captures.name("minutes") { match captures.name("minutes") {
Some(n) => { Some(n) => {
let n = n.as_str().to_string(); let n = n.as_str().to_string();
let n = n.trim_end_matches('m'); let n = n.trim_end_matches('m');
sum += 60 * from_str::<u64>(n).unwrap(); sum += 60 * from_str::<u64>(n).unwrap();
} },
None => {} None => {},
}; };
match captures.name("hours") { match captures.name("hours") {
Some(n) => { Some(n) => {
let n = n.as_str().to_string(); let n = n.as_str().to_string();
let n = n.trim_end_matches('h'); let n = n.trim_end_matches('h');
sum += 60 * 60 * from_str::<u64>(n).unwrap(); sum += 60 * 60 * from_str::<u64>(n).unwrap();
} },
None => {} None => {},
}; };
Ok(sum) Ok(sum)
} },
None => Ok(0), None => Ok(0),
} }
} },
None => Ok(0), None => Ok(0),
} }
} }
fn parse_time(since: &Option<String>) -> Result<SystemTime, String> { fn parse_time(since: &Option<String>) -> Result<SystemTime, String> {
match since { match since {
Some(since) => match chrono::NaiveDate::parse_from_str(since, "%Y-%m-%d") { Some(since) => {
match chrono::NaiveDate::parse_from_str(since, "%Y-%m-%d") {
Ok(nd) => { Ok(nd) => {
let ndt = nd.and_hms_opt(1, 1, 1).unwrap(); let ndt = nd.and_hms_opt(1, 1, 1).unwrap();
let dt = Local.from_local_datetime(&ndt).unwrap(); let dt = Local.from_local_datetime(&ndt).unwrap();
Ok(UNIX_EPOCH.add(Duration::from_secs(dt.timestamp() as u64))) Ok(UNIX_EPOCH.add(
} Duration::from_secs(dt.timestamp() as u64)
Err(msg) => Err(format!("failed to parse {}: {}", since, msg)), ))
}, },
None => { Err(msg) => Err(format!("failed to parse {}: {}", since, msg)),
Ok(SystemTime::now().sub(Duration::from_secs(Local::now().hour() as u64 * 60 * 60)))
} }
},
None => Ok(SystemTime::now().sub(Duration::from_secs(Local::now().hour() as u64*60*60))),
} }
} }
@ -314,10 +252,7 @@ struct X {
fn save(path: &String, tsheet: TSheet) -> Result<(), String> { fn save(path: &String, tsheet: TSheet) -> Result<(), String> {
match File::create(path.clone()) { match File::create(path.clone()) {
Ok(mut writer) => _save(&mut writer, tsheet), Ok(mut writer) => _save(&mut writer, tsheet),
Err(reason) => Err(format!( Err(reason) => Err(format!("failed to open {} to save tsheet: {}", path, reason)),
"failed to open {} to save tsheet: {}",
path, reason
)),
} }
} }
@ -359,20 +294,10 @@ mod test_save_load {
#[test] #[test]
fn test_testdata_standalone_yaml() { fn test_testdata_standalone_yaml() {
let want = TSheet { let want = TSheet{xs: vec![
xs: vec![ X{t: 1, x: "def".to_string(), tag: "abc".to_string()},
X { X{t: 2, x: "ghi".to_string(), tag: "".to_string()},
t: 1, ]};
x: "def".to_string(),
tag: "abc".to_string(),
},
X {
t: 2,
x: "ghi".to_string(),
tag: "".to_string(),
},
],
};
assert_eq!( assert_eq!(
load(&"./src/testdata/standalone.yaml".to_string()).expect("cant load standalone.yaml"), load(&"./src/testdata/standalone.yaml".to_string()).expect("cant load standalone.yaml"),
want, want,
@ -380,18 +305,14 @@ mod test_save_load {
let mut w = vec![]; let mut w = vec![];
_save(&mut w, want).expect("failed saving tsheet to writer"); _save(&mut w, want).expect("failed saving tsheet to writer");
assert_eq!( assert_eq!(String::from_utf8(w).unwrap(), "xs:\n- t: 1\n x: def\n tag: abc\n- t: 2\n x: ghi\n tag: ''\n".to_string());
String::from_utf8(w).unwrap(),
"xs:\n- t: 1\n x: def\n tag: abc\n- t: 2\n x: ghi\n tag: ''\n".to_string()
);
} }
} }
impl TSheet { impl TSheet {
fn since(&self, t: SystemTime) -> TSheet { fn since(&self, t: SystemTime) -> TSheet {
let mut result = TSheet{xs: vec![]}; let mut result = TSheet{xs: vec![]};
self.xs self.xs.iter()
.iter()
.filter(|x| x.ts() >= t) .filter(|x| x.ts() >= t)
.for_each(|x| result.xs.push(x.clone())); .for_each(|x| result.xs.push(x.clone()));
result result
@ -399,7 +320,17 @@ impl TSheet {
fn add(&mut self, x: String, tag: String, duration: u64) { fn add(&mut self, x: String, tag: String, duration: u64) {
let now = system_time_to_unix_seconds(&SystemTime::now()); let now = system_time_to_unix_seconds(&SystemTime::now());
self.xs.push(new_x(now - duration as i64, x, tag)); self.xs.push(new_x(
now - duration as i64,
x,
tag,
));
}
fn sorted(&self) -> TSheet {
let mut result = TSheet{xs: self.xs.clone()};
result.xs.sort();
return result;
} }
} }
@ -408,8 +339,8 @@ impl X {
UNIX_EPOCH.add(Duration::from_secs(self.t.try_into().unwrap())) UNIX_EPOCH.add(Duration::from_secs(self.t.try_into().unwrap()))
} }
fn timestamp(&self, precision: &u32) -> String { fn timestamp(&self) -> String {
timestamp(&self.t, &precision) timestamp(&self.t)
} }
} }
@ -417,13 +348,9 @@ fn system_time_to_unix_seconds(st: &SystemTime) -> i64 {
st.duration_since(UNIX_EPOCH).unwrap().as_secs() as i64 st.duration_since(UNIX_EPOCH).unwrap().as_secs() as i64
} }
fn timestamp(t: &i64, precision: &u32) -> String { fn timestamp(t: &i64) -> String {
let dt = Local.timestamp_opt(*t, 0).unwrap(); let dt = Local.timestamp_opt(*t, 0).unwrap();
match precision { dt.format("%Y-%m-%d").to_string()
0 => dt.format("%Y-%m-%d").to_string(),
1 => dt.format("%Y-%m-%dT%H:%M").to_string(),
_ => dt.format("%Y-%m-%dT%H:%M:%S").to_string(),
}
} }
fn new_x(t: i64, x: String, tag: String) -> X { fn new_x(t: i64, x: String, tag: String) -> X {
@ -440,13 +367,9 @@ mod test_tsheet {
#[test] #[test]
fn test_add() { fn test_add() {
let mut given = TSheet { let mut given = TSheet{xs: vec![
xs: vec![X { X{t: 1, x: "def".to_string(), tag: "abc".to_string()},
t: 1, ]};
x: "def".to_string(),
tag: "abc".to_string(),
}],
};
given.add("ghi".to_string(), "".to_string(), 0); given.add("ghi".to_string(), "".to_string(), 0);
assert_eq!(given.xs.len(), 2); assert_eq!(given.xs.len(), 2);
assert!(given.xs[1].t != 1); assert!(given.xs[1].t != 1);
@ -456,39 +379,15 @@ mod test_tsheet {
#[test] #[test]
fn test_since_date() { fn test_since_date() {
let given = TSheet { let given = TSheet{xs: vec![
xs: vec![ X{t: 1, x: "def".to_string(), tag: "abc".to_string()},
X { X{t: 2, x: "ghi".to_string(), tag: "".to_string()},
t: 1, X{t: 3, x: "jkl".to_string(), tag: "".to_string()},
x: "def".to_string(), ]};
tag: "abc".to_string(), let want = TSheet{xs: vec![
}, X{t: 2, x: "ghi".to_string(), tag: "".to_string()},
X { X{t: 3, x: "jkl".to_string(), tag: "".to_string()},
t: 2, ]};
x: "ghi".to_string(),
tag: "".to_string(),
},
X {
t: 3,
x: "jkl".to_string(),
tag: "".to_string(),
},
],
};
let want = TSheet {
xs: vec![
X {
t: 2,
x: "ghi".to_string(),
tag: "".to_string(),
},
X {
t: 3,
x: "jkl".to_string(),
tag: "".to_string(),
},
],
};
let got = given.since(UNIX_EPOCH.add(Duration::from_secs(2))); let got = given.since(UNIX_EPOCH.add(Duration::from_secs(2)));
assert_eq!(got, want); assert_eq!(got, want);
} }