4 Commits

Author SHA1 Message Date
48df1fd9e0 v0.1.2 2024-03-18 22:02:46 -04:00
cfe9065243 using new file selection logic 2024-03-18 22:02:24 -04:00
c92da26ee7 cleanup 2024-03-18 20:20:18 -04:00
d3218ad907 getting latest file with window 2024-03-18 20:17:38 -04:00
7 changed files with 160 additions and 135 deletions

2
.gitignore vendored
View File

@@ -21,4 +21,4 @@ Cargo.lock
# config file
.rusty_task.json
Notes/

View File

@@ -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

View File

@@ -11,7 +11,13 @@ pub struct Args {
#[arg(short = 'C', long)]
pub current_config: bool,
/// veiw previous day's notes
/// 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,
}

View File

@@ -6,17 +6,11 @@ use comrak::nodes::{AstNode, NodeValue};
use comrak::parse_document;
use comrak::{Arena, ComrakExtensionOptions, ComrakOptions, ComrakParseOptions};
use std::collections::HashMap;
use std::fs::{read, read_dir, File};
use std::fs::{read, File};
use std::io::Write;
use std::path::{Path, PathBuf};
use std::path::PathBuf;
use std::str;
#[derive(Debug, Clone, PartialEq)]
pub struct DatedPathBuf {
path: PathBuf,
date: NaiveDate,
}
#[derive(Debug)]
pub enum FileNameParseError {
TypeConversionError(&'static str),
@@ -49,13 +43,13 @@ pub fn write_file(path: &PathBuf, content: &String) {
}
pub 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());
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.path().to_string_lossy()
file.file.to_string_lossy()
)
.as_str(),
)
@@ -117,94 +111,3 @@ pub fn extract_secitons<'a>(
}
groups
}
pub 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())
}
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 DatedPathBuf {
type Error = FileNameParseError;
fn try_from(path: PathBuf) -> Result<Self, Self::Error> {
Ok(Self {
date: try_get_date(&path)?,
path,
})
}
}
pub fn get_closest_files(files: &Vec<PathBuf>, target: NaiveDate, n: usize) -> Vec<DatedPathBuf> {
let mut dated_files = files
.clone()
.into_iter()
.filter_map(|file| DatedPathBuf::try_from(file).ok())
.collect::<Vec<_>>();
dated_files.sort_by_cached_key(|dated_file| (dated_file.date - target).num_days().abs());
dated_files[..n].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 = get_closest_files(&files, NaiveDate::from_ymd_opt(2023, 12, 30).unwrap(), 3);
let expected_res = vec![
DatedPathBuf::try_from(PathBuf::from("./2024-01-01.md")).unwrap(),
DatedPathBuf::try_from(PathBuf::from("./2024-01-02.md")).unwrap(),
DatedPathBuf::try_from(PathBuf::from("./2024-01-03.md")).unwrap(),
];
assert_eq!(res, expected_res);
let res = get_closest_files(&files, NaiveDate::from_ymd_opt(2024, 2, 1).unwrap(), 3);
let expected_res = vec![
DatedPathBuf::try_from(PathBuf::from("./2024-02-01.md")).unwrap(),
DatedPathBuf::try_from(PathBuf::from("./2024-01-03.md")).unwrap(),
DatedPathBuf::try_from(PathBuf::from("./2024-03-01.md")).unwrap(),
];
assert_eq!(res, expected_res);
let res = get_closest_files(&files, NaiveDate::from_ymd_opt(2024, 5, 2).unwrap(), 3);
let expected_res = vec![
DatedPathBuf::try_from(PathBuf::from("./2024-04-04.md")).unwrap(),
DatedPathBuf::try_from(PathBuf::from("./2024-04-03.md")).unwrap(),
DatedPathBuf::try_from(PathBuf::from("./2024-04-02.md")).unwrap(),
];
assert_eq!(res, expected_res);
}
}

View File

@@ -5,9 +5,9 @@ mod todo;
use crate::cli::Args;
use crate::config::Config;
use crate::todo::TaskGroup;
use crate::todo::{File as TodoFile, TaskGroup};
use chrono::naive::NaiveDate;
use chrono::{Datelike, Local};
use chrono::{Local, TimeDelta};
use clap::Parser;
use comrak::Arena;
use resolve_path::PathResolveExt;
@@ -17,7 +17,7 @@ use std::process::Command;
fn main() {
let args = Args::parse();
println!("previous = {}", args.previous);
println!("{:?}", args);
let expected_cfg_files = match Config::expected_locations() {
Ok(cfg_files) => cfg_files,
@@ -61,30 +61,45 @@ fn main() {
if !fs::metadata(&data_dir).is_ok() {
match fs::create_dir_all(&data_dir) {
Err(_e) => panic!("Could not create defult directory: {:?}", &data_dir),
Err(_e) => panic!("Could not create default directory: {:?}", &data_dir),
_ => (),
};
}
let latest_file = file::get_latest_file(&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 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 => {
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 sections = &cfg.sections;
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) {
@@ -98,7 +113,8 @@ fn main() {
file::write_file(&file_path, &content);
file_path
}
Err(_) => {
Some(todo_file) => todo_file.file.clone(),
None => {
let sections = &cfg.sections;
let data = sections
.iter()
@@ -109,7 +125,6 @@ fn main() {
file::write_file(&file_path, &content);
file_path
}
Ok(todo_file) => todo_file.file.path(),
};
Command::new(&cfg.editor)

View File

@@ -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);
}
}

View File

@@ -3,3 +3,4 @@ mod tasks;
pub use file::File;
pub use tasks::{Status, TaskGroup};