1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
use chrono::{DateTime, FixedOffset, Local, TimeZone};

use std::env;

use std::io::ErrorKind;

use std::fs::{self, File, Metadata, OpenOptions};
use std::time::SystemTime;

/// Get the created time or panic
pub fn get_metadata_created(metadata: Metadata) -> DateTime<Local> {
    match metadata.created() {
        Ok(created_at) => system_time_to_local_datetime(&created_at),
        Err(e) => panic!("err getting session metadata: {:?}", e),
    }
}

/// Convert a SystemTime to chrono::DateTime
pub fn system_time_to_local_datetime(time: &SystemTime) -> DateTime<Local> {
    match time.duration_since(SystemTime::UNIX_EPOCH) {
        Ok(duration) => Local.timestamp(duration.as_secs() as i64, 0),
        Err(e) => panic!("error getting SystemTime seconds: {}", e),
    }
}

pub fn format_datetime(time: &DateTime<Local>) -> String {
    time.to_rfc3339()
}

pub fn datetime_from_str(time: &str) -> DateTime<FixedOffset> {
    match DateTime::parse_from_rfc3339(time) {
        Ok(datetime) => datetime,
        Err(e) => panic!("failed to parse datetime {}: {}", time, e),
    }
}

/// Return the value of $HOME or panic if it doesn't exist
pub fn get_home_dir() -> String {
    match env::var("HOME") {
        Ok(home_dir) => home_dir,
        Err(e) => panic!("error getting $HOME env variable: {}", e),
    }
}

/// Create a directory & all parent directories if they don't exist
/// & return the name. Panic if an error occurs while creating the dir
pub fn create_dir(dir: &str) {
    fs::create_dir_all(&dir).unwrap_or_else(|e| {
        // if it already exists, no problem
        if e.kind() != ErrorKind::AlreadyExists {
            panic!("could not create {} directory: {}", dir, e);
        }
    });
}

/// Open a file for appending or create it if it doesn't exist
/// Panic on error, return the file handle
pub fn create_or_open_file(path: &str) -> File {
    let file = OpenOptions::new()
        .create(true)
        .append(true)
        .open(&path);

    match file {
        Ok(file) => file,
        Err(e) => panic!("Error opening {}: {}", &path, e),
    }
}

/// Returns the length in hours between the start & end time
pub fn get_length_hours<Tz: TimeZone>(start: &DateTime<Tz>, end: &DateTime<Tz>) -> f64 {
    ((end.timestamp() - start.timestamp()) as f64) / 3600.0
}