Compare commits
3 Commits
061afcf9cd
...
02ed04fad5
| Author | SHA1 | Date |
|---|---|---|
|
|
02ed04fad5 | |
|
|
145905066c | |
|
|
34c9ceac86 |
|
|
@ -17,3 +17,8 @@ Cargo.lock
|
||||||
# Added by cargo
|
# Added by cargo
|
||||||
|
|
||||||
/target
|
/target
|
||||||
|
|
||||||
|
|
||||||
|
# config file
|
||||||
|
.rusty_task.json
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -59,7 +59,6 @@ impl Config {
|
||||||
home_cfg.push(format!(".{}", cfg_name));
|
home_cfg.push(format!(".{}", cfg_name));
|
||||||
|
|
||||||
let mut pwd_cfg = PathBuf::from(pwd.clone());
|
let mut pwd_cfg = PathBuf::from(pwd.clone());
|
||||||
pwd_cfg.push(cfg_name);
|
|
||||||
pwd_cfg.push(format!(".{}", cfg_name));
|
pwd_cfg.push(format!(".{}", cfg_name));
|
||||||
|
|
||||||
Ok(vec![home_config_cfg, home_cfg, pwd_cfg])
|
Ok(vec![home_config_cfg, home_cfg, pwd_cfg])
|
||||||
|
|
|
||||||
156
src/main.rs
156
src/main.rs
|
|
@ -1,29 +1,32 @@
|
||||||
mod config;
|
mod config;
|
||||||
|
mod todo;
|
||||||
mod todo_file;
|
mod todo_file;
|
||||||
|
|
||||||
use crate::config::Config;
|
use crate::config::Config;
|
||||||
|
use crate::todo::{Status as TaskStatus, TaskGroup};
|
||||||
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, NodeHeading, NodeValue};
|
use comrak::nodes::{AstNode, NodeValue};
|
||||||
use comrak::{format_commonmark, parse_document, Arena};
|
use comrak::{parse_document, Arena};
|
||||||
use comrak::{ComrakExtensionOptions, ComrakOptions, ComrakParseOptions};
|
use comrak::{ComrakExtensionOptions, ComrakOptions, ComrakParseOptions};
|
||||||
use std::borrow::Borrow;
|
use std::borrow::Borrow;
|
||||||
use std::collections::HashSet;
|
use std::collections::HashMap;
|
||||||
use std::env;
|
use std::env;
|
||||||
use std::fs::{read, read_dir, File};
|
use std::fs::{read, read_dir, File};
|
||||||
use std::io::Write;
|
use std::io::Write;
|
||||||
use std::iter::FromIterator;
|
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
use std::process::Command;
|
use std::process::Command;
|
||||||
use std::str;
|
use std::str;
|
||||||
|
|
||||||
//TODO handle unwraps and errors more uniformly
|
//TODO handle unwraps and errors more uniformly
|
||||||
|
//TODO refactor creating new file
|
||||||
//TODO clean up verbose printing
|
//TODO clean up verbose printing
|
||||||
//TODO create config for passing options to different files
|
//TODO create custom errors for better error handling
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
let expected_cfg_files = Config::expected_locations().unwrap();
|
let expected_cfg_files = Config::expected_locations().unwrap();
|
||||||
|
println!("{:#?}", expected_cfg_files);
|
||||||
let cfg_files: Vec<&Path> = expected_cfg_files
|
let cfg_files: Vec<&Path> = expected_cfg_files
|
||||||
.iter()
|
.iter()
|
||||||
.map(|file| Path::new(file))
|
.map(|file| Path::new(file))
|
||||||
|
|
@ -40,19 +43,17 @@ fn main() {
|
||||||
let cfg = Config::load(cfg_files.last().unwrap().to_str().unwrap()).unwrap();
|
let cfg = Config::load(cfg_files.last().unwrap().to_str().unwrap()).unwrap();
|
||||||
|
|
||||||
println!("{:#?}", cfg);
|
println!("{:#?}", cfg);
|
||||||
let data_dir = get_data_dir("notes");
|
let data_dir = get_data_dir(&cfg.notes_dir.clone().expect("Could not get notes dir from config"));
|
||||||
println!("{}", data_dir.to_str().unwrap());
|
println!("dir = {}", data_dir.to_str().unwrap());
|
||||||
|
|
||||||
let latest_file =
|
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);
|
println!("Latest file: {:?}", latest_file);
|
||||||
|
|
||||||
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()).unwrap();
|
||||||
let current_file = match today {
|
let current_file = match latest_file {
|
||||||
Some(today) if latest_file.date < today => {
|
Ok(file) if 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!(
|
||||||
"{}-{:02}-{:02}.md",
|
"{}-{:02}-{:02}.md",
|
||||||
|
|
@ -62,46 +63,94 @@ fn main() {
|
||||||
);
|
);
|
||||||
let mut today_file_path = data_dir.clone();
|
let mut today_file_path = data_dir.clone();
|
||||||
today_file_path.push(today_file_name);
|
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 arena = Arena::new();
|
||||||
let root = parse_todo_file(&latest_file, &arena);
|
let root = parse_todo_file(&file, &arena);
|
||||||
let found_sections: HashSet<String> = HashSet::from_iter(
|
//println!("{:#?}", root);
|
||||||
&mut cleanup_sections(&root, &cfg.sections.unwrap()).into_iter(),
|
|
||||||
|
//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 file = File::create(today_file_path.clone())
|
||||||
let mut new_doc = vec![];
|
.expect("Could not open today's file: {today_file_path}");
|
||||||
format_commonmark(root, &ComrakOptions::default(), &mut new_doc).unwrap();
|
write!(file, "{}", content).expect("Could not write to file: {today_file_path}");
|
||||||
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();
|
|
||||||
|
|
||||||
Some(today_file_path)
|
Some(today_file_path)
|
||||||
}
|
}
|
||||||
Some(_) => {
|
Ok(file) => {
|
||||||
println!("Todays file was created");
|
println!("Today's file was created");
|
||||||
Some(latest_file.file.path())
|
Some(file.file.path())
|
||||||
}
|
}
|
||||||
_ => {
|
Err(_) => {
|
||||||
println!("Could not get today's date");
|
println!("No files in dir: {:}", cfg.notes_dir.unwrap());
|
||||||
None
|
|
||||||
|
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 {
|
if let Some(file) = current_file {
|
||||||
editor
|
Command::new(cfg.editor.expect("Could not resolve editor from config"))
|
||||||
.args([file])
|
.args([file])
|
||||||
.status()
|
.status()
|
||||||
.expect(format!("failed to launch editor {}", "vim").as_str());
|
.expect(format!("failed to launch editor {}", "vim").as_str());
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
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> {
|
||||||
let options = &ComrakOptions {
|
let options = &ComrakOptions {
|
||||||
extension: ComrakExtensionOptions {
|
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)
|
parse_document(arena, contents, options)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn cleanup_sections<'a>(root: &'a AstNode<'a>, sections: &Vec<String>) -> Vec<String> {
|
fn extract_secitons<'a>(
|
||||||
let mut found_sections: Vec<String> = Vec::new();
|
root: &'a AstNode<'a>,
|
||||||
|
sections: &Vec<String>,
|
||||||
|
) -> HashMap<String, TaskGroup> {
|
||||||
|
let mut groups: HashMap<String, TaskGroup> = HashMap::new();
|
||||||
for node in root.reverse_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 < 3 {
|
if heading.level < 2 {
|
||||||
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() {
|
||||||
|
|
@ -152,27 +203,20 @@ fn cleanup_sections<'a>(root: &'a AstNode<'a>, sections: &Vec<String>) -> Vec<St
|
||||||
continue;
|
continue;
|
||||||
};
|
};
|
||||||
|
|
||||||
println!("checking {}", title);
|
println!("Attempting to parse {}", title);
|
||||||
if !sections.iter().any(|section| section.eq(title)) {
|
if sections.iter().any(|section| section.eq(title)) {
|
||||||
let level = heading.level;
|
if let Ok(mut group) = TaskGroup::try_from(node) {
|
||||||
println!("removing {}", title);
|
group.tasks = group
|
||||||
|
.tasks
|
||||||
let mut following = node.following_siblings();
|
.into_iter()
|
||||||
following.next(); // Skip self
|
.filter(|task| !matches!(task.status, TaskStatus::Done(_)))
|
||||||
for node in following {
|
.collect();
|
||||||
// remove everthing under this heading
|
groups.insert(title.to_string(), group);
|
||||||
match &node.data.borrow().value {
|
|
||||||
NodeValue::Heading(sub_heading) if sub_heading.level <= level => break,
|
|
||||||
_ => node.detach(),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
node.detach(); // remove heading as well
|
|
||||||
} else {
|
|
||||||
found_sections.push(title.to_string());
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
found_sections
|
groups
|
||||||
}
|
}
|
||||||
|
|
||||||
fn get_data_dir(dir_name: &str) -> PathBuf {
|
fn get_data_dir(dir_name: &str) -> PathBuf {
|
||||||
|
|
|
||||||
|
|
@ -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())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Loading…
Reference in New Issue