| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright (c) 2026 UtopiaIA |
| 3 | |
| 4 | //! The time a changeset is made, in the local time zone. |
| 5 | //! |
| 6 | //! The time zone is the system's, as [jiff](https://docs.rs/jiff) finds it |
| 7 | //! without calling into the C library: the `TZ` environment variable, a |
| 8 | //! POSIX rule or a name in the system's time zone database, or else the |
| 9 | //! system setting (on Unix, `/etc/localtime`). When it cannot be determined, |
| 10 | //! the offset is zero. |
| 11 | |
| 12 | use braid_format::Signature; |
| 13 | use jiff::Timestamp; |
| 14 | use jiff::tz::TimeZone; |
| 15 | |
| 16 | /// The current time: seconds since the Unix epoch, and the offset of the |
| 17 | /// local time zone from UTC at that instant, in minutes. |
| 18 | pub fn local_now() -> (i64, i64) { |
| 19 | let now = Timestamp::now(); |
| 20 | let offset = |
| 21 | TimeZone::try_system().map_or(0, |zone| i64::from(zone.to_offset(now).seconds()) / 60); |
| 22 | (now.as_second(), offset) |
| 23 | } |
| 24 | |
| 25 | /// A signature by `name` and `email`, made now, in local time. |
| 26 | pub fn signature_now(name: &[u8], email: &[u8]) -> Signature { |
| 27 | let (seconds, offset_minutes) = local_now(); |
| 28 | Signature { |
| 29 | name: name.to_vec(), |
| 30 | email: email.to_vec(), |
| 31 | seconds, |
| 32 | offset_minutes, |
| 33 | } |
| 34 | } |
| 35 | |
| 36 | #[cfg(test)] |
| 37 | mod tests { |
| 38 | use super::*; |
| 39 | |
| 40 | #[test] |
| 41 | fn now_has_a_real_offset() { |
| 42 | let (seconds, offset) = local_now(); |
| 43 | assert!(seconds > 1_700_000_000); |
| 44 | // Every time zone in use is within a day of UTC. |
| 45 | assert!(offset.abs() < 24 * 60, "{offset}"); |
| 46 | let signature = signature_now(b"Ada", b"ada@example.org"); |
| 47 | assert_eq!(signature.name, b"Ada"); |
| 48 | assert!(signature.seconds >= seconds); |
| 49 | } |
| 50 | } |