Skip to content

Commit

Permalink
Merge pull request #16 from simonwiles/timezone-selection
Browse files Browse the repository at this point in the history
Timezone Selection
  • Loading branch information
samwho committed Sep 18, 2023
2 parents 9291389 + c9c7dc6 commit 7870c1f
Show file tree
Hide file tree
Showing 3 changed files with 193 additions and 10 deletions.
116 changes: 110 additions & 6 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ log = "0.4"
env_logger = "0.10"
human-panic = "1.0"
chrono = "0.4.30"
chrono-tz = "0.8.3"

[dev-dependencies]
regex = "1.9.5"
test-case = "3"
85 changes: 81 additions & 4 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use anyhow::{Context, Result};
use chrono::Local;
use chrono::{DateTime, Local};
use chrono_tz::Tz;
use clap::Parser;
use log::debug;
use owo_colors::{self, OwoColorize, Stream};
Expand Down Expand Up @@ -38,6 +39,10 @@ struct Args {
/// Put the timestamp on the right side of the spacer.
#[arg(long, default_value = "false")]
right: bool,

/// Print timestamp in an arbitrary timezone (in IANA format, e.g. Europe/London).
#[arg(long)]
timezone: Option<String>,
}

struct TestStats {
Expand Down Expand Up @@ -87,8 +92,35 @@ fn print_spacer(mut output: impl Write, args: &Args, last_spacer: &Instant) -> R
writeln!(output, "{}", "\n".repeat(args.padding - 1))?;
}

let now = Local::now();
let date_str = now.format("%Y-%m-%d").to_string();
let datetime_strings = match args.timezone.clone() {
None => {
let now: DateTime<Local> = Local::now();
(
now.format("%Y-%m-%d").to_string(),
now.format("%H:%M:%S").to_string(),
)
}
Some(timezone_str) => match timezone_str.parse::<Tz>() {
Ok(timezone) => {
let now: DateTime<Tz> = Local::now().with_timezone(&timezone);
(
now.format("%Y-%m-%d").to_string(),
now.format("%H:%M:%S %Z").to_string(),
)
}
Err(err) => {
eprintln!("Error: {}", err);
debug!("could not parse supplied timezone name, using local time");
let now: DateTime<Local> = Local::now();
(
now.format("%Y-%m-%d").to_string(),
now.format("%H:%M:%S").to_string(),
)
}
},
};

let date_str = datetime_strings.0;
let mut buf = Vec::new();
write!(
buf,
Expand All @@ -97,7 +129,7 @@ fn print_spacer(mut output: impl Write, args: &Args, last_spacer: &Instant) -> R
)?;
dashes -= date_str.len() + 1;

let time_str = now.format("%H:%M:%S").to_string();
let time_str = datetime_strings.1;
write!(
buf,
"{} ",
Expand Down Expand Up @@ -281,6 +313,7 @@ mod tests {
use self::Op::*;
use self::Out::*;
use super::*;
use regex::Regex;
use std::io::{BufReader, Read};
use std::thread::sleep;
use std::time::Duration;
Expand All @@ -296,6 +329,8 @@ mod tests {
Line(&'static str),
Spacer,
RightSpacer,
SpacerWithLondonTimezone,
RightSpacerWithLondonTimezone,
}

struct TimedInput {
Expand Down Expand Up @@ -346,6 +381,7 @@ mod tests {
no_color: true,
force_color: false,
right: false,
timezone: None,
}
}

Expand Down Expand Up @@ -385,6 +421,7 @@ mod tests {
no_color: true,
force_color: false,
right: true,
timezone: None,
}
; "single line, right spacer"
)]
Expand All @@ -398,6 +435,7 @@ mod tests {
no_color: true,
force_color: false,
right: false,
timezone: None,
}
; "padding = 1"
)]
Expand All @@ -411,9 +449,38 @@ mod tests {
no_color: true,
force_color: false,
right: false,
timezone: None,
}
; "padding = 2"
)]
#[test_case(
vec![WriteLn("foo"), Sleep(300)],
vec![Line("foo"), SpacerWithLondonTimezone],
Args {
after: 0.1,
dash: '-',
padding: 0,
no_color: true,
force_color: false,
right: false,
timezone: Some("Europe/London".to_string()),
}
; "with timezone"
)]
#[test_case(
vec![WriteLn("foo"), Sleep(300)],
vec![Line("foo"), RightSpacerWithLondonTimezone],
Args {
after: 0.1,
dash: '-',
padding: 0,
no_color: true,
force_color: false,
right: true,
timezone: Some("Europe/London".to_string()),
}
; "right spacer with timezone"
)]
fn test_output(ops: Vec<Op>, out: Vec<Out>, args: Args) -> Result<()> {
let mut total_sleep_ms = 0;
for op in ops.iter() {
Expand Down Expand Up @@ -444,6 +511,16 @@ mod tests {
Line(expected) => assert_eq!(line, expected),
Spacer => assert!(line.ends_with("----")),
RightSpacer => assert!(line.starts_with("----")),
SpacerWithLondonTimezone => {
let re = Regex::new(r"GMT|BST").unwrap();
assert!(re.is_match(line));
assert!(line.ends_with("----"));
}
RightSpacerWithLondonTimezone => {
let re = Regex::new(r"GMT|BST").unwrap();
assert!(re.is_match(line));
assert!(line.starts_with("----"));
}
}
}

Expand Down

0 comments on commit 7870c1f

Please sign in to comment.