summaryrefslogtreecommitdiff
path: root/src/parse.rs
blob: d7a6e2b36617ac0306b49e2f41e5d22d50f4b7b5 (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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
use std::path::Path;
use std::fs::File;
use std::io::prelude::*;
use std::str::FromStr;
use chrono::{Datelike, NaiveDate, NaiveTime, Weekday, Duration, Timelike};

use crate::task::*;
use crate::dates::*;

// Translates a Path into a vector of tasks. Panics if the path cannot be opened or read from.
pub fn tasks_from_path(wtd_path: &WTDPath) -> Vec<Task> {
    let path = Path::new(&wtd_path.path);
    let display = path.display();

    // Open the path in read-only mode, returns `io::Result<File>`
    let mut file = match File::open(&path) {
        Err(why) => panic!("Error opening {}: {}", display, why),
        Ok(file) => file,
    };

    // Read the file contents into a string, returns `io::Result<usize>`
    let mut s = String::new();
    match file.read_to_string(&mut s) {
        Err(why) => panic!("Couldn't read {}: {}", display, why),
        Ok(_) => return parse_file_str(&s, wtd_path.week_start),
    }
}

fn parse_file_str(file_str: &str, implicit_week: Option<NaiveDate>) -> Vec<Task> {
    let mut tasks = Vec::new();
    let mut start_date = implicit_week;
    let mut the_date = None;
    for l in file_str.split('\n') {
        if l.starts_with("# ") {
            // '# 12/27/21', starts a new week block
            start_date = parse_date_line(l);
            if implicit_week.is_some() && start_date != implicit_week {
                panic!("Cannot use different '# ' headers in a weekly.md or [week].md file!");
            }
        } else if l.starts_with("## ") {
            // '## Monday/Tuesday/...', starts a new day block
            // Need to compute the actual date, basically looking for the first one after
            // start_date.
            let dayofweek = parse_day_line(l);
            let mut current = start_date.expect("Invalid or missing '# ' date");
            the_date = loop {
                if current.weekday() == dayofweek {
                    break Some(current);
                }
                current = current.succ();
            };
        } else if l.starts_with("- [ ]") || l.starts_with("- [X]") {
            // '- [ ] ...', starts a new task block
            let date = the_date.expect("No current date parsed yet...");
            tasks.push(Task {
                date: date,
                start_time: None,
                end_time: None,
                details: "".to_string(),
                raw: l.to_string(),
                tags: Vec::new(),
            });
            tasks.last_mut().expect("").raw.push('\n');
            let details = l.get(5..).expect("").trim();
            handle_task_details(details, tasks.last_mut().expect("Unexpected error..."));
        } else if l.starts_with(" ") {
            // Extends the last task.
            tasks.last_mut().expect("").raw.push_str(l);
            tasks.last_mut().expect("").raw.push('\n');
            handle_task_details(l, tasks.last_mut().expect("Unexpected error..."));
        } else if l.trim().len() > 0 {
            eprint!("Ignoring line: {}\n", l);
        }
    }
    return tasks;
}

pub fn parse_date_line(l: &str) -> Option<NaiveDate> {
    for maybe_date_str in l.split(' ') {
        if let Ok(date) = NaiveDate::parse_from_str(maybe_date_str, "%m/%d/%y") {
            return Some(date);
        }
    };
    return None;
}

fn parse_day_line(l: &str) -> Weekday {
    let daystr = l.get(3..).expect("Day-of-week line not long enough...");
    return Weekday::from_str(daystr).expect("Misparse day-of-week str...");
}

fn parse_time(s_: &str) -> NaiveTime {
    let formats = vec!["%l:%M%p", "%H:%M"];
    let mut s = s_.to_string();
    if !s.contains(":") {
        if s.ends_with("M") {
            s.insert_str(s.len() - 2, ":00");
        } else {
            s.push_str(":00");
        }
    }
    for format in formats {
        if let Ok(parsed) = NaiveTime::parse_from_str(&s, format) {
            if !format.contains("%p") && parsed.hour() < 6 {
                return parsed + Duration::hours(12);
            }
            return parsed;
        }
    }
    panic!("Couldn't parse time {}", s);
}

fn parse_duration(s: &str) -> chrono::Duration {
    // We try to find Mm, HhMm, Hh
    if s.contains("h") && s.contains("m") {
        // TODO: Decompose this case into the two below.
        let hstr = s.split("h").collect::<Vec<&str>>().get(0).expect("").to_string();
        let mstr = s.split("h").collect::<Vec<&str>>().get(1).expect("").split("m").collect::<Vec<&str>>().get(0).expect("Expected XhYm").to_string();
        let secs = ((hstr.parse::<u64>().unwrap() * 60)
                    + (mstr.parse::<u64>().unwrap())) * 60;
        return chrono::Duration::from_std(std::time::Duration::new(secs, 0)).unwrap();
    } else if s.contains("h") {
        let hstr = s.split("h").collect::<Vec<&str>>().get(0).expect("").to_string();
        let secs = hstr.parse::<u64>().unwrap() * 60 * 60;
        return chrono::Duration::from_std(std::time::Duration::new(secs, 0)).unwrap();
    } else if s.contains("m") {
        let hstr = s.split("m").collect::<Vec<&str>>().get(0).expect("").to_string();
        let secs = hstr.parse::<u64>().unwrap() * 60;
        return chrono::Duration::from_std(std::time::Duration::new(secs, 0)).unwrap();
    }
    panic!("Couldn't parse duration {}", s);
}

fn handle_task_details(l: &str, t: &mut Task) {
    for tok in l.split(' ') {
        if tok.starts_with("+") {
            let tag = tok.get(1..).expect("Unexpected");
            t.tags.push(tag.to_string());
        } else if tok.starts_with("@") {
            let timestr = tok.get(1..).expect("Unexpected");
            if timestr.contains("+") { // @Start+Duration
                let parts: Vec<&str> = timestr.split("+").collect();
                match parts[..] {
                    [startstr, durstr] => {
                        t.start_time = Some(parse_time(startstr));
                        t.end_time = Some(t.start_time.unwrap() + parse_duration(durstr));
                    },
                    _ => panic!("Not 2 parts to {}\n", timestr)
                }
            } else if timestr.contains("--") { // @Start--End
                let parts: Vec<&str> = timestr.split("--").collect();
                match parts[..] {
                    [startstr, endstr] => {
                        t.start_time = Some(parse_time(startstr));
                        t.end_time = Some(parse_time(endstr));
                        if t.start_time > t.end_time {
                            panic!("Start time {} interpreted as after end time {}",
                                   startstr, endstr);
                        }
                    },
                    _ => panic!("Not 2 parts to {}\n", timestr)
                }
            } else {
                panic!("'{}' is not of the form Start+Duration or Start--End\n", timestr);
            }
        } else {
            if t.details.len() > 0 {
                t.details.push(' ');
            }
            t.details.push_str(tok.trim());
        }
    }
}
generated by cgit on debian on lair
contact matthew@masot.net with questions or feedback