Debian Codegraph @

.cargo/vendor/built/src/krono.rs

raw
1 use crate::{environment, util, write_str_variable, write_variable};
2 use std::{fs, io};
3
4 impl<'a> util::ParseFromEnv<'a> for chrono::DateTime<chrono::offset::Utc> {
5 type Err = chrono::ParseError;
6
7 fn parse_from_env(s: &'a str) -> Result<Self, Self::Err> {
8 Ok(chrono::DateTime::parse_from_rfc2822(s)?.with_timezone(&chrono::offset::Utc))
9 }
10 }
11
12 /// Parse a time-string as formatted by `built`.
13 ///
14 /// ```
15 /// use chrono::Datelike;
16 ///
17 /// pub mod build_info {
18 /// pub static BUILT_TIME_UTC: &'static str = "Tue, 14 Feb 2017 05:21:41 GMT";
19 /// }
20 ///
21 /// assert_eq!(built::util::strptime(&build_info::BUILT_TIME_UTC).year(), 2017);
22 /// ```
23 ///
24 /// # Panics
25 /// If the string can't be parsed. This should never happen with input provided
26 /// by `built`.
27 #[must_use]
28 pub fn strptime(s: &str) -> chrono::DateTime<chrono::offset::Utc> {
29 chrono::DateTime::parse_from_rfc2822(s)
30 .unwrap()
31 .with_timezone(&chrono::offset::Utc)
32 }
33
34 fn get_source_date_epoch_from_env() -> Option<chrono::DateTime<chrono::offset::Utc>> {
35 match std::env::var(crate::SOURCE_DATE_EPOCH) {
36 Ok(val) => {
37 let ts = match val.parse::<i64>() {
38 Ok(ts) => ts,
39 Err(_) => {
40 eprintln!("SOURCE_DATE_EPOCH defined, but not a i64");
41 return None;
42 }
43 };
44 match chrono::DateTime::from_timestamp(ts, 0) {
45 Some(now) => Some(now),
46 None => {
47 eprintln!("SOURCE_DATE_EPOCH can't be represented as a UTC-time");
48 None
49 }
50 }
51 }
52 Err(_) => None,
53 }
54 }
55
56 pub fn write_time(mut w: &fs::File, envmap: &environment::EnvironmentMap) -> io::Result<()> {
57 use io::Write;
58
59 let now = match envmap.get_override_var("BUILT_TIME_UTC") {
60 Some(v) => v,
61 None => get_source_date_epoch_from_env().unwrap_or_else(chrono::offset::Utc::now),
62 };
63 write_str_variable!(
64 w,
65 "BUILT_TIME_UTC",
66 now.to_rfc2822(),
67 "The build time in RFC2822, UTC."
68 );
69 Ok(())
70 }