using config to load editor and sections

This commit is contained in:
Andrei Stoica 2023-06-22 13:44:06 -04:00
parent fffb3aebfe
commit 0fdef6ed6e
2 changed files with 53 additions and 32 deletions

View File

@ -1,13 +1,13 @@
mod config;
mod todo_file; mod todo_file;
use crate::config::Config;
use crate::todo_file::TodoFile; use crate::todo_file::TodoFile;
use chrono::naive::NaiveDate; use chrono::naive::NaiveDate;
use chrono::{Datelike, Local}; use chrono::{Datelike, Local};
use comrak::nodes::{AstNode, NodeValue}; use comrak::nodes::{AstNode, NodeValue};
use comrak::{ use comrak::{format_commonmark, parse_document, Arena};
format_commonmark, parse_document, Arena, ComrakExtensionOptions, ComrakOptions, use comrak::{ComrakExtensionOptions, ComrakOptions, ComrakParseOptions};
ComrakParseOptions,
};
use std::borrow::Borrow; use std::borrow::Borrow;
use std::env; use std::env;
use std::fs::{read, read_dir, File}; use std::fs::{read, read_dir, File};
@ -21,6 +21,23 @@ use std::str;
//TODO create config for passing options to different files //TODO create config for passing options to different files
fn main() { fn main() {
let expected_cfg_files = Config::expected_locations().unwrap();
let cfg_files: Vec<&Path> = expected_cfg_files
.iter()
.map(|file| Path::new(file))
.filter(|file| file.exists())
.collect();
println!("{:#?}", cfg_files);
if cfg_files.len() <= 0 {
let status = Config::write_default(expected_cfg_files[0].to_str().unwrap());
if let Err(e) = status {
println!("Could not write to default cfg location: {:#?}", e);
}
}
let cfg = Config::load(cfg_files.last().unwrap().to_str().unwrap()).unwrap();
println!("{:#?}", cfg);
let data_dir = get_data_dir("notes"); let data_dir = get_data_dir("notes");
println!("{}", data_dir.to_str().unwrap()); println!("{}", data_dir.to_str().unwrap());
@ -28,11 +45,11 @@ fn main() {
get_latest_file(&data_dir).expect(format!("Could not find any notes files").as_str()); get_latest_file(&data_dir).expect(format!("Could not find any notes files").as_str());
println!("Latest file: {:?}", latest_file); println!("Latest file: {:?}", latest_file);
let mut editor = Command::new(get_editor("vim".to_string())); let mut editor = Command::new(cfg.editor.expect("Could not resovle edidtor from config"));
let now = Local::now(); let now = Local::now();
let today = NaiveDate::from_ymd_opt(now.year(), now.month(), now.day()); let today = NaiveDate::from_ymd_opt(now.year(), now.month(), now.day());
match today { let current_file = match today {
Some(today) if latest_file.date < today => { Some(today) if latest_file.date < today => {
println!("Today's file does not exist, creating"); println!("Today's file does not exist, creating");
let today_file_name = format!( let today_file_name = format!(
@ -46,27 +63,35 @@ fn main() {
let arena = Arena::new(); let arena = Arena::new();
let root = parse_todo_file(&latest_file, &arena); let root = parse_todo_file(&latest_file, &arena);
cleanup_sections(&root, &["Hello world!", "Hi there"], 2); //println!("{:#?}", root);
//println!("=======================================================");
//println!("{:#?}", root.children().collect::<Vec<_>>());
cleanup_sections(&root, &cfg.sections.unwrap(), 2);
//println!("{:#?}", root);
let mut new_doc = vec![]; let mut new_doc = vec![];
format_commonmark(root, &ComrakOptions::default(), &mut new_doc).unwrap(); format_commonmark(root, &ComrakOptions::default(), &mut new_doc).unwrap();
let mut new_file = File::create(today_file_path.clone()).unwrap(); let mut new_file = File::create(today_file_path.clone()).unwrap();
new_file.write_all(&new_doc).unwrap(); new_file.write_all(&new_doc).unwrap();
editor Some(today_file_path)
.args([today_file_path]) },
.status()
.expect(format!("failed to launch editor {}", "vim").as_str());
}
Some(_) => { Some(_) => {
println!("Todays file was created"); println!("Todays file was created");
Some(latest_file.file.path())
},
_ => {
println!("Could not get today's date");
None
}
};
if let Some(file) = current_file {
editor editor
.args([latest_file.file.path()]) .args([file])
.status() .status()
.expect(format!("failed to launch editor {}", "vim").as_str()); .expect(format!("failed to launch editor {}", "vim").as_str());
} };
_ => println!("Could not get today's date"),
}
} }
fn parse_todo_file<'a>(file: &TodoFile, arena: &'a Arena<AstNode<'a>>) -> &'a AstNode<'a> { fn parse_todo_file<'a>(file: &TodoFile, arena: &'a Arena<AstNode<'a>>) -> &'a AstNode<'a> {
@ -97,15 +122,16 @@ fn parse_todo_file<'a>(file: &TodoFile, arena: &'a Arena<AstNode<'a>>) -> &'a As
fn cleanup_sections<'a>( fn cleanup_sections<'a>(
root: &'a AstNode<'a>, root: &'a AstNode<'a>,
sections: &[&str], sections: &Vec<String>,
target_level: u8, target_level: u8,
) -> &'a AstNode<'a> { ) -> &'a AstNode<'a> {
for node in root.children() { for node in root.reverse_children(){
let node_ref = &node.data.borrow(); let node_ref = &node.data.borrow();
if let NodeValue::Heading(heading) = node_ref.value { if let NodeValue::Heading(heading) = node_ref.value {
if heading.level != target_level { if heading.level != target_level {
continue; continue;
} }
println!("at level {}", heading.level);
let first_child_ref = &node.first_child(); let first_child_ref = &node.first_child();
let first_child = if let Some(child) = first_child_ref.borrow() { let first_child = if let Some(child) = first_child_ref.borrow() {
@ -121,15 +147,17 @@ fn cleanup_sections<'a>(
continue; continue;
}; };
if !sections.contains(&title.as_str()) { println!("checking {}", title);
if !sections.iter().any(|section| section.eq(title)) {
let level = heading.level; let level = heading.level;
println!("removing {}", title);
let mut following = node.following_siblings(); let mut following = node.following_siblings();
following.next(); // Skip self following.next(); // Skip self
for node in following { for node in following {
// remove everthing under this heading // remove everthing under this heading
match &node.data.borrow().value { match &node.data.borrow().value {
NodeValue::Heading(heading) if heading.level <= level => break, NodeValue::Heading(sub_heading) if sub_heading.level <= level => break,
_ => node.detach(), _ => node.detach(),
} }
} }
@ -140,13 +168,6 @@ fn cleanup_sections<'a>(
root root
} }
fn get_editor(fallback: String) -> String {
match env::var("EDITOR") {
Ok(editor) => editor,
_ => fallback,
}
}
fn get_data_dir(dir_name: &str) -> PathBuf { fn get_data_dir(dir_name: &str) -> PathBuf {
let mut dir = match env::var("HOME") { let mut dir = match env::var("HOME") {
Ok(home) => { Ok(home) => {

View File

@ -41,13 +41,13 @@ impl TryFrom<DirEntry> for TodoFile {
fn try_from(direntry: DirEntry) -> Result<Self, Self::Error> { fn try_from(direntry: DirEntry) -> Result<Self, Self::Error> {
let re = TodoFile::get_file_regex(); let re = TodoFile::get_file_regex();
println!("{:?}", re); // println!("{:?}", re);
let file_name = direntry.file_name(); let file_name = direntry.file_name();
let file_name_str = match file_name.to_str() { let file_name_str = match file_name.to_str() {
Some(name) => name, Some(name) => name,
_ => "", _ => "",
}; };
println!("{:?}", file_name_str); // println!("{:?}", file_name_str);
if let Some(caps) = re.captures(file_name_str) { if let Some(caps) = re.captures(file_name_str) {
let year: i32 = Self::capture_as_number(&caps, "year").unwrap(); let year: i32 = Self::capture_as_number(&caps, "year").unwrap();