Skip to content

Commit

Permalink
Merge pull request #99 from baoyachi/issue_72
Browse files Browse the repository at this point in the history
add stash
  • Loading branch information
baoyachi authored Jul 14, 2022
2 parents 0a51190 + f0d78df commit 8b5a4a3
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 22 deletions.
7 changes: 4 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "shadow-rs"
version = "0.12.0"
version = "0.13.0"
authors = ["baoyachi <[email protected]>"]
edition = "2021"
description = "A build-time information stored in your rust project"
Expand All @@ -11,7 +11,7 @@ repository = "https://github.com/baoyachi/shadow-rs"
documentation = "https://docs.rs/shadow-rs"
homepage = "https://github.com/baoyachi/shadow-rs"
license = "MIT AND Apache-2.0"
exclude = ["shadow-rs.png","build_module.png"]
exclude = ["shadow-rs.png", "build_module.png"]
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html


Expand All @@ -20,8 +20,9 @@ all-features = true

[dependencies]
is_debug = "1.0.1"
chrono = "0.4.13"
const_format = "0.2.22"
tz-rs = "0.6.11"
time = { version = "0.3.11", features = ["formatting", "local-offset", "parsing"] }

#! Optional Dependencies:

Expand Down
6 changes: 5 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,8 @@ mod gen_const;
mod git;
mod time;

pub use time::*;

/// Get current project build mode.
///
/// It's very useful. Debug mode is usually used for debugging information.
Expand Down Expand Up @@ -371,7 +373,9 @@ impl Shadow {
// Author by:https://www.github.com/baoyachi
// The build script repository:https://github.com/baoyachi/shadow-rs
// Create time by:{}"#,
BuildTime::local_now().human_format()
BuildTime::local_now()
.map_err(|err| format!("get local DateTime error:{}", err))?
.human_format()
);
writeln!(&self.f, "{}\n\n", desc)?;
Ok(())
Expand Down
64 changes: 46 additions & 18 deletions src/time.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
use crate::Format;
use chrono::{DateTime, Local, NaiveDateTime, SecondsFormat, TimeZone, Utc};
use std::error::Error;
use std::time::{SystemTime, UNIX_EPOCH};
use time::format_description::well_known::{Rfc2822, Rfc3339};
use time::UtcOffset;
use time::{format_description, OffsetDateTime};
use tz::TimeZone;

pub enum BuildTime {
Local(DateTime<Local>),
Utc(DateTime<Utc>),
Local(OffsetDateTime),
Utc(OffsetDateTime),
}

pub fn now_data_time() -> BuildTime {
Expand All @@ -13,51 +18,59 @@ pub fn now_data_time() -> BuildTime {
// https://reproducible-builds.org/docs/source-date-epoch/
println!("cargo:rerun-if-env-changed=SOURCE_DATE_EPOCH");
match std::env::var_os("SOURCE_DATE_EPOCH") {
None => BuildTime::Local(Local::now()),
None => BuildTime::local_now().unwrap(),
Some(timestamp) => {
let epoch = timestamp
.into_string()
.expect("Input SOURCE_DATE_EPOCH could not be parsed")
.parse::<i64>()
.expect("Input SOURCE_DATE_EPOCH could not be cast to a number");
BuildTime::Utc(Utc.timestamp(epoch, 0))
// BuildTime::Utc(Utc.timestamp(epoch, 0))
BuildTime::Utc(OffsetDateTime::from_unix_timestamp(epoch).unwrap())
}
}
}

impl BuildTime {
pub fn local_now() -> Self {
BuildTime::Local(Local::now())
pub fn local_now() -> Result<Self, Box<dyn Error>> {
let time_zone_local = TimeZone::local()?; // expensive call, should be cached

let duration_since_epoch = SystemTime::now().duration_since(UNIX_EPOCH)?;
let local_time_type =
time_zone_local.find_local_time_type(duration_since_epoch.as_secs().try_into()?)?;
let time_zone_offset = UtcOffset::from_whole_seconds(local_time_type.ut_offset())?;
let local_date_time =
(OffsetDateTime::UNIX_EPOCH + duration_since_epoch).to_offset(time_zone_offset);
Ok(BuildTime::Local(local_date_time))
}

pub fn timestamp_2_utc(time_stamp: i64) -> Self {
let dt = NaiveDateTime::from_timestamp(time_stamp, 0);
BuildTime::Utc(DateTime::<Utc>::from_utc(dt, Utc))
let time = OffsetDateTime::from_unix_timestamp(time_stamp).unwrap();
BuildTime::Utc(time)
}

pub fn to_rfc2822(&self) -> String {
match self {
BuildTime::Local(dt) => dt.to_rfc2822(),
BuildTime::Utc(dt) => dt.to_rfc2822(),
BuildTime::Local(dt) | BuildTime::Utc(dt) => dt.format(&Rfc2822).unwrap(),
}
}

pub fn to_rfc3339(&self) -> String {
let sec_form = SecondsFormat::Secs;
let use_z = true;
match self {
BuildTime::Local(dt) => dt.to_rfc3339_opts(sec_form, use_z),
BuildTime::Utc(dt) => dt.to_rfc3339_opts(sec_form, use_z),
BuildTime::Local(dt) | BuildTime::Utc(dt) => dt.format(&Rfc3339).unwrap(),
}
}
}

impl Format for BuildTime {
fn human_format(&self) -> String {
let fmt = "%Y-%m-%d %H:%M:%S %:z";
let fmt = format_description::parse(
"[year]-[month]-[day] [hour]:[minute]:[second] [offset_hour \
sign:mandatory]:[offset_minute]",
)
.unwrap();
match self {
BuildTime::Local(dt) => dt.format(fmt).to_string(),
BuildTime::Utc(dt) => dt.format(fmt).to_string(),
BuildTime::Local(dt) | BuildTime::Utc(dt) => dt.format(&fmt).unwrap(),
}
}
}
Expand All @@ -72,4 +85,19 @@ mod tests {
let time = now_data_time();
assert_eq!(time.human_format(), "2021-08-04 12:34:03 +00:00");
}

#[test]
fn test_local_now_human_format() {
let time = BuildTime::local_now().unwrap().human_format();
println!("{}", time); // 2022-07-14 00:40:05 +08:00
assert_eq!(time.len(), 26);
}

#[test]
fn test_timestamp_2_utc() {
let time = BuildTime::timestamp_2_utc(1628080443);
assert_eq!(time.to_rfc2822(), "Wed, 04 Aug 2021 12:34:03 +0000");
assert_eq!(time.to_rfc3339(), "2021-08-04T12:34:03Z");
assert_eq!(time.human_format(), "2021-08-04 12:34:03 +00:00");
}
}

0 comments on commit 8b5a4a3

Please sign in to comment.