6 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
3b1485d2c0 getting closest file to date 2024-03-06 14:50:03 -05:00
e4be0fb471 cli arguments 2024-03-06 14:31:53 -05:00
7 changed files with 178 additions and 56 deletions

2
.gitignore vendored
View File

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

View File

@@ -1,6 +1,6 @@
[package] [package]
name = "rusty-tasks" name = "rusty-tasks"
version = "0.1.1" version = "0.1.2"
edition = "2021" edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

View File

@@ -10,4 +10,14 @@ pub struct Args {
/// show current config file /// show current config file
#[arg(short = 'C', long)] #[arg(short = 'C', long)]
pub current_config: bool, 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,
} }

View File

@@ -1,21 +1,26 @@
use chrono::Datelike; use crate::todo::{File as TodoFile, Status as TaskStatus};
use crate::TaskGroup;
use crate::NaiveDate; use crate::NaiveDate;
use crate::todo::{Status as TaskStatus,File as TodoFile}; use crate::TaskGroup;
use chrono::Datelike;
use comrak::nodes::{AstNode, NodeValue}; use comrak::nodes::{AstNode, NodeValue};
use comrak::{Arena, ComrakExtensionOptions, ComrakOptions, ComrakParseOptions};
use std::str;
use std::io::Write;
use std::collections::HashMap;
use comrak::parse_document; use comrak::parse_document;
use std::path::{Path, PathBuf}; use comrak::{Arena, ComrakExtensionOptions, ComrakOptions, ComrakParseOptions};
use std::fs::{read, read_dir, File}; 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 { pub fn get_filepath(data_dir: &PathBuf, date: &NaiveDate) -> PathBuf {
let file_name = format!("{}-{:02}-{:02}.md", date.year(), date.month(), date.day()); let file_name = format!("{}-{:02}-{:02}.md", date.year(), date.month(), date.day());
let mut file_path = data_dir.clone(); let mut file_path = data_dir.clone();
file_path.push(file_name); file_path.push(file_name);
file_path file_path
} }
@@ -38,13 +43,13 @@ pub fn write_file(path: &PathBuf, content: &String) {
} }
pub fn load_file(file: &TodoFile) -> String { pub fn load_file(file: &TodoFile) -> String {
let contents_utf8 = read(file.file.path()) let contents_utf8 = read(file.file.clone())
.expect(format!("Could not read file {}", file.file.path().to_string_lossy()).as_str()); .expect(format!("Could not read file {}", file.file.to_string_lossy()).as_str());
str::from_utf8(&contents_utf8) str::from_utf8(&contents_utf8)
.expect( .expect(
format!( format!(
"failed to convert contents of file to string: {}", "failed to convert contents of file to string: {}",
file.file.path().to_string_lossy() file.file.to_string_lossy()
) )
.as_str(), .as_str(),
) )
@@ -106,11 +111,3 @@ pub fn extract_secitons<'a>(
} }
groups 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())
}

View File

