Compare commits
6 Commits
bce8f1e4b8
...
v0.1.2
| Author | SHA1 | Date | |
|---|---|---|---|
| 48df1fd9e0 | |||
| cfe9065243 | |||
| c92da26ee7 | |||
| d3218ad907 | |||
| 3b1485d2c0 | |||
| e4be0fb471 |
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
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
|
||||
@@ -1,21 +1,26 @@
|
||||
use chrono::Datelike;
|
||||
use crate::TaskGroup;
|
||||
use crate::todo::{File as TodoFile, Status as TaskStatus};
|
||||
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::{Arena, ComrakExtensionOptions, ComrakOptions, ComrakParseOptions};
|
||||
use std::str;
|
||||
use std::io::Write;
|
||||
use std::collections::HashMap;
|
||||
use comrak::parse_document;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::fs::{read, read_dir, File};
|
||||
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
|
||||
}
|
||||
|
||||
@@ -38,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(),
|
||||
)
|
||||
@@ -106,11 +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())
|
||||
}
|
||||
|
||||
50
src/main.rs
50
src/main.rs
@@ -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;
|
||||
@@ -15,10 +15,9 @@ use std::fs;
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
|
||||
//TODO refactor creating new file
|
||||
|
||||
fn main() {
|
||||
let args = Args::parse();
|
||||
println!("{:?}", args);
|
||||
|
||||
let expected_cfg_files = match Config::expected_locations() {
|
||||
Ok(cfg_files) => cfg_files,
|
||||
@@ -62,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) {
|
||||
@@ -99,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()
|
||||
@@ -110,11 +125,10 @@ fn main() {
|
||||
file::write_file(&file_path, &content);
|
||||
file_path
|
||||
}
|
||||
Ok(todo_file) => todo_file.file.path(),
|
||||
};
|
||||
|
||||
Command::new(cfg.editor)
|
||||
Command::new(&cfg.editor)
|
||||
.args([current_file])
|
||||
.status()
|
||||
.expect(format!("failed to launch editor {}", "vim").as_str());
|
||||
.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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,3 +3,4 @@ mod tasks;
|
||||
|
||||
pub use file::File;
|
||||
pub use tasks::{Status, TaskGroup};
|
||||
|
||||
|
||||
Reference in New Issue
Block a user