diff options
Diffstat (limited to 'src/prune.rs')
-rw-r--r-- | src/prune.rs | 49 |
1 files changed, 49 insertions, 0 deletions
diff --git a/src/prune.rs b/src/prune.rs new file mode 100644 index 0000000..dd7a5fb --- /dev/null +++ b/src/prune.rs @@ -0,0 +1,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; +} |