Compare commits

...

10 Commits
v0.0.2 ... main

Author SHA1 Message Date
Bel LaPointe 087fa739ce since multi day prints expected 2025-09-11 22:40:20 -06:00
Bel LaPointe 64e30da785 NOW bug fixed 2024-12-04 16:17:26 -07:00
Bel LaPointe a39187a417 maybe fix a bug 2024-12-04 16:06:51 -07:00
Bel LaPointe caefbdbdd6 only eprint if more than 1 day 2024-11-25 10:32:05 -07:00
Bel LaPointe 24621725ca eprint hours sum 2024-11-25 10:27:14 -07:00
Bel LaPointe 181cfc1454 allow imaginary times because f u customer right 2024-11-06 15:36:53 -07:00
Bel LaPointe d9f84022a0 though timestamps may include hours, always sum by day 2024-08-27 08:21:43 -06:00
Bel LaPointe f9f3fa5212 precision also affects displaying timestamp on log 2024-08-26 11:29:17 -06:00
Bel LaPointe 5e832956db impl -d 1h2m3s to modify duration of an add 2024-04-08 21:29:13 -06:00
Bel LaPointe ad22e13ca3 parse_duration unused but impl 2024-04-08 20:53:23 -06:00
3 changed files with 454 additions and 237 deletions

45
Cargo.lock generated
View File

@ -2,6 +2,15 @@
# It is not intended for manual editing. # It is not intended for manual editing.
version = 3 version = 3
[[package]]
name = "aho-corasick"
version = "1.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e60d3430d3a69478ad0993f19238d2df97c507009a52b3c10addcd7f6bcb916"
dependencies = [
"memchr",
]
[[package]] [[package]]
name = "android-tzdata" name = "android-tzdata"
version = "0.1.1" version = "0.1.1"
@ -236,6 +245,12 @@ version = "0.4.20"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b5e6163cb8c49088c2c36f57875e58ccd8c87c7427f7fbd50ea6710b2f3f2e8f" checksum = "b5e6163cb8c49088c2c36f57875e58ccd8c87c7427f7fbd50ea6710b2f3f2e8f"
[[package]]
name = "memchr"
version = "2.7.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6c8640c5d730cb13ebd907d8d04b52f55ac9a2eec55b440c8892f40d56c76c1d"
[[package]] [[package]]
name = "num-traits" name = "num-traits"
version = "0.2.17" version = "0.2.17"
@ -269,6 +284,35 @@ dependencies = [
"proc-macro2", "proc-macro2",
] ]
[[package]]
name = "regex"
version = "1.10.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c117dbdfde9c8308975b6a18d71f3f385c89461f7b3fb054288ecf2a2058ba4c"
dependencies = [
"aho-corasick",
"memchr",
"regex-automata",
"regex-syntax",
]
[[package]]
name = "regex-automata"
version = "0.4.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "86b83b8b9847f9bf95ef68afb0b8e6cdb80f498442f5179a29fad448fcc1eaea"
dependencies = [
"aho-corasick",
"memchr",
"regex-syntax",
]
[[package]]
name = "regex-syntax"
version = "0.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "adad44e29e4c806119491a7f06f03de4d1af22c3a680dd47f1e6e179439d1f56"
[[package]] [[package]]
name = "ryu" name = "ryu"
version = "1.0.15" version = "1.0.15"
@ -331,6 +375,7 @@ version = "0.1.0"
dependencies = [ dependencies = [
"chrono", "chrono",
"clap", "clap",
"regex",
"serde", "serde",
"serde_yaml", "serde_yaml",
] ]

View File

@ -8,5 +8,6 @@ edition = "2021"
[dependencies] [dependencies]
chrono = "0.4.31" chrono = "0.4.31"
clap = { version = "4.4.8", features = ["derive"] } clap = { version = "4.4.8", features = ["derive"] }
regex = "1.10.4"
serde = { version = "1.0.193", features = ["derive"] } serde = { version = "1.0.193", features = ["derive"] }
serde_yaml = "0.9.27" serde_yaml = "0.9.27"

View File

@ -1,10 +1,12 @@
use serde::{Serialize, Deserialize}; use chrono::{Local, TimeZone, Timelike};
use std::io::{Read, Write};
use std::fs::File;
use std::time::{SystemTime, UNIX_EPOCH, Duration};
use std::ops::{Add, Sub};
use clap::Parser; use clap::Parser;
use chrono::{TimeZone, Local, Timelike}; use regex::Regex;
use serde::{Deserialize, Serialize};
use serde_yaml::from_str;
use std::fs::File;
use std::io::{Read, Write};
use std::ops::{Add, Sub};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
#[derive(Debug, Parser)] #[derive(Debug, Parser)]
struct Flags { struct Flags {
@ -26,6 +28,9 @@ struct Flags {
#[arg(short = 'c', long = "clock")] #[arg(short = 'c', long = "clock")]
clock: bool, clock: bool,
#[arg(short = 'd', long = "duration")]
duration: Option<String>,
#[arg(short = 'v', long = "verbose")] #[arg(short = 'v', long = "verbose")]
verbose: bool, verbose: bool,
@ -37,29 +42,44 @@ fn main() {
let mut flags = Flags::parse(); let mut flags = Flags::parse();
flags.log = flags.log || flags.since.is_some(); flags.log = flags.log || flags.since.is_some();
clock(&flags.f, &flags.clock).unwrap(); let duration = parse_duration(&flags.duration).unwrap();
add(&flags.f, &flags.add, &flags.tag).unwrap();
log(&flags.f, &flags.log, &flags.since, &flags.verbose, &flags.precision.unwrap_or(0)).unwrap(); clock(
&flags.f,
&(flags.clock || flags.duration.is_some()),
&duration,
)
.unwrap();
add(&flags.f, &flags.add, &flags.tag, &0).unwrap();
log(
&flags.f,
&flags.log,
&flags.since,
&flags.verbose,
&flags.precision.unwrap_or(0),
)
.unwrap();
} }
fn clock(f: &String, clock: &bool) -> Result<(), String> { fn clock(f: &String, clock: &bool, duration: &u64) -> Result<(), String> {
match clock { match clock {
true => add(&f, &Some("".to_string()), &None), true => add(&f, &Some("".to_string()), &None, duration),
false => Ok(()), false => Ok(()),
} }
} }
fn add(f: &String, x: &Option<String>, tag: &Option<String>) -> Result<(), String> { fn add(f: &String, x: &Option<String>, tag: &Option<String>, duration: &u64) -> Result<(), String> {
match x { match x {
Some(x) => { Some(x) => {
let mut tsheet = load(&f)?; let mut tsheet = load(&f)?;
tsheet.add( tsheet.add(
x.to_string(), x.to_string(),
tag.clone().unwrap_or("".to_string()), tag.clone().unwrap_or("".to_string()),
*duration,
); );
save(&f, tsheet)?; save(&f, tsheet)?;
}, }
None => {}, None => {}
}; };
Ok(()) Ok(())
} }
@ -76,30 +96,44 @@ struct LogX {
x: String, x: String,
} }
fn log(f: &String, enabled: &bool, since: &Option<String>, verbose: &bool, precision: &u32) -> Result<(), String> { fn log(
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!("since = {} ({})", system_time_to_unix_seconds(&since), timestamp(&system_time_to_unix_seconds(&since))); eprintln!(
"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{t: "".to_string(), d: 0.0, xs: vec![]}; let mut curr = Log {
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()); eprintln!("{} != {}?", &curr.t, x.timestamp(&precision));
} }
if curr.t != x.timestamp() { if currt != x.timestamp(&0) {
if curr.xs.len() > 0 { if curr.xs.len() > 0 {
if *verbose { if *verbose {
eprintln!("push {:?}", &curr.xs); eprintln!("push {:?}", &curr.xs);
@ -107,24 +141,31 @@ fn log(f: &String, enabled: &bool, since: &Option<String>, verbose: &bool, preci
result.push(curr.clone()); result.push(curr.clone());
} }
curr.xs.truncate(0); curr.xs.truncate(0);
curr.t = x.timestamp(); curr.t = x.timestamp(&precision);
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 { } else if i > 0 && tsheet.xs[i].timestamp(&0) == tsheet.xs[i - 1].timestamp(&0) {
d = ((tsheet.xs[i].t - tsheet.xs[i-1].t) as f32 / (60.0*60.0)) as f32; // 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;
} }
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(); curr.t = x.timestamp(&precision);
curr.xs.push(LogX{d: d, x: x.x.clone()}); currt = x.timestamp(&0);
}, curr.xs.push(LogX {
d: d,
x: x.x.clone(),
});
}
}; };
} }
if curr.xs.len() > 0 { if curr.xs.len() > 0 {
@ -133,15 +174,21 @@ fn log(f: &String, enabled: &bool, since: &Option<String>, verbose: &bool, preci
} }
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!("{} = {:?}", &i.d, &i.xs.iter().map(|x| x.d).collect::<Vec<_>>()); eprintln!(
"{} = {:?}",
&i.d,
&i.xs.iter().map(|x| x.d).collect::<Vec<_>>()
);
} }
} }
for log in result { for log in &result {
for x in log.xs { for x in log.xs.clone() {
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),
@ -151,24 +198,104 @@ fn log(f: &String, enabled: &bool, since: &Option<String>, verbose: &bool, preci
} }
} }
} }
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(())
} }
#[cfg(test)]
mod test_parse {
use super::*;
#[test]
fn test_duration() {
assert_eq!(0, parse_duration(&None).unwrap());
assert_eq!(1, parse_duration(&Some("1s".to_string())).unwrap());
assert_eq!(33, parse_duration(&Some("33s".to_string())).unwrap());
assert_eq!(666, parse_duration(&Some("666s".to_string())).unwrap());
assert_eq!(60, parse_duration(&Some("1m".to_string())).unwrap());
assert_eq!(62, parse_duration(&Some("1m2s".to_string())).unwrap());
assert_eq!(3600, parse_duration(&Some("1h".to_string())).unwrap());
assert_eq!(3723, parse_duration(&Some("1h2m3s".to_string())).unwrap());
}
}
fn parse_duration(d: &Option<String>) -> Result<u64, String> {
match d {
Some(d) => {
let mut sum: u64 = 0;
let re = Regex::new(r"^(?<hours>[0-9]+h)?(?<minutes>[0-9]+m)?(?<seconds>[0-9]+s)?$")
.unwrap();
match re.captures(d) {
Some(captures) => {
match captures.name("seconds") {
Some(n) => {
let n = n.as_str().to_string();
let n = n.trim_end_matches('s');
sum += from_str::<u64>(n).unwrap();
}
None => {}
};
match captures.name("minutes") {
Some(n) => {
let n = n.as_str().to_string();
let n = n.trim_end_matches('m');
sum += 60 * from_str::<u64>(n).unwrap();
}
None => {}
};
match captures.name("hours") {
Some(n) => {
let n = n.as_str().to_string();
let n = n.trim_end_matches('h');
sum += 60 * 60 * from_str::<u64>(n).unwrap();
}
None => {}
};
Ok(sum)
}
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) => { Some(since) => match chrono::NaiveDate::parse_from_str(since, "%Y-%m-%d") {
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( Ok(UNIX_EPOCH.add(Duration::from_secs(dt.timestamp() as u64)))
Duration::from_secs(dt.timestamp() as u64)
))
},
Err(msg) => Err(format!("failed to parse {}: {}", since, msg)),
} }
Err(msg) => Err(format!("failed to parse {}: {}", since, msg)),
}, },
None => 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)))
}
} }
} }
@ -187,7 +314,10 @@ 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!("failed to open {} to save tsheet: {}", path, reason)), Err(reason) => Err(format!(
"failed to open {} to save tsheet: {}",
path, reason
)),
} }
} }
@ -220,7 +350,7 @@ mod test_save_load {
#[test] #[test]
fn test_empty() { fn test_empty() {
let got = _load(&mut "xs: []".as_bytes()).expect("failed to parse 'xs: []' tsheet"); let got = _load(&mut "xs: []".as_bytes()).expect("failed to parse 'xs: []' tsheet");
assert_eq!(got, TSheet{xs: vec![]}); assert_eq!(got, TSheet { xs: vec![] });
let mut w = vec![]; let mut w = vec![];
_save(&mut w, got).expect("failed saving tsheet to writer"); _save(&mut w, got).expect("failed saving tsheet to writer");
@ -229,10 +359,20 @@ mod test_save_load {
#[test] #[test]
fn test_testdata_standalone_yaml() { fn test_testdata_standalone_yaml() {
let want = TSheet{xs: vec![ let want = TSheet {
X{t: 1, x: "def".to_string(), tag: "abc".to_string()}, xs: vec![
X{t: 2, x: "ghi".to_string(), tag: "".to_string()}, X {
]}; 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,
@ -240,27 +380,26 @@ 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!(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()); 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()
);
} }
} }
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.iter() self.xs
.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
} }
fn add(&mut self, x: String, tag: String) { fn add(&mut self, x: String, tag: String, duration: u64) {
self.xs.push(new_x(SystemTime::now(), x, tag)); let now = system_time_to_unix_seconds(&SystemTime::now());
} 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;
} }
} }
@ -269,8 +408,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) -> String { fn timestamp(&self, precision: &u32) -> String {
timestamp(&self.t) timestamp(&self.t, &precision)
} }
} }
@ -278,14 +417,18 @@ 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) -> String { fn timestamp(t: &i64, precision: &u32) -> String {
let dt = Local.timestamp_opt(*t, 0).unwrap(); let dt = Local.timestamp_opt(*t, 0).unwrap();
dt.format("%Y-%m-%d").to_string() match precision {
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: SystemTime, x: String, tag: String) -> X { fn new_x(t: i64, x: String, tag: String) -> X {
X{ X {
t: system_time_to_unix_seconds(&t), t: t,
x: x, x: x,
tag: tag, tag: tag,
} }
@ -297,10 +440,14 @@ mod test_tsheet {
#[test] #[test]
fn test_add() { fn test_add() {
let mut given = TSheet{xs: vec![ let mut given = TSheet {
X{t: 1, x: "def".to_string(), tag: "abc".to_string()}, xs: vec![X {
]}; t: 1,
given.add("ghi".to_string(), "".to_string()); x: "def".to_string(),
tag: "abc".to_string(),
}],
};
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);
assert_eq!(given.xs[1].x, "ghi".to_string()); assert_eq!(given.xs[1].x, "ghi".to_string());
@ -309,15 +456,39 @@ mod test_tsheet {
#[test] #[test]
fn test_since_date() { fn test_since_date() {
let given = TSheet{xs: vec![ let given = TSheet {
X{t: 1, x: "def".to_string(), tag: "abc".to_string()}, xs: vec![
X{t: 2, x: "ghi".to_string(), tag: "".to_string()}, X {
X{t: 3, x: "jkl".to_string(), tag: "".to_string()}, t: 1,
]}; x: "def".to_string(),
let want = TSheet{xs: vec![ tag: "abc".to_string(),
X{t: 2, x: "ghi".to_string(), tag: "".to_string()}, },
X{t: 3, x: "jkl".to_string(), tag: "".to_string()}, X {
]}; 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);
} }