summaryrefslogtreecommitdiff
path: root/src/dates.rs
blob: fc3863ce3b491ecdcb133725070e21fe46005b7c (plain)
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
use std::path::Path;
// use std::str::FromStr;
// use chrono::{Datelike, NaiveDate, NaiveTime, Weekday, Duration, Timelike};
use chrono::{Datelike, NaiveDate, Duration};

pub struct WTDPath<'a> {
    pub path: &'a Path,
    pub week_start: Option<NaiveDate>,
    pub is_weekly_file: bool,
}

// both start, end are inclusive.
pub fn relevant_files<'a>(start: &'a NaiveDate, end: &'a NaiveDate) -> Vec<WTDPath<'a>> {
    let mut paths: Vec<WTDPath> = vec![];
    if let Some(path) = maybe_path("wtd.md".to_string()) {
        paths.push(WTDPath {
            path: &path,
            week_start: None,
            is_weekly_file: false,
        });
    }

    let weekly = maybe_path("weekly.md".to_string());

    let start_week = week_start_of(start);
    let end_week = week_start_of(end); // inclusive

    let mut curr_week = start_week;
    while curr_week <= end_week {
        let maybe_week_path = week_file(curr_week);
        let path = match [maybe_week_path, weekly] {
            [Some(path), _] => path,
            [_, Some(path)] => path,
            [None, None] => continue,
        };
        paths.push(WTDPath {
            path: path,
            week_start: Some(curr_week),
            is_weekly_file: maybe_week_path.is_none(),
        });
        curr_week = curr_week + Duration::weeks(1);
    }

    return paths;
}

fn week_file(week_start: NaiveDate) -> Option<&'static Path> {
    let filename = week_start.format("%b_%d_%Y.md").to_string().to_lowercase();
    return maybe_path(filename);
}

fn maybe_path(name: String) -> Option<&'static Path> {
    let path = Path::new("wtd.md");
    return if path.exists() { Some(&path) } else { None };
}

fn week_start_of(date: &NaiveDate) -> NaiveDate {
    let days_from_monday = date.weekday().number_from_monday();
    return *date - Duration::days(days_from_monday.into());
}
generated by cgit on debian on lair
contact matthew@masot.net with questions or feedback