Compare commits
44 Commits
c6925d9a8d
...
v0.1.2
| Author | SHA1 | Date | |
|---|---|---|---|
| 48df1fd9e0 | |||
| cfe9065243 | |||
| c92da26ee7 | |||
| d3218ad907 | |||
| 3b1485d2c0 | |||
| e4be0fb471 | |||
| bce8f1e4b8 | |||
| e0c81885c8 | |||
| 1c51c53eef | |||
| 875ea1e53e | |||
| 05fb399530 | |||
| 695e31c7e4 | |||
| 62617473bd | |||
| f6e9bac0e3 | |||
| 6958375f6c | |||
| 85d81c02cc | |||
| e90ec3e647 | |||
| ad557e822f | |||
| ea7cd57c07 | |||
| cd97c18fef | |||
| 3bb095ca45 | |||
| 16a2646cb8 | |||
| 86750a7428 | |||
| c78071d132 | |||
| 1382482faa | |||
| 75d8b80dd7 | |||
| d4688d199b | |||
| 7a6ed10e23 | |||
| 02ed04fad5 | |||
| 145905066c | |||
| 34c9ceac86 | |||
| 061afcf9cd | |||
| 0fdef6ed6e | |||
| fffb3aebfe | |||
| 6fccb02d3f | |||
| 0dce3e8ab9 | |||
| 35d5467d03 | |||
| 2caa88ad43 | |||
| ff25155aed | |||
| 5ba22cb6c9 | |||
| 9c96744bda | |||
| 175a6c20a8 | |||
| 679acf1064 | |||
| dd2880aa75 |
10
.gitignore
vendored
10
.gitignore
vendored
@@ -12,3 +12,13 @@ Cargo.lock
|
|||||||
|
|
||||||
# MSVC Windows builds of rustc generate these, which store debugging information
|
# MSVC Windows builds of rustc generate these, which store debugging information
|
||||||
*.pdb
|
*.pdb
|
||||||
|
|
||||||
|
|
||||||
|
# Added by cargo
|
||||||
|
|
||||||
|
/target
|
||||||
|
|
||||||
|
|
||||||
|
# config file
|
||||||
|
.rusty_task.json
|
||||||
|
Notes/
|
||||||
|
|||||||
16
Cargo.toml
Normal file
16
Cargo.toml
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
[package]
|
||||||
|
name = "rusty-tasks"
|
||||||
|
version = "0.1.2"
|
||||||
|
edition = "2021"
|
||||||
|
|
||||||
|
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
chrono = "0.4.26"
|
||||||
|
clap = { version = "4.5.1", features = ["derive"] }
|
||||||
|
comrak = "0.18.0"
|
||||||
|
figment = { version = "0.10.10", features = ["env", "serde_json", "json"] }
|
||||||
|
regex = "1.8.4"
|
||||||
|
serde = { version = "1.0.164", features = ["serde_derive"] }
|
||||||
|
serde_json = "1.0.97"
|
||||||
|
resolve-path = "0.1.0"
|
||||||
24
README.md
24
README.md
@@ -1,2 +1,26 @@
|
|||||||
# Rusty-tasks
|
# Rusty-tasks
|
||||||
A rewrite of an older CLI todo system without python and regex
|
A rewrite of an older CLI todo system without python and regex
|
||||||
|
|
||||||
|
## Goals
|
||||||
|
|
||||||
|
- [ ] BLAZING FAST!
|
||||||
|
- [ ] replace python with rust
|
||||||
|
- [ ] replace regex with a markdown parsing library
|
||||||
|
- [ ] learn some rust along the way
|
||||||
|
|
||||||
|
## Ideas
|
||||||
|
|
||||||
|
If you've used the bullet journal technique before, think if this as the
|
||||||
|
digital, automated version of that.
|
||||||
|
|
||||||
|
- Accessible from anywhere in the terminal (TMUX, bare shell, etc)
|
||||||
|
* works really well with a drop-down terminal
|
||||||
|
- Takes advantage of default editor (vim, emacs, etc)
|
||||||
|
- Take advantage of Markdown for formatting
|
||||||
|
- Organize tasks at different levels of urgency
|
||||||
|
* Daily - Must get done now
|
||||||
|
* Weekly - Must get done in the near future
|
||||||
|
* Monthly - I'm going to forget if I don't write it down but It's a ways away
|
||||||
|
- Every day start a new file
|
||||||
|
* files should be dated
|
||||||
|
- Carry over uncompleted tasks from previous day
|
||||||
|
|||||||
23
src/cli/mod.rs
Normal file
23
src/cli/mod.rs
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
use clap::Parser;
|
||||||
|
|
||||||
|
#[derive(Parser, Debug)]
|
||||||
|
#[command(version, about)]
|
||||||
|
pub struct Args {
|
||||||
|
/// set config file to use
|
||||||
|
#[arg(short, long, value_name = "FILE")]
|
||||||
|
pub config: Option<String>,
|
||||||
|
|
||||||
|
/// show current config file
|
||||||
|
#[arg(short = 'C', long)]
|
||||||
|
pub current_config: bool,
|
||||||
|
|
||||||
|
/// view previous day's notes
|
||||||
|
#[arg(short = 'p', long, default_value_t = 0)]
|
||||||
|
pub previous: u16,
|
||||||
|
/// list closest files to date
|
||||||
|
#[arg(short, long)]
|
||||||
|
pub list: bool,
|
||||||
|
/// list closest files to date
|
||||||
|
#[arg(short = 'L', long)]
|
||||||
|
pub list_all: bool,
|
||||||
|
}
|
||||||
84
src/config/mod.rs
Normal file
84
src/config/mod.rs
Normal file
@@ -0,0 +1,84 @@
|
|||||||
|
extern crate serde;
|
||||||
|
extern crate serde_json;
|
||||||
|
|
||||||
|
use figment::providers::{Env, Format, Json, Serialized};
|
||||||
|
use figment::Figment;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use std::env::var;
|
||||||
|
use std::fs::File;
|
||||||
|
use std::io::Write;
|
||||||
|
use std::path::PathBuf;
|
||||||
|
|
||||||
|
#[derive(Deserialize, Serialize, Debug)]
|
||||||
|
pub struct Config {
|
||||||
|
pub editor: String,
|
||||||
|
pub sections: Vec<String>,
|
||||||
|
pub notes_dir: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for Config {
|
||||||
|
fn default() -> Self {
|
||||||
|
Config {
|
||||||
|
editor: "nano".into(),
|
||||||
|
sections: vec!["Daily".into(), "Weekly".into(), "Monthly".into()],
|
||||||
|
notes_dir: "~/Notes".into(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub enum ConfigError {
|
||||||
|
IOError(&'static str),
|
||||||
|
ParseError(&'static str),
|
||||||
|
EnvError(&'static str),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Config {
|
||||||
|
pub fn load(cfg_file: &str) -> Result<Self, ConfigError> {
|
||||||
|
Figment::from(Serialized::defaults(Config::default()))
|
||||||
|
.merge(Env::raw().only(&["EDITOR"]))
|
||||||
|
.merge(Json::file(cfg_file))
|
||||||
|
.extract()
|
||||||
|
.or(Err(ConfigError::IOError("Could not load config")))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn write_default(cfg_file: &str) -> Result<(), ConfigError> {
|
||||||
|
let buf = serde_json::to_string_pretty(&Self::default()).or_else(|_| {
|
||||||
|
Err(ConfigError::ParseError(
|
||||||
|
"could not serialize default config",
|
||||||
|
))
|
||||||
|
})?;
|
||||||
|
|
||||||
|
let mut f = File::create(cfg_file)
|
||||||
|
.or_else(|_| Err(ConfigError::IOError("Could not open config file")))?;
|
||||||
|
f.write_all(&buf.as_bytes()).or_else(|_| {
|
||||||
|
Err(ConfigError::IOError(
|
||||||
|
"could not write default config to file",
|
||||||
|
))
|
||||||
|
})?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn expected_locations() -> Result<Vec<PathBuf>, ConfigError> {
|
||||||
|
let cfg_name = "rusty_task.json";
|
||||||
|
let home = var("HOME").or(Err(ConfigError::EnvError(
|
||||||
|
"$HOME environment variable not set",
|
||||||
|
)))?;
|
||||||
|
let pwd = var("PWD").or(Err(ConfigError::EnvError(
|
||||||
|
"$PWD environment variable not set",
|
||||||
|
)))?;
|
||||||
|
|
||||||
|
let mut home_config_cfg = PathBuf::from(home.clone());
|
||||||
|
home_config_cfg.push(".config");
|
||||||
|
home_config_cfg.push(cfg_name);
|
||||||
|
|
||||||
|
let mut home_cfg = PathBuf::from(home.clone());
|
||||||
|
home_cfg.push(format!(".{}", cfg_name));
|
||||||
|
|
||||||
|
let mut pwd_cfg = PathBuf::from(pwd.clone());
|
||||||
|
pwd_cfg.push(format!(".{}", cfg_name));
|
||||||
|
|
||||||
|
Ok(vec![home_config_cfg, home_cfg, pwd_cfg])
|
||||||
|
}
|
||||||
|
}
|
||||||
113
src/file/mod.rs
Normal file
113
src/file/mod.rs
Normal file
@@ -0,0 +1,113 @@
|
|||||||
|
use crate::todo::{File as TodoFile, Status as TaskStatus};
|
||||||
|
use crate::NaiveDate;
|
||||||
|
use crate::TaskGroup;
|
||||||
|
use chrono::Datelike;
|
||||||
|
use comrak::nodes::{AstNode, NodeValue};
|
||||||
|
use comrak::parse_document;
|
||||||
|
use comrak::{Arena, ComrakExtensionOptions, ComrakOptions, ComrakParseOptions};
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::fs::{read, File};
|
||||||
|
use std::io::Write;
|
||||||
|
use std::path::PathBuf;
|
||||||
|
use std::str;
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub enum FileNameParseError {
|
||||||
|
TypeConversionError(&'static str),
|
||||||
|
ParseError(chrono::ParseError),
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_filepath(data_dir: &PathBuf, date: &NaiveDate) -> PathBuf {
|
||||||
|
let file_name = format!("{}-{:02}-{:02}.md", date.year(), date.month(), date.day());
|
||||||
|
let mut file_path = data_dir.clone();
|
||||||
|
file_path.push(file_name);
|
||||||
|
file_path
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn generate_file_content(data: &Vec<TaskGroup>, date: &NaiveDate) -> String {
|
||||||
|
let mut content = format!(
|
||||||
|
"# Today's tasks {}-{:02}-{:02}\n",
|
||||||
|
date.year(),
|
||||||
|
date.month(),
|
||||||
|
date.day()
|
||||||
|
);
|
||||||
|
data.iter()
|
||||||
|
.for_each(|task_group| content.push_str(format!("\n{}", task_group.to_string()).as_str()));
|
||||||
|
|
||||||
|
content
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn write_file(path: &PathBuf, content: &String) {
|
||||||
|
let mut new_file = File::create(&path).expect("Could not open today's file: {today_file_path}");
|
||||||
|
write!(new_file, "{}", content).expect("Could not write to file: {today_file_path}");
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn load_file(file: &TodoFile) -> String {
|
||||||
|
let contents_utf8 = read(file.file.clone())
|
||||||
|
.expect(format!("Could not read file {}", file.file.to_string_lossy()).as_str());
|
||||||
|
str::from_utf8(&contents_utf8)
|
||||||
|
.expect(
|
||||||
|
format!(
|
||||||
|
"failed to convert contents of file to string: {}",
|
||||||
|
file.file.to_string_lossy()
|
||||||
|
)
|
||||||
|
.as_str(),
|
||||||
|
)
|
||||||
|
.to_string()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn parse_todo_file<'a>(contents: &String, arena: &'a Arena<AstNode<'a>>) -> &'a AstNode<'a> {
|
||||||
|
let options = &ComrakOptions {
|
||||||
|
extension: ComrakExtensionOptions {
|
||||||
|
tasklist: true,
|
||||||
|
..ComrakExtensionOptions::default()
|
||||||
|
},
|
||||||
|
parse: ComrakParseOptions {
|
||||||
|
relaxed_tasklist_matching: true,
|
||||||
|
..ComrakParseOptions::default()
|
||||||
|
},
|
||||||
|
..ComrakOptions::default()
|
||||||
|
};
|
||||||
|
parse_document(arena, contents, options)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub 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 < 2 {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
let first_child_ref = &node.first_child();
|
||||||
|
let first_child = if let Some(child) = first_child_ref {
|
||||||
|
child
|
||||||
|
} else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
|
||||||
|
let data_ref = &first_child.data.borrow();
|
||||||
|
let title = if let NodeValue::Text(value) = &data_ref.value {
|
||||||
|
value
|
||||||
|
} else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
groups
|
||||||
|
}
|
||||||
134
src/main.rs
Normal file
134
src/main.rs
Normal file
@@ -0,0 +1,134 @@
|
|||||||
|
mod cli;
|
||||||
|
mod config;
|
||||||
|
mod file;
|
||||||
|
mod todo;
|
||||||
|
|
||||||
|
use crate::cli::Args;
|
||||||
|
use crate::config::Config;
|
||||||
|
use crate::todo::{File as TodoFile, TaskGroup};
|
||||||
|
use chrono::naive::NaiveDate;
|
||||||
|
use chrono::{Local, TimeDelta};
|
||||||
|
use clap::Parser;
|
||||||
|
use comrak::Arena;
|
||||||
|
use resolve_path::PathResolveExt;
|
||||||
|
use std::fs;
|
||||||
|
use std::path::Path;
|
||||||
|
use std::process::Command;
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
let args = Args::parse();
|
||||||
|
println!("{:?}", args);
|
||||||
|
|
||||||
|
let expected_cfg_files = match Config::expected_locations() {
|
||||||
|
Ok(cfg_files) => cfg_files,
|
||||||
|
Err(e) => panic!("{:?}", e),
|
||||||
|
};
|
||||||
|
|
||||||
|
let cfg_files: Vec<&Path> = expected_cfg_files
|
||||||
|
.iter()
|
||||||
|
.map(|file| Path::new(file))
|
||||||
|
.filter(|file| file.exists())
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
if cfg_files.len() <= 0 {
|
||||||
|
if let Err(e) = Config::write_default(match expected_cfg_files[0].to_str() {
|
||||||
|
Some(s) => s,
|
||||||
|
None => panic!("Could not resolve expected cfg file paths"),
|
||||||
|
}) {
|
||||||
|
panic!("Could not write config: {:?}", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let cfg_file = match args.config {
|
||||||
|
Some(file) => file,
|
||||||
|
None => match cfg_files.last() {
|
||||||
|
None => expected_cfg_files[0].to_string_lossy().to_string(),
|
||||||
|
Some(file) => file.to_string_lossy().to_string(),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
if args.current_config {
|
||||||
|
println!("{}", &cfg_file);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let cfg = match Config::load(&cfg_file) {
|
||||||
|
Ok(cfg) => cfg,
|
||||||
|
Err(_e) => panic!("could not load config: {}", cfg_file),
|
||||||
|
};
|
||||||
|
|
||||||
|
let data_dir = cfg.notes_dir.resolve().to_path_buf();
|
||||||
|
|
||||||
|
if !fs::metadata(&data_dir).is_ok() {
|
||||||
|
match fs::create_dir_all(&data_dir) {
|
||||||
|
Err(_e) => panic!("Could not create default directory: {:?}", &data_dir),
|
||||||
|
_ => (),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
let files = fs::read_dir(&data_dir)
|
||||||
|
.expect(format!("Could not find notes folder: {:?}", &data_dir).as_str())
|
||||||
|
.filter_map(|f| f.ok())
|
||||||
|
.map(|file| file.path());
|
||||||
|
if args.list_all {
|
||||||
|
files
|
||||||
|
.into_iter()
|
||||||
|
.for_each(|f| println!("{}", f.canonicalize().unwrap().to_string_lossy()));
|
||||||
|
return ();
|
||||||
|
}
|
||||||
|
|
||||||
|
let today = Local::now().date_naive();
|
||||||
|
let target = today - TimeDelta::try_days(args.previous.into()).unwrap();
|
||||||
|
let closest_files = TodoFile::get_closest_files(files.collect(), target, 5);
|
||||||
|
if args.list {
|
||||||
|
closest_files
|
||||||
|
.into_iter()
|
||||||
|
.for_each(|f| println!("{}", f.file.canonicalize().unwrap().to_string_lossy()));
|
||||||
|
return ();
|
||||||
|
}
|
||||||
|
|
||||||
|
let latest_file = closest_files.first();
|
||||||
|
let current_file = match latest_file {
|
||||||
|
Some(todo_file) if todo_file.date < today && args.previous == 0 => {
|
||||||
|
let sections = &cfg.sections;
|
||||||
|
let arena = Arena::new();
|
||||||
|
|
||||||
|
let root = {
|
||||||
|
let contents = file::load_file(&todo_file);
|
||||||
|
let root = file::parse_todo_file(&contents, &arena);
|
||||||
|
root
|
||||||
|
};
|
||||||
|
let groups = file::extract_secitons(root, sections);
|
||||||
|
let level = groups.values().map(|group| group.level).min().unwrap_or(2);
|
||||||
|
let data = sections
|
||||||
|
.iter()
|
||||||
|
.map(|section| match groups.get(section) {
|
||||||
|
Some(group) => group.clone(),
|
||||||
|
None => TaskGroup::empty(section.to_string(), level),
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
let content = file::generate_file_content(&data, &today);
|
||||||
|
let file_path = file::get_filepath(&data_dir, &today);
|
||||||
|
file::write_file(&file_path, &content);
|
||||||
|
file_path
|
||||||
|
}
|
||||||
|
Some(todo_file) => todo_file.file.clone(),
|
||||||
|
None => {
|
||||||
|
let sections = &cfg.sections;
|
||||||
|
let data = sections
|
||||||
|
.iter()
|
||||||
|
.map(|sec| TaskGroup::empty(sec.clone(), 2))
|
||||||
|
.collect();
|
||||||
|
let content = file::generate_file_content(&data, &today);
|
||||||
|
let file_path = file::get_filepath(&data_dir, &today);
|
||||||
|
file::write_file(&file_path, &content);
|
||||||
|
file_path
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
Command::new(&cfg.editor)
|
||||||
|
.args([current_file])
|
||||||
|
.status()
|
||||||
|
.expect(format!("failed to launch editor {}", &cfg.editor).as_str());
|
||||||
|
}
|
||||||
169
src/todo/file.rs
Normal file
169
src/todo/file.rs
Normal file
@@ -0,0 +1,169 @@
|
|||||||
|
use chrono::naive::NaiveDate;
|
||||||
|
use regex::Regex;
|
||||||
|
use std::cmp::min;
|
||||||
|
use std::convert::TryFrom;
|
||||||
|
use std::fs::DirEntry;
|
||||||
|
use std::path::PathBuf;
|
||||||
|
use std::str::FromStr;
|
||||||
|
|
||||||
|
use crate::file::FileNameParseError;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq)]
|
||||||
|
pub struct File {
|
||||||
|
pub file: PathBuf,
|
||||||
|
pub date: NaiveDate,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub enum FileError {
|
||||||
|
//IOError(&'static str),
|
||||||
|
ParseError(&'static str),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl File {
|
||||||
|
fn capture_as_number<T: FromStr>(capture: ®ex::Captures, name: &str) -> Result<T, String> {
|
||||||
|
Ok(capture
|
||||||
|
.name(name)
|
||||||
|
.unwrap()
|
||||||
|
.as_str()
|
||||||
|
.parse::<T>()
|
||||||
|
.ok()
|
||||||
|
.ok_or("Something went wrong".to_owned())?)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_file_regex() -> Regex {
|
||||||
|
//TODO This would ideally be configurable
|
||||||
|
Regex::new(r"(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2}).md")
|
||||||
|
.expect("could not create regex")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TryFrom<DirEntry> for File {
|
||||||
|
type Error = FileError;
|
||||||
|
|
||||||
|
fn try_from(direntry: DirEntry) -> Result<Self, Self::Error> {
|
||||||
|
let re = File::get_file_regex();
|
||||||
|
// println!("{:?}", re);
|
||||||
|
let file_name = direntry.file_name();
|
||||||
|
let file_name_str = match file_name.to_str() {
|
||||||
|
Some(name) => name,
|
||||||
|
_ => "",
|
||||||
|
};
|
||||||
|
// println!("{:?}", file_name_str);
|
||||||
|
|
||||||
|
if let Some(caps) = re.captures(file_name_str) {
|
||||||
|
let year: i32 = Self::capture_as_number(&caps, "year").unwrap();
|
||||||
|
let month: u32 = Self::capture_as_number(&caps, "month").unwrap();
|
||||||
|
let day: u32 = Self::capture_as_number(&caps, "day").unwrap();
|
||||||
|
|
||||||
|
return Ok(Self {
|
||||||
|
file: direntry.path(),
|
||||||
|
date: NaiveDate::from_ymd_opt(year, month, day).unwrap(),
|
||||||
|
});
|
||||||
|
};
|
||||||
|
Err(FileError::ParseError("Could not parse file name"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn try_get_date(file: &PathBuf) -> Result<NaiveDate, FileNameParseError> {
|
||||||
|
let file_name = file
|
||||||
|
.file_name()
|
||||||
|
.ok_or(FileNameParseError::TypeConversionError(
|
||||||
|
"Could not get filename from path: {:?}",
|
||||||
|
))?
|
||||||
|
.to_str()
|
||||||
|
.ok_or(FileNameParseError::TypeConversionError(
|
||||||
|
"Could not get filename from path: {:?}",
|
||||||
|
))?;
|
||||||
|
|
||||||
|
NaiveDate::parse_from_str(file_name, "%Y-%m-%d.md")
|
||||||
|
.or_else(|e| Err(FileNameParseError::ParseError(e)))
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TryFrom<PathBuf> for File {
|
||||||
|
type Error = FileNameParseError;
|
||||||
|
|
||||||
|
fn try_from(path: PathBuf) -> Result<Self, Self::Error> {
|
||||||
|
Ok(Self {
|
||||||
|
date: try_get_date(&path)?,
|
||||||
|
file: path.into(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl File {
|
||||||
|
pub fn get_closest_files(files: Vec<PathBuf>, target: NaiveDate, n: usize) -> Vec<File> {
|
||||||
|
let mut dated_files = files
|
||||||
|
.into_iter()
|
||||||
|
.filter_map(|file| File::try_from(file).ok())
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
dated_files.sort_by_cached_key(|dated_file| (dated_file.date - target).num_days().abs());
|
||||||
|
|
||||||
|
let count = min(n, dated_files.len());
|
||||||
|
dated_files[..count].to_vec()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod test {
|
||||||
|
use super::*;
|
||||||
|
use chrono::NaiveDate;
|
||||||
|
use std::path::PathBuf;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_get_closest_date() {
|
||||||
|
let files = vec![
|
||||||
|
PathBuf::from("./2024-01-01.md"),
|
||||||
|
PathBuf::from("./2024-01-02.md"),
|
||||||
|
PathBuf::from("./2024-01-03.md"),
|
||||||
|
PathBuf::from("./2024-02-01.md"),
|
||||||
|
PathBuf::from("./2024-03-01.md"),
|
||||||
|
PathBuf::from("./2024-04-01.md"),
|
||||||
|
PathBuf::from("./2024-04-02.md"),
|
||||||
|
PathBuf::from("./2024-04-03.md"),
|
||||||
|
PathBuf::from("./2024-04-04.md"),
|
||||||
|
];
|
||||||
|
|
||||||
|
let res = File::get_closest_files(
|
||||||
|
files.clone(),
|
||||||
|
NaiveDate::from_ymd_opt(2023, 12, 30).unwrap(),
|
||||||
|
3,
|
||||||
|
);
|
||||||
|
let expected_res = vec![
|
||||||
|
File::try_from(PathBuf::from("./2024-01-01.md")).unwrap(),
|
||||||
|
File::try_from(PathBuf::from("./2024-01-02.md")).unwrap(),
|
||||||
|
File::try_from(PathBuf::from("./2024-01-03.md")).unwrap(),
|
||||||
|
];
|
||||||
|
assert_eq!(res, expected_res);
|
||||||
|
|
||||||
|
let res = File::get_closest_files(
|
||||||
|
files.clone(),
|
||||||
|
NaiveDate::from_ymd_opt(2024, 2, 1).unwrap(),
|
||||||
|
3,
|
||||||
|
);
|
||||||
|
let expected_res = vec![
|
||||||
|
File::try_from(PathBuf::from("./2024-02-01.md")).unwrap(),
|
||||||
|
File::try_from(PathBuf::from("./2024-01-03.md")).unwrap(),
|
||||||
|
File::try_from(PathBuf::from("./2024-03-01.md")).unwrap(),
|
||||||
|
];
|
||||||
|
assert_eq!(res, expected_res);
|
||||||
|
|
||||||
|
let res = File::get_closest_files(
|
||||||
|
files.clone(),
|
||||||
|
NaiveDate::from_ymd_opt(2024, 5, 2).unwrap(),
|
||||||
|
3,
|
||||||
|
);
|
||||||
|
let expected_res = vec![
|
||||||
|
File::try_from(PathBuf::from("./2024-04-04.md")).unwrap(),
|
||||||
|
File::try_from(PathBuf::from("./2024-04-03.md")).unwrap(),
|
||||||
|
File::try_from(PathBuf::from("./2024-04-02.md")).unwrap(),
|
||||||
|
];
|
||||||
|
assert_eq!(res, expected_res);
|
||||||
|
|
||||||
|
let res = File::get_closest_files(
|
||||||
|
files[..1].to_vec(),
|
||||||
|
NaiveDate::from_ymd_opt(2023, 12, 30).unwrap(),
|
||||||
|
3,
|
||||||
|
);
|
||||||
|
let expected_res = vec![File::try_from(PathBuf::from("./2024-01-01.md")).unwrap()];
|
||||||
|
assert_eq!(res, expected_res);
|
||||||
|
}
|
||||||
|
}
|
||||||
6
src/todo/mod.rs
Normal file
6
src/todo/mod.rs
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
mod file;
|
||||||
|
mod tasks;
|
||||||
|
|
||||||
|
pub use file::File;
|
||||||
|
pub use tasks::{Status, TaskGroup};
|
||||||
|
|
||||||
202
src/todo/tasks.rs
Normal file
202
src/todo/tasks.rs
Normal file
@@ -0,0 +1,202 @@
|
|||||||
|
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,
|
||||||
|
pub subtasks: Option<Vec<Task>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, PartialEq, Clone)]
|
||||||
|
pub enum Status {
|
||||||
|
Done(char),
|
||||||
|
Todo(char),
|
||||||
|
Empty,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub enum TaskError {
|
||||||
|
ParsingError(&'static str),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Task {
|
||||||
|
fn extract_text<'a>(node: &'a AstNode<'a>) -> Result<String, TaskError> {
|
||||||
|
let data_ref = node.data.borrow();
|
||||||
|
if let NodeValue::Text(contents) = &data_ref.value {
|
||||||
|
Ok(contents.to_string())
|
||||||
|
} else {
|
||||||
|
Err(TaskError::ParsingError("Could not get text from element"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn extract_text_from_task<'a>(node: &'a AstNode<'a>) -> Result<String, TaskError> {
|
||||||
|
let mut text = String::new();
|
||||||
|
let data_ref = node.data.borrow();
|
||||||
|
if let NodeValue::Paragraph = data_ref.value {
|
||||||
|
for child in node.children() {
|
||||||
|
let child_data_ref = child.data.borrow();
|
||||||
|
let t = match &child_data_ref.borrow().value {
|
||||||
|
NodeValue::Text(contents) => contents.clone(),
|
||||||
|
NodeValue::Emph if child.first_child().is_some() => {
|
||||||
|
format!("*{}*", Self::extract_text(child.first_child().unwrap())?)
|
||||||
|
}
|
||||||
|
NodeValue::Strong if child.first_child().is_some() => {
|
||||||
|
format!("**{}**", Self::extract_text(child.first_child().unwrap())?)
|
||||||
|
}
|
||||||
|
NodeValue::SoftBreak => {
|
||||||
|
format!("\n{}", " ".repeat(data_ref.sourcepos.start.column))
|
||||||
|
}
|
||||||
|
_ => "".into(),
|
||||||
|
};
|
||||||
|
text.push_str(&t);
|
||||||
|
}
|
||||||
|
Ok(text)
|
||||||
|
} else {
|
||||||
|
Err(TaskError::ParsingError("First child is not Paragraph"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ToString for Task {
|
||||||
|
fn to_string(&self) -> String {
|
||||||
|
let ch = match self.status {
|
||||||
|
Status::Done(ch) => ch,
|
||||||
|
Status::Todo(ch) => ch,
|
||||||
|
Status::Empty => ' ',
|
||||||
|
};
|
||||||
|
|
||||||
|
let subtasks = if let Some(subtasks) = &self.subtasks {
|
||||||
|
let text = subtasks
|
||||||
|
.iter()
|
||||||
|
.map(|task| task.to_string())
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join("\n");
|
||||||
|
format!("\n{}", text).trim_end().replace("\n", "\n ")
|
||||||
|
} else {
|
||||||
|
"".into()
|
||||||
|
};
|
||||||
|
|
||||||
|
format!("- [{}] {}{}\n", ch, self.text.trim(), subtasks)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> TryFrom<&'a AstNode<'a>> for Task {
|
||||||
|
type Error = TaskError;
|
||||||
|
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::extract_text_from_task(
|
||||||
|
node.first_child()
|
||||||
|
.ok_or(TaskError::ParsingError("No childern of node found"))?,
|
||||||
|
)?;
|
||||||
|
let status = match ch {
|
||||||
|
Some(c) if c == 'x' || c == 'X' => Status::Done(c),
|
||||||
|
Some(c) => Status::Todo(c),
|
||||||
|
_ => Status::Empty,
|
||||||
|
};
|
||||||
|
let subtasks = node
|
||||||
|
.children()
|
||||||
|
.filter_map(|child| {
|
||||||
|
if let NodeValue::List(_) = child.data.borrow().value {
|
||||||
|
Some(child)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.map(|child| {
|
||||||
|
child
|
||||||
|
.children()
|
||||||
|
.into_iter()
|
||||||
|
.filter_map(|item_node| Task::try_from(item_node).ok())
|
||||||
|
.collect()
|
||||||
|
})
|
||||||
|
.reduce(|a: Vec<Task>, b: Vec<Task>| [a, b].concat());
|
||||||
|
|
||||||
|
Ok(Self {
|
||||||
|
status,
|
||||||
|
text,
|
||||||
|
subtasks,
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
Err(TaskError::ParsingError(
|
||||||
|
"Node being parsed is not a TaskItem",
|
||||||
|
))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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 = TaskError;
|
||||||
|
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 {
|
||||||
|
child
|
||||||
|
} else {
|
||||||
|
return Err(TaskError::ParsingError("Node has no children"));
|
||||||
|
};
|
||||||
|
|
||||||
|
let data_ref = &first_child.data.borrow();
|
||||||
|
let name = if let NodeValue::Text(value) = &data_ref.value {
|
||||||
|
value.to_string()
|
||||||
|
} else {
|
||||||
|
return Err(TaskError::ParsingError(
|
||||||
|
"Could not get title from heading node",
|
||||||
|
));
|
||||||
|
};
|
||||||
|
|
||||||
|
let next_sib = node
|
||||||
|
.next_sibling()
|
||||||
|
.ok_or(TaskError::ParsingError("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(TaskError::ParsingError(
|
||||||
|
"Next sibling of node is not a list",
|
||||||
|
))
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Err(TaskError::ParsingError("Node is not a section heading"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user