@@ -5,9 +5,9 @@ mod todo;
use crate::cli::Args; use crate::cli::Args;
use crate::config::Config; use crate::config::Config;
use crate::todo::TaskGroup; use crate::todo::{File as TodoFile, TaskGroup};
use chrono::naive::NaiveDate; use chrono::naive::NaiveDate;
use chrono::{Datelike, Local}; use chrono::{Local, TimeDelta};
use clap::Parser; use clap::Parser;
use comrak::Arena; use comrak::Arena;
use resolve_path::PathResolveExt; use resolve_path::PathResolveExt;
@@ -15,10 +15,9 @@ use std::fs;
use std::path::Path; use std::path::Path;
use std::process::Command; use std::process::Command;
//TODO refactor creating new file
fn main() { fn main() {
let args = Args::parse(); let args = Args::parse();
println!("{:?}", args);
let expected_cfg_files = match Config::expected_locations() { let expected_cfg_files = match Config::expected_locations() {
Ok(cfg_files) => cfg_files, Ok(cfg_files) => cfg_files,
@@ -62,30 +61,45 @@ fn main() {
if !fs::metadata(&data_dir).is_ok() { if !fs::metadata(&data_dir).is_ok() {
match fs::create_dir_all(&data_dir) { 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 = Local::now().date_naive();
let today = NaiveDate::from_ymd_opt(now.year(), now.month(), now.day()).unwrap(); 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 { 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 arena = Arena::new();
let root = { let root = {
let contents = file::load_file(&todo_file); let contents = file::load_file(&todo_file);
let root = file::parse_todo_file(&contents, &arena); let root = file::parse_todo_file(&contents, &arena);
root root
}; };
let sections = &cfg.sections;
let groups = file::extract_secitons(root, sections); let groups = file::extract_secitons(root, sections);
let level = groups.values().map(|group| group.level).min().unwrap_or(2); let level = groups.values().map(|group| group.level).min().unwrap_or(2);
let data = sections let data = sections
.iter() .iter()
.map(|section| match groups.get(section) { .map(|section| match groups.get(section) {
@@ -99,7 +113,8 @@ fn main() {
file::write_file(&file_path, &content); file::write_file(&file_path, &content);
file_path file_path
} }
Err(_) => { Some(todo_file) => todo_file.file.clone(),
None => {
let sections = &cfg.sections; let sections = &cfg.sections;
let data = sections let data = sections
.iter() .iter()
@@ -110,11 +125,10 @@ fn main() {
file::write_file(&file_path, &content); file::write_file(&file_path, &content);
file_path file_path
} }
Ok(todo_file) => todo_file.file.path(),
}; };
Command::new(cfg.editor) Command::new(&cfg.editor)
.args([current_file]) .args([current_file])
.status() .status()
.expect(format!("failed to launch editor {}", "vim").as_str()); .expect(format!("failed to launch editor {}", &cfg.editor).as_str());
} }

View File

@@ -1,18 +1,22 @@
use chrono::naive::NaiveDate; use chrono::naive::NaiveDate;
use regex::Regex; use regex::Regex;
use std::cmp::min;
use std::convert::TryFrom; use std::convert::TryFrom;
use std::fs::DirEntry; use std::fs::DirEntry;
use std::path::PathBuf;
use std::str::FromStr; use std::str::FromStr;
#[derive(Debug)] use crate::file::FileNameParseError;
#[derive(Debug, Clone, PartialEq)]
pub struct File { pub struct File {
pub file: DirEntry, pub file: PathBuf,
pub date: NaiveDate, pub date: NaiveDate,
} }
pub enum FileError{ pub enum FileError {
//IOError(&'static str), //IOError(&'static str),
ParseError(&'static str) ParseError(&'static str),
} }
impl File { impl File {
@@ -26,14 +30,6 @@ impl File {
.ok_or("Something went wrong".to_owned())?) .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 { fn get_file_regex() -> Regex {
//TODO This would ideally be configurable //TODO This would ideally be configurable
Regex::new(r"(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2}).md") Regex::new(r"(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2}).md")
@@ -46,13 +42,13 @@ impl TryFrom<DirEntry> for File {
fn try_from(direntry: DirEntry) -> Result<Self, Self::Error> { fn try_from(direntry: DirEntry) -> Result<Self, Self::Error> {
let re = File::get_file_regex(); let re = File::get_file_regex();
// println!("{:?}", re); // println!("{:?}", re);
let file_name = direntry.file_name(); let file_name = direntry.file_name();
let file_name_str = match file_name.to_str() { let file_name_str = match file_name.to_str() {
Some(name) => name, Some(name) => name,
_ => "", _ => "",
}; };
// println!("{:?}", file_name_str); // println!("{:?}", file_name_str);
if let Some(caps) = re.captures(file_name_str) { if let Some(caps) = re.captures(file_name_str) {
let year: i32 = Self::capture_as_number(&caps, "year").unwrap(); let year: i32 = Self::capture_as_number(&caps, "year").unwrap();
@@ -60,10 +56,114 @@ impl TryFrom<DirEntry> for File {
let day: u32 = Self::capture_as_number(&caps, "day").unwrap(); let day: u32 = Self::capture_as_number(&caps, "day").unwrap();
return Ok(Self { return Ok(Self {
file: direntry, file: direntry.path(),
date: NaiveDate::from_ymd_opt(year, month, day).unwrap(), date: NaiveDate::from_ymd_opt(year, month, day).unwrap(),
}); });
}; };
Err(FileError::ParseError("Could not parse file name")) 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 file::File;
pub use tasks::{Status, TaskGroup}; pub use tasks::{Status, TaskGroup};