Lines
92 %
Functions
83.33 %
Branches
100 %
//! The per-user `timezone` config: the zone a user's report dates are read in.
use chrono::{DateTime, NaiveDate, Utc};
pub use chrono_tz::Tz;
use crate::config::{ConfigError, ConfigOption, config_on};
/// The config key holding an IANA zone name; unset means UTC.
pub const KEY: &str = "timezone";
/// The zone named `name`, or the reason it is unknown.
///
/// # Errors
/// A message naming the unknown zone.
pub fn parse_zone(name: &str) -> Result<Tz, String> {
name.parse::<Tz>()
.map_err(|_| format!("unknown timezone '{name}', expected an IANA name like Asia/Tokyo"))
}
/// Whether `field` is the timezone key, as the config table folds case.
#[must_use]
pub fn is_key(field: &str) -> bool {
field.trim().eq_ignore_ascii_case(KEY)
/// The user's zone on `conn`; UTC when unset.
/// [`ConfigError::Sqlx`] on a database error; [`ConfigError::InvalidTimezone`]
/// when the stored value is not a zone, naming it and the way to fix it.
pub async fn zone_on(conn: &mut sqlx::PgConnection) -> Result<Tz, ConfigError> {
match config_on(conn, KEY).await {
Ok(Some(ConfigOption::String(name))) => {
parse_zone(&name).map_err(|_| stored_invalid(&name))
Ok(Some(ConfigOption::Blob(_))) => Err(stored_invalid("<binary>")),
Ok(None) | Err(ConfigError::NoConfig(_)) => Ok(Tz::UTC),
Err(err) => Err(err),
fn stored_invalid(name: &str) -> ConfigError {
ConfigError::InvalidTimezone(format!(
"the stored timezone '{name}' is not an IANA zone name; fix it with (set-config \"{KEY}\" \"Asia/Tokyo\")"
))
/// The calendar day `now` falls on in `zone`.
pub fn local_day(now: DateTime<Utc>, zone: Tz) -> NaiveDate {
now.with_timezone(&zone).date_naive()
/// `at` as `YYYY-MM-DD HH:MM` on the clock of `zone`.
pub fn display(at: DateTime<Utc>, zone: Tz) -> String {
at.with_timezone(&zone).format("%Y-%m-%d %H:%M").to_string()
#[cfg(test)]
#[path = "timezone_tests.rs"]
mod tests;