Compare commits

...

3 Commits

4 changed files with 233 additions and 57 deletions

5
.gitignore vendored
View File

@ -17,3 +17,8 @@ Cargo.lock
# Added by cargo
/target
# config file
.rusty_task.json

View File

@ -59,7 +59,6 @@ impl Config {
home_cfg.push(format!(".{}", cfg_name));
let mut pwd_cfg = PathBuf::from(pwd.clone());
pwd_cfg.push(cfg_name);
pwd_cfg.push(format!(".{}", cfg_name));
Ok(vec![home_config_cfg, home_cfg, pwd_cfg])

View File

@ -1,29 +1,32 @@
mod config;
mod todo;
mod todo_file;
use crate::config::Config;
use crate::todo::{Status as TaskStatus, TaskGroup};
use crate::todo_file::TodoFile;
use chrono::naive::NaiveDate;
use chrono::{Datelike, Local};
use comrak::nodes::{AstNode, NodeHeading, NodeValue};
use comrak::{format_commonmark, parse_document, Arena};
use comrak::nodes::{AstNode, NodeValue};
use comrak::{parse_document, Arena};
use comrak::{ComrakExtensionOptions, ComrakOptions, ComrakParseOptions};
use std::borrow::Borrow;
use std::collections::HashSet;
use std::collections::HashMap;
use std::env;
use std::fs::{read, read_dir, File};
use std::io::Write;
use std::iter::FromIterator;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::str;
//TODO handle unwraps and errors more uniformly
//TODO refactor creating new file
//TODO clean up verbose printing
//TODO create config for passing options to different files
//TODO create custom errors for better error handling
fn main() {
let expected_cfg_files = Config::expected_locations().unwrap();
println!("{:#?}", expected_cfg_files);
let cfg_files: Vec<&Path> = expected_cfg_files
.iter()
.map(|file| Path::new(file))
@ -40,19 +43,17 @@ fn main() {
let cfg = Config::load(cfg_files.last().unwrap().to_str().unwrap()).unwrap();
println!("{:#?}", cfg);
let data_dir = get_data_dir("notes");
println!("{}", data_dir.to_str().unwrap());
let data_dir = get_data_dir(&cfg.notes_dir.clone().expect("Could not get notes dir from config"));
println!("dir = {}", data_dir.to_str().unwrap());
let latest_file =
get_latest_file(&data_dir).expect(format!("Could not find any notes files").as_str());
get_latest_file(&data_dir);
println!("Latest file: {:?}", latest_file);
let mut editor = Command::new(cfg.editor.expect("Could not resovle edidtor from config"));
let now = Local::now();
let today = NaiveDate::from_ymd_opt(now.year(), now.month(), now.day());
let current_file = match today {
Some(today) if latest_file.date < today => {
let today = NaiveDate::from_ymd_opt(now.year(), now.month(), now.day()).unwrap();
let current_file = match latest_file {
Ok(file) if file.date < today => {
println!("Today's file does not exist, creating");
let today_file_name = format!(
"{}-{:02}-{:02}.md",
@ -62,46 +63,94 @@ fn main() {
);
let mut today_file_path = data_dir.clone();
today_file_path.push(today_file_name);
let sections: HashSet<String> =
HashSet::from_iter(cfg.sections.clone().unwrap().into_iter());
let arena = Arena::new();
let root = parse_todo_file(&latest_file, &arena);
let found_sections: HashSet<String> = HashSet::from_iter(
&mut cleanup_sections(&root, &cfg.sections.unwrap()).into_iter(),
let root = parse_todo_file(&file, &arena);
//println!("{:#?}", root);
//println!("=======================================================");
let sections = &cfg.sections.unwrap();
let groups = extract_secitons(root, sections);
println!("{:#?}", groups);
let level = groups.values().map(|group| group.level).min().unwrap_or(2);
sections
.iter()
.map(|section| match groups.get(section) {
Some(group) => group.clone(),
None => TaskGroup::empty(section.to_string(), level),
})
.for_each(|task_group| println!("{}", task_group.to_string()));
let mut content = format!(
"# Today's tasks {}-{:02}-{:02}\n",
today.year(),
today.month(),
today.day()
);
let missing_sections: Vec<&String> = sections.symmetric_difference(&found_sections).collect();
sections
.iter()
.map(|section| match groups.get(section) {
Some(group) => group.clone(),
None => TaskGroup::empty(section.to_string(), level),
})
.for_each(|task_group| {
content.push_str(format!("\n{}", task_group.to_string()).as_str())
});
let mut new_doc = vec![];
format_commonmark(root, &ComrakOptions::default(), &mut new_doc).unwrap();
for section in missing_sections.iter().map(|s| format!("\n## {}\n", s)) {
new_doc.append(&mut section.as_bytes().to_vec())
}
let mut new_file = File::create(today_file_path.clone()).unwrap();
new_file.write_all(&new_doc).unwrap();
let mut file = File::create(today_file_path.clone())
.expect("Could not open today's file: {today_file_path}");
write!(file, "{}", content).expect("Could not write to file: {today_file_path}");
Some(today_file_path)
}
Some(_) => {
println!("Todays file was created");
Some(latest_file.file.path())
Ok(file) => {
println!("Today's file was created");
Some(file.file.path())
}
_ => {
println!("Could not get today's date");
None
Err(_) => {
println!("No files in dir: {:}", cfg.notes_dir.unwrap());
let today_file_name = format!(
"{}-{:02}-{:02}.md",
today.year(),
today.month(),
today.day()
);
let mut today_file_path = data_dir.clone();
today_file_path.push(today_file_name);
let sections = &cfg.sections.unwrap();
let mut content = format!(
"# Today's tasks {}-{:02}-{:02}\n",
today.year(),
today.month(),
today.day()
);
sections
.iter()
.map(|section| TaskGroup::empty(section.to_string(), 2))
.for_each(|task_group| {
content.push_str(format!("\n{}", task_group.to_string()).as_str())
});
let mut file = File::create(today_file_path.clone())
.expect("Could not open today's file: {today_file_path}");
write!(file, "{}", content).expect("Could not write to file: {today_file_path}");
Some(today_file_path)
}
};
if let Some(file) = current_file {
editor
Command::new(cfg.editor.expect("Could not resolve editor from config"))
.args([file])
.status()
.expect(format!("failed to launch editor {}", "vim").as_str());
};
}
fn parse_todo_file<'a>(file: &TodoFile, arena: &'a Arena<AstNode<'a>>) -> &'a AstNode<'a> {
let options = &ComrakOptions {
extension: ComrakExtensionOptions {
@ -128,15 +177,17 @@ fn parse_todo_file<'a>(file: &TodoFile, arena: &'a Arena<AstNode<'a>>) -> &'a As
parse_document(arena, contents, options)
}
fn cleanup_sections<'a>(root: &'a AstNode<'a>, sections: &Vec<String>) -> Vec<String> {
let mut found_sections: Vec<String> = Vec::new();
fn extract_secitons<'a>(
root: &'a AstNode<'a>,
sections: &Vec<String>,
) -> HashMap<String, TaskGroup> {
let mut groups: HashMap<String, TaskGroup> = HashMap::new();
for node in root.reverse_children() {
let node_ref = &node.data.borrow();
if let NodeValue::Heading(heading) = node_ref.value {
if heading.level < 3 {
if heading.level < 2 {
continue;
}
println!("at level {}", heading.level);
let first_child_ref = &node.first_child();
let first_child = if let Some(child) = first_child_ref.borrow() {
@ -152,27 +203,20 @@ fn cleanup_sections<'a>(root: &'a AstNode<'a>, sections: &Vec<String>) -> Vec<St
continue;
};
println!("checking {}", title);
if !sections.iter().any(|section| section.eq(title)) {
let level = heading.level;
println!("removing {}", title);
let mut following = node.following_siblings();
following.next(); // Skip self
for node in following {
// remove everthing under this heading
match &node.data.borrow().value {
NodeValue::Heading(sub_heading) if sub_heading.level <= level => break,
_ => node.detach(),
}
println!("Attempting to parse {}", title);
if sections.iter().any(|section| section.eq(title)) {
if let Ok(mut group) = TaskGroup::try_from(node) {
group.tasks = group
.tasks
.into_iter()
.filter(|task| !matches!(task.status, TaskStatus::Done(_)))
.collect();
groups.insert(title.to_string(), group);
}
node.detach(); // remove heading as well
} else {
found_sections.push(title.to_string());
}
};
}
found_sections
groups
}
fn get_data_dir(dir_name: &str) -> PathBuf {

128
src/todo/mod.rs Normal file
View File

@ -0,0 +1,128 @@
use std::borrow::Borrow;
use comrak::nodes::AstNode;
use comrak::nodes::NodeValue;
#[derive(Debug, Clone)]
pub struct TaskGroup {
pub name: String,
pub tasks: Vec<Task>,
pub level: u8,
}
// This does not support subtasks, need to figure out best path forward
#[derive(Debug, Clone)]
pub struct Task {
pub status: Status,
pub text: String,
}
#[derive(Debug, PartialEq, Clone)]
pub enum Status {
Done(char),
Todo(char),
Empty,
}
impl Task {
fn find_text<'a>(node: &'a AstNode<'a>) -> String {
let mut text = String::new();
for child in node.descendants() {
let data_ref = child.data.borrow();
if let NodeValue::Text(contents) = &data_ref.value {
text.push_str(format!("{}\n ", &contents.clone()).as_str());
};
}
text
}
}
impl ToString for Task {
fn to_string(&self) -> String {
let ch = match self.status {
Status::Done(ch) => ch,
Status::Todo(ch) => ch,
Status::Empty => ' ',
};
format!(" - [{}] {}\n", ch, self.text.trim())
}
}
impl<'a> TryFrom<&'a AstNode<'a>> for Task {
type Error = String;
fn try_from(node: &'a AstNode<'a>) -> Result<Self, Self::Error> {
let data_ref = &node.data.borrow();
if let NodeValue::TaskItem(ch) = data_ref.value {
let text = Self::find_text(node);
let status = match ch {
Some(c) if c == 'x' || c == 'X' => Status::Done(c),
Some(c) => Status::Todo(c),
_ => Status::Empty,
};
Ok(Self { status, text })
} else {
Err("Node being parsed is not a TaskItem".into())
}
}
}
impl TaskGroup {
pub fn empty(name: String, level: u8) -> TaskGroup {
TaskGroup {
name,
tasks: Vec::new(),
level,
}
}
}
impl ToString for TaskGroup {
fn to_string(&self) -> String {
let mut output = String::new();
output.push_str(format!("{} {}\n", "#".repeat(self.level.into()), self.name).as_str());
self.tasks
.iter()
.for_each(|task| output.push_str(task.to_string().as_str()));
output
}
}
impl<'a> TryFrom<&'a AstNode<'a>> for TaskGroup {
type Error = String;
fn try_from(node: &'a AstNode<'a>) -> Result<Self, Self::Error> {
let node_ref = &node.data.borrow();
if let NodeValue::Heading(heading) = node_ref.value {
let level = heading.level;
let first_child_ref = &node.first_child();
let first_child = if let Some(child) = first_child_ref.borrow() {
child
} else {
return Err("".into());
};
let data_ref = &first_child.data.borrow();
let name = if let NodeValue::Text(value) = &data_ref.value {
value.to_string()
} else {
return Err("".into());
};
let next_sib = node.next_sibling().ok_or("Empty section at end of file")?;
if let NodeValue::List(_list_meta) = next_sib.data.borrow().value {
let tasks = next_sib
.children()
.into_iter()
.filter_map(|item_node| Task::try_from(item_node).ok())
.collect();
Ok(TaskGroup { name, tasks, level })
} else {
Err("Next sibling of node is not a list".into())
}
} else {
Err("Node is not a section heading".into())
}
}
}