Replace chrono dependency by time

This commit is contained in:
Joscha 2022-07-24 17:12:22 +02:00
parent 4e014168b4
commit 8bc7af0d3f
11 changed files with 76 additions and 76 deletions

View file

@ -8,9 +8,9 @@
use std::fmt;
use chrono::{DateTime, TimeZone, Utc};
use serde::{de, ser, Deserialize, Serialize};
use serde_json::Value;
use time::OffsetDateTime;
/// Describes an account and its preferred name.
#[derive(Debug, Clone, Serialize, Deserialize)]
@ -331,15 +331,11 @@ impl<'de> Deserialize<'de> for Snowflake {
/// Time is specified as a signed 64-bit integer, giving the number of seconds
/// since the Unix Epoch.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct Time(#[serde(with = "chrono::serde::ts_seconds")] pub DateTime<Utc>);
pub struct Time(#[serde(with = "time::serde::timestamp")] pub OffsetDateTime);
impl Time {
pub fn new(timestamp: i64) -> Self {
Self(Utc.timestamp(timestamp, 0))
}
pub fn now() -> Self {
Self::new(Utc::now().timestamp())
Self(OffsetDateTime::now_utc().replace_millisecond(0).unwrap())
}
}

View file

@ -3,11 +3,11 @@ use std::sync::Arc;
use std::time::Duration;
use anyhow::bail;
use chrono::Utc;
use log::{error, info, warn};
use parking_lot::Mutex;
use time::OffsetDateTime;
use tokio::sync::{mpsc, oneshot};
use tokio::{select, task, time};
use tokio::{select, task};
use tokio_tungstenite::tungstenite;
use crate::ui::UiEvent;
@ -82,7 +82,7 @@ impl State {
} else {
info!("e&{}: could not connect", name);
}
time::sleep(Duration::from_secs(5)).await; // TODO Make configurable
tokio::time::sleep(Duration::from_secs(5)).await; // TODO Make configurable
}
}
@ -103,7 +103,7 @@ impl State {
async fn regularly_request_logs(event_tx: &mpsc::UnboundedSender<Event>) {
loop {
time::sleep(Duration::from_secs(2)).await; // TODO Make configurable
tokio::time::sleep(Duration::from_secs(2)).await; // TODO Make configurable
let _ = event_tx.send(Event::RequestLogs);
}
}
@ -171,7 +171,7 @@ impl State {
}
Data::SnapshotEvent(d) => {
info!("e&{}: successfully joined", self.name);
self.vault.join(Utc::now());
self.vault.join(OffsetDateTime::now_utc());
self.last_msg_id = Some(d.log.last().map(|m| m.id));
self.vault.add_messages(d.log, None);
}

View file

@ -4,13 +4,16 @@ use std::fs::File;
use std::io::{BufWriter, Write};
use std::path::Path;
use time::format_description::FormatItem;
use time::macros::format_description;
use unicode_width::UnicodeWidthStr;
use crate::euph::api::Snowflake;
use crate::store::{MsgStore, Tree};
use crate::vault::{EuphMsg, Vault};
const TIME_FORMAT: &str = "%F %T";
const TIME_FORMAT: &[FormatItem<'_>] =
format_description!("[year]-[month]-[day] [hour]:[minute]:[second]");
const TIME_EMPTY: &str = " ";
pub async fn export(vault: &Vault, room: String, file: &Path) -> anyhow::Result<()> {
@ -67,7 +70,11 @@ fn write_msg(file: &mut BufWriter<File>, indent_string: &str, msg: &EuphMsg) ->
for (i, line) in msg.content.lines().enumerate() {
if i == 0 {
let time = msg.time.0.format(TIME_FORMAT);
let time = msg
.time
.0
.format(TIME_FORMAT)
.expect("time can be formatted");
writeln!(file, "{time} {indent_string}[{nick}] {line}")?;
} else {
writeln!(file, "{TIME_EMPTY} {indent_string}| {nick_empty} {line}")?;

View file

@ -2,10 +2,10 @@ use std::sync::Arc;
use std::vec;
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use crossterm::style::{ContentStyle, Stylize};
use log::{Level, Log};
use parking_lot::Mutex;
use time::OffsetDateTime;
use tokio::sync::mpsc;
use toss::styled::Styled;
@ -14,7 +14,7 @@ use crate::store::{Msg, MsgStore, Path, Tree};
#[derive(Debug, Clone)]
pub struct LogMsg {
id: usize,
time: DateTime<Utc>,
time: OffsetDateTime,
level: Level,
content: String,
}
@ -30,7 +30,7 @@ impl Msg for LogMsg {
None
}
fn time(&self) -> DateTime<Utc> {
fn time(&self) -> OffsetDateTime {
self.time
}
@ -109,7 +109,7 @@ impl Log for Logger {
let mut guard = self.messages.lock();
let msg = LogMsg {
id: guard.len(),
time: Utc::now(),
time: OffsetDateTime::now_utc(),
level: record.level(),
content: format!("<{}> {}", record.target(), record.args()),
};

View file

@ -4,7 +4,7 @@ use std::hash::Hash;
use std::vec;
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use time::OffsetDateTime;
use toss::styled::Styled;
pub trait Msg {
@ -12,7 +12,7 @@ pub trait Msg {
fn id(&self) -> Self::Id;
fn parent(&self) -> Option<Self::Id>;
fn time(&self) -> DateTime<Utc>;
fn time(&self) -> OffsetDateTime;
fn nick(&self) -> Styled;
fn content(&self) -> Styled;

View file

@ -3,7 +3,7 @@
use std::collections::{vec_deque, VecDeque};
use std::iter;
use chrono::{DateTime, Utc};
use time::OffsetDateTime;
use toss::styled::Styled;
use crate::macros::some_or_return;
@ -50,7 +50,7 @@ pub enum BlockBody<I> {
#[derive(Debug, Clone)]
pub struct Block<I> {
pub line: i32,
pub time: Option<DateTime<Utc>>,
pub time: Option<OffsetDateTime>,
pub indent: usize,
pub body: BlockBody<I>,
}
@ -75,7 +75,7 @@ impl<I> Block<I> {
}
pub fn msg(
time: DateTime<Utc>,
time: OffsetDateTime,
indent: usize,
id: I,
nick: Styled,
@ -92,7 +92,7 @@ impl<I> Block<I> {
}
}
pub fn placeholder(time: Option<DateTime<Utc>>, indent: usize, id: I) -> Self {
pub fn placeholder(time: Option<OffsetDateTime>, indent: usize, id: I) -> Self {
Self {
line: 0,
time,

View file

@ -1,6 +1,6 @@
//! Rendering blocks to a [`Frame`].
use chrono::{DateTime, Utc};
use time::OffsetDateTime;
use toss::frame::{Frame, Pos};
use toss::styled::Styled;
@ -10,7 +10,7 @@ use super::blocks::{Block, BlockBody, MsgBlock, MsgContent};
use super::{util, InnerTreeViewState};
impl<M: Msg, S: MsgStore<M>> InnerTreeViewState<M, S> {
fn render_time(frame: &mut Frame, line: i32, time: Option<DateTime<Utc>>, is_cursor: bool) {
fn render_time(frame: &mut Frame, line: i32, time: Option<OffsetDateTime>, is_cursor: bool) {
let pos = Pos::new(0, line);
let style = if is_cursor {
util::style_time_inverted()
@ -19,7 +19,9 @@ impl<M: Msg, S: MsgStore<M>> InnerTreeViewState<M, S> {
};
if let Some(time) = time {
let time = format!("{}", time.format(util::TIME_FORMAT));
let time = time
.format(util::TIME_FORMAT)
.expect("time can be formatted");
frame.write(pos, (&time, style));
} else {
frame.write(pos, (util::TIME_EMPTY, style));
@ -51,7 +53,7 @@ impl<M: Msg, S: MsgStore<M>> InnerTreeViewState<M, S> {
fn draw_msg_block(
frame: &mut Frame,
line: i32,
time: Option<DateTime<Utc>>,
time: Option<OffsetDateTime>,
indent: usize,
msg: &MsgBlock<M::Id>,
is_cursor: bool,

View file

@ -1,10 +1,13 @@
//! Constants and helper functions.
use crossterm::style::{ContentStyle, Stylize};
use time::format_description::FormatItem;
use time::macros::format_description;
use toss::frame::Frame;
use toss::styled::Styled;
pub const TIME_FORMAT: &str = "%F %R ";
pub const TIME_FORMAT: &[FormatItem<'_>] =
format_description!("[year]-[month]-[day] [hour]:[minute] ");
pub const TIME_EMPTY: &str = " ";
pub const TIME_WIDTH: usize = TIME_EMPTY.len();

View file

@ -1,9 +1,9 @@
use std::mem;
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use rusqlite::types::{FromSql, FromSqlError, ToSqlOutput, Value, ValueRef};
use rusqlite::{named_params, params, Connection, OptionalExtension, ToSql, Transaction};
use time::OffsetDateTime;
use tokio::sync::{mpsc, oneshot};
use toss::styled::Styled;
@ -27,7 +27,7 @@ impl FromSql for Snowflake {
impl ToSql for Time {
fn to_sql(&self) -> rusqlite::Result<ToSqlOutput<'_>> {
let timestamp = self.0.timestamp();
let timestamp = self.0.unix_timestamp();
Ok(ToSqlOutput::Owned(Value::Integer(timestamp)))
}
}
@ -35,7 +35,9 @@ impl ToSql for Time {
impl FromSql for Time {
fn column_result(value: ValueRef<'_>) -> rusqlite::types::FromSqlResult<Self> {
let timestamp = i64::column_result(value)?;
Ok(Self::new(timestamp))
Ok(Self(
OffsetDateTime::from_unix_timestamp(timestamp).expect("timestamp in range"),
))
}
}
@ -59,7 +61,7 @@ impl Msg for EuphMsg {
self.parent
}
fn time(&self) -> DateTime<Utc> {
fn time(&self) -> OffsetDateTime {
self.time.0
}
@ -103,7 +105,7 @@ impl EuphVault {
&self.room
}
pub fn join(&self, time: DateTime<Utc>) {
pub fn join(&self, time: OffsetDateTime) {
let request = EuphRequest::Join {
room: self.room.clone(),
time,
@ -225,7 +227,7 @@ pub(super) enum EuphRequest {
},
Join {
room: String,
time: DateTime<Utc>,
time: OffsetDateTime,
},
Delete {
room: String,
@ -325,7 +327,7 @@ impl EuphRequest {
Ok(())
}
fn join(conn: &mut Connection, room: String, time: DateTime<Utc>) -> rusqlite::Result<()> {
fn join(conn: &mut Connection, room: String, time: OffsetDateTime) -> rusqlite::Result<()> {
conn.execute(
"
INSERT INTO euph_rooms (room, first_joined, last_joined)