Compare commits
10 Commits
05fb399530
...
v0.1.2
| Author | SHA1 | Date | |
|---|---|---|---|
| 48df1fd9e0 | |||
| cfe9065243 | |||
| c92da26ee7 | |||
| d3218ad907 | |||
| 3b1485d2c0 | |||
| e4be0fb471 | |||
| bce8f1e4b8 | |||
| e0c81885c8 | |||
| 1c51c53eef | |||
| 875ea1e53e |
2
.gitignore
vendored
2
.gitignore
vendored
@@ -21,4 +21,4 @@ Cargo.lock
|
||||
|
||||
# config file
|
||||
.rusty_task.json
|
||||
|
||||
Notes/
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "rusty-tasks"
|
||||
version = "0.1.1"
|
||||
version = "0.1.2"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
@@ -13,3 +13,4 @@ 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"
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use clap::{Parser, Subcommand};
|
||||
use clap::Parser;
|
||||
|
||||
#[derive(Parser, Debug)]
|
||||
#[command(version, about)]
|
||||
@@ -10,4 +10,14 @@ pub struct Args {
|
||||
/// 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,
|
||||
}
|
||||
|
||||
@@ -11,17 +11,17 @@ use std::path::PathBuf;
|
||||
|
||||
#[derive(Deserialize, Serialize, Debug)]
|
||||
pub struct Config {
|
||||
pub editor: Option<String>,
|
||||
pub sections: Option<Vec<String>>,
|
||||
pub notes_dir: Option<String>,
|
||||
pub editor: String,
|
||||
pub sections: Vec<String>,
|
||||
pub notes_dir: String,
|
||||
}
|
||||
|
||||
impl Default for Config {
|
||||
fn default() -> Self {
|
||||
Config {
|
||||
editor: Some("nano".into()),
|
||||
sections: Some(vec!["Daily".into(), "Weekly".into(), "Monthly".into()]),
|
||||
notes_dir: Some("Notes".into()),
|
||||
editor: "nano".into(),
|
||||
sections: vec!["Daily".into(), "Weekly".into(), "Monthly".into()],
|
||||
notes_dir: "~/Notes".into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -30,7 +30,7 @@ impl Default for Config {
|
||||
pub enum ConfigError {
|
||||
IOError(&'static str),
|
||||
ParseError(&'static str),
|
||||
EnvError(&'static str)
|
||||
EnvError(&'static str),
|
||||
}
|
||||
|
||||
impl Config {
|
||||
@@ -43,20 +43,31 @@ impl Config {
|
||||
}
|
||||
|
||||
pub fn write_default(cfg_file: &str) -> Result<(), ConfigError> {
|
||||
let buf = serde_json::to_string_pretty(&Self::default())
|
||||
.or_else(|_| return Err(ConfigError::ParseError("could not serialize default config")))?;
|
||||
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(|_| return Err(ConfigError::IOError("could not write default config to file")))?;
|
||||
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 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");
|
||||
|
||||
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
|
||||
}
|
||||
289
src/main.rs
289
src/main.rs
@@ -1,115 +1,105 @@
|
||||
mod cli;
|
||||
mod config;
|
||||
mod file;
|
||||
mod todo;
|
||||
|
||||
use crate::cli::Args;
|
||||
use clap::Parser;
|
||||
|
||||
use crate::config::Config;
|
||||
use crate::todo::File as TodoFile;
|
||||
use crate::todo::{Status as TaskStatus, TaskGroup};
|
||||
use crate::todo::{File as TodoFile, TaskGroup};
|
||||
use chrono::naive::NaiveDate;
|
||||
use chrono::{Datelike, Local};
|
||||
use comrak::nodes::{AstNode, NodeValue};
|
||||
use comrak::{parse_document, Arena};
|
||||
use comrak::{ComrakExtensionOptions, ComrakOptions, ComrakParseOptions};
|
||||
use std::borrow::Borrow;
|
||||
use std::collections::HashMap;
|
||||
use std::fs::{create_dir_all, metadata, read, read_dir, File};
|
||||
use std::io::{self, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
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;
|
||||
use std::{env, str};
|
||||
|
||||
//TODO handle unwraps and errors more uniformly
|
||||
//TODO refactor creating new file
|
||||
//TODO clean up verbose printing
|
||||
//TODO create custom errors for better error handling
|
||||
//TODO Default path for note_dir should start with curent path not home
|
||||
fn main() {
|
||||
let args = Args::parse();
|
||||
println!("{:?}", args);
|
||||
|
||||
#[derive(Debug)]
|
||||
enum ExitError {
|
||||
ConfigError(String),
|
||||
IOError(String, io::Error),
|
||||
}
|
||||
let expected_cfg_files = match Config::expected_locations() {
|
||||
Ok(cfg_files) => cfg_files,
|
||||
Err(e) => panic!("{:?}", e),
|
||||
};
|
||||
|
||||
fn main() -> Result<(), ExitError> {
|
||||
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))
|
||||
.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 {
|
||||
return Err(ExitError::ConfigError(format!(
|
||||
"Could not write to default cfg location: {:#?}",
|
||||
e
|
||||
)));
|
||||
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 cfg_files.last() {
|
||||
None => expected_cfg_files[0].to_str().unwrap(),
|
||||
Some(file) => file.to_str().unwrap(),
|
||||
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(),
|
||||
},
|
||||
};
|
||||
|
||||
let cfg = Config::load(cfg_file).unwrap();
|
||||
|
||||
println!("{:#?}", cfg);
|
||||
let data_dir = match &cfg.notes_dir {
|
||||
Some(dir) => get_data_dir(dir),
|
||||
_ => {
|
||||
return Err(ExitError::ConfigError(
|
||||
"Could not get notes dir from config".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),
|
||||
};
|
||||
|
||||
if !metadata(&data_dir).is_ok() {
|
||||
match create_dir_all(&data_dir) {
|
||||
Err(e) => {
|
||||
return Err(ExitError::IOError(
|
||||
format!(
|
||||
"Could not create defult directory: {}",
|
||||
&data_dir.to_str().unwrap(),
|
||||
),
|
||||
e,
|
||||
))
|
||||
}
|
||||
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),
|
||||
_ => (),
|
||||
};
|
||||
}
|
||||
println!("dir = {}", data_dir.to_str().unwrap());
|
||||
|
||||
let latest_file = get_latest_file(&data_dir);
|
||||
println!("Latest file: {:?}", latest_file);
|
||||
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 now = Local::now();
|
||||
let today = NaiveDate::from_ymd_opt(now.year(), now.month(), now.day()).unwrap();
|
||||
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 {
|
||||
Ok(todo_file) if todo_file.date < today => {
|
||||
println!("Today's file does not exist, creating");
|
||||
Some(todo_file) if todo_file.date < today && args.previous == 0 => {
|
||||
let sections = &cfg.sections;
|
||||
let arena = Arena::new();
|
||||
|
||||
let root = {
|
||||
let contents = load_file(&todo_file);
|
||||
let root = parse_todo_file(&contents, &arena);
|
||||
let contents = file::load_file(&todo_file);
|
||||
let root = file::parse_todo_file(&contents, &arena);
|
||||
root
|
||||
};
|
||||
|
||||
println!("{:#?}", root);
|
||||
println!("=======================================================");
|
||||
|
||||
let sections = &cfg.sections.unwrap();
|
||||
let groups = extract_secitons(root, sections);
|
||||
println!("{:#?}", groups);
|
||||
|
||||
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) {
|
||||
@@ -118,154 +108,27 @@ fn main() -> Result<(), ExitError> {
|
||||
})
|
||||
.collect();
|
||||
|
||||
// let new_file = write_file(&data_dir, &today, &data);
|
||||
|
||||
let content = generate_file_content(&data, &today);
|
||||
let file_path = get_filepath(&data_dir, &today);
|
||||
write_file(&file_path, &content);
|
||||
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
|
||||
}
|
||||
Err(_) => {
|
||||
println!("No files in dir: {:}", cfg.notes_dir.unwrap());
|
||||
let sections = &cfg.sections.unwrap();
|
||||
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 = generate_file_content(&data, &today);
|
||||
let file_path = get_filepath(&data_dir, &today);
|
||||
write_file(&file_path, &content);
|
||||
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
|
||||
}
|
||||
Ok(todo_file) => {
|
||||
println!("Today's file was created");
|
||||
todo_file.file.path()
|
||||
}
|
||||
};
|
||||
|
||||
Command::new(cfg.editor.expect("Could not resolve editor from config"))
|
||||
Command::new(&cfg.editor)
|
||||
.args([current_file])
|
||||
.status()
|
||||
.expect(format!("failed to launch editor {}", "vim").as_str());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
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}");
|
||||
}
|
||||
|
||||
fn load_file(file: &TodoFile) -> String {
|
||||
let contents_utf8 = read(file.file.path())
|
||||
.expect(format!("Could not read file {}", file.file.path().to_string_lossy()).as_str());
|
||||
str::from_utf8(&contents_utf8)
|
||||
.expect(
|
||||
format!(
|
||||
"failed to convert contents of file to string: {}",
|
||||
file.file.path().to_string_lossy()
|
||||
)
|
||||
.as_str(),
|
||||
)
|
||||
.to_string()
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
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.borrow() {
|
||||
child
|
||||
} else {
|
||||
continue;
|
||||
};
|
||||
|
||||
let data_ref = &first_child.data.borrow();
|
||||
let title = if let NodeValue::Text(value) = &data_ref.value {
|
||||
value
|
||||
} else {
|
||||
continue;
|
||||
};
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
groups
|
||||
}
|
||||
|
||||
fn get_data_dir(dir_name: &str) -> PathBuf {
|
||||
let mut dir = match env::var("HOME") {
|
||||
Ok(home) => {
|
||||
let mut x = PathBuf::new();
|
||||
x.push(home);
|
||||
x
|
||||
}
|
||||
_ => env::current_dir().expect("PWD environment variable not set"),
|
||||
};
|
||||
dir = dir.join(dir_name);
|
||||
dir
|
||||
}
|
||||
|
||||
fn get_latest_file(dir: &Path) -> Result<TodoFile, String> {
|
||||
let dir = read_dir(dir).expect(format!("Could not find notes folder: {:?}", dir).as_str());
|
||||
dir.filter_map(|f| f.ok())
|
||||
.filter_map(|file| TodoFile::try_from(file).ok())
|
||||
.reduce(|a, b| TodoFile::latest_file(a, b))
|
||||
.ok_or("Could not reduce items".to_string())
|
||||
.expect(format!("failed to launch editor {}", &cfg.editor).as_str());
|
||||
}
|
||||
|
||||
124
src/todo/file.rs
124
src/todo/file.rs
@@ -1,18 +1,22 @@
|
||||
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;
|
||||
|
||||
#[derive(Debug)]
|
||||
use crate::file::FileNameParseError;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct File {
|
||||
pub file: DirEntry,
|
||||
pub file: PathBuf,
|
||||
pub date: NaiveDate,
|
||||
}
|
||||
|
||||
pub enum FileError {
|
||||
//IOError(&'static str),
|
||||
ParseError(&'static str)
|
||||
ParseError(&'static str),
|
||||
}
|
||||
|
||||
impl File {
|
||||
@@ -26,14 +30,6 @@ impl File {
|
||||
.ok_or("Something went wrong".to_owned())?)
|
||||
}
|
||||
|
||||
pub fn latest_file(a: File, b: File) -> File {
|
||||
if a.date > b.date {
|
||||
a
|
||||
} else {
|
||||
b
|
||||
}
|
||||
}
|
||||
|
||||
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")
|
||||
@@ -60,10 +56,114 @@ impl TryFrom<DirEntry> for File {
|
||||
let day: u32 = Self::capture_as_number(&caps, "day").unwrap();
|
||||
|
||||
return Ok(Self {
|
||||
file: direntry,
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,4 +2,5 @@ mod file;
|
||||
mod tasks;
|
||||
|
||||
pub use file::File;
|
||||
pub use tasks::{Status, Task, TaskGroup};
|
||||
pub use tasks::{Status, TaskGroup};
|
||||
|
||||
|
||||
@@ -163,7 +163,7 @@ impl<'a> TryFrom<&'a AstNode<'a>> for TaskGroup {
|
||||
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() {
|
||||
let first_child = if let Some(child) = first_child_ref {
|
||||
child
|
||||
} else {
|
||||
return Err(TaskError::ParsingError("Node has no children"));
|
||||
|
||||
Reference in New Issue
Block a user