summaryrefslogtreecommitdiff
path: root/src/prune.rs
blob: dd7a5fb4e4f699a83ce71b59a22a176747fa5f20 (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
use std::path::Path;
use std::fs::File;
use std::io::prelude::*;
use chrono::{NaiveDate, Duration};

use crate::parse::*;

pub fn prune_week_from_file(week: NaiveDate, file_str: &str) -> String {
    let path = Path::new(file_str);
    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 prune_week_from_str(week, &s),
    }
}

fn prune_week_from_str(week: NaiveDate, file_str: &str) -> String {
    let mut new_contents = "\n".to_string();
    let mut ghost = false;
    let ghost_start = week - Duration::days(6);
    let ghost_end = week + Duration::days(6);
    for l in file_str.split('\n') {
        if l.starts_with("# ") {
            // '# 12/27/21', starts a new week block
            let start_date = parse_date_line(l).expect("Couldn't parse '# ' header.");
            ghost = ghost_start <= start_date && start_date <= ghost_end;
            if ghost && start_date != week {
                panic!("generate currently assumes `# ` headers always start on Mondays.");
            }
        }
        if !ghost {
            new_contents.push_str(l);
            new_contents.push('\n');
        }
    }
    // Remove leading & trailing newlines.
    new_contents.remove(0);
    new_contents.pop();
    return new_contents;
}
generated by cgit on debian on lair
contact matthew@masot.net with questions or feedback