Compare commits
53 Commits
175a6c20a8
...
v0.1.3
| Author | SHA1 | Date | |
|---|---|---|---|
| 754ae271d7 | |||
| 2643957c91 | |||
| 5cd03b713c | |||
| 4e26695532 | |||
| 7453bb8cae | |||
| c92bb3b31b | |||
| 51574e1403 | |||
| d910f78afd | |||
| a8e6572a53 | |||
| fc7e45cd3f | |||
| 9fe6ae5eb8 | |||
| ddd620a021 | |||
| 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 |
5
.gitignore
vendored
5
.gitignore
vendored
@@ -17,3 +17,8 @@ Cargo.lock
|
|||||||
# Added by cargo
|
# Added by cargo
|
||||||
|
|
||||||
/target
|
/target
|
||||||
|
|
||||||
|
|
||||||
|
# config file
|
||||||
|
.rusty_task.json
|
||||||
|
Notes/
|
||||||
|
|||||||
10
Cargo.toml
10
Cargo.toml
@@ -1,10 +1,18 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "rusty-tasks"
|
name = "rusty-tasks"
|
||||||
version = "0.1.0"
|
version = "0.1.3"
|
||||||
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
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
chrono = "0.4.26"
|
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"
|
regex = "1.8.4"
|
||||||
|
serde = { version = "1.0.164", features = ["serde_derive"] }
|
||||||
|
serde_json = "1.0.97"
|
||||||
|
resolve-path = "0.1.0"
|
||||||
|
simple_logger = "4.3.3"
|
||||||
|
log = "0.4.21"
|
||||||
|
|||||||
111
README.md
111
README.md
@@ -1,26 +1,111 @@
|
|||||||
# Rusty-tasks
|
# Rusty-tasks
|
||||||
A rewrite of an older CLI todo system without python and regex
|
|
||||||
|
|
||||||
## Goals
|
A personal task management system built on plain text and works in your favorite editor
|
||||||
|
|
||||||
- [ ] BLAZING FAST!
|
|
||||||
- [ ] replace python with rust
|
|
||||||
- [ ] replace regex with a markdown parsing library
|
|
||||||
- [ ] learn some rust along the way
|
|
||||||
|
|
||||||
## Ideas
|
## The General Idea
|
||||||
|
|
||||||
If you've used the bullet journal technique before, think if this as the
|
If you've used the bullet journal technique before, think of this as the
|
||||||
digital, automated version of that.
|
digital, automated version of that.
|
||||||
|
|
||||||
- Accessible from anywhere in the terminal (TMUX, bare shell, etc)
|
- Accessible from anywhere in the terminal (TMUX, bare shell, etc.)
|
||||||
* works really well with a drop-down terminal
|
* works really well with a drop-down terminal
|
||||||
- Takes advantage of default editor (vim, emacs, etc)
|
- Take advantage of your favorite editor (vim, Emacs, etc.)
|
||||||
- Take advantage of Markdown for formatting
|
- Take advantage of plain text formats (Markdown)
|
||||||
- Organize tasks at different levels of urgency
|
- Organize tasks at different levels of urgency
|
||||||
* Daily - Must get done now
|
* Daily - Must get done now
|
||||||
* Weekly - Must get done in the near future
|
* 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
|
* 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
|
- Every day start a new file
|
||||||
* files should be dated
|
* files should be dated
|
||||||
- Carry over uncompleted tasks from previous day
|
- Carry over uncompleted tasks from the previous day
|
||||||
|
|
||||||
|
|
||||||
|
## Installing
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git clone https://github.com/andrei-stoica/rusty-tasks.git
|
||||||
|
cd rusty-task cargo install --path .
|
||||||
|
```
|
||||||
|
|
||||||
|
Alternatively, there is a binary download for AMD64 Linux machines available
|
||||||
|
on the [releases page](https://github.com/andrei-stoica/rusty-tasks/releases).
|
||||||
|
Just drop that anywhere on your PATH. I recommend adding `~/bin` to your PATH
|
||||||
|
and dropping the executable there.
|
||||||
|
|
||||||
|
If you are not on an AMD64 Linux machine, you will need to build from source.
|
||||||
|
I have not tested this on other platforms, so I hesitate to provide binaries
|
||||||
|
for them.
|
||||||
|
|
||||||
|
## Usage
|
||||||
|
***WARNING:*** *This documentation can be ahead of the releases on the GH release page*
|
||||||
|
```help
|
||||||
|
Usage: rusty-tasks [OPTIONS]
|
||||||
|
|
||||||
|
Options:
|
||||||
|
-c, --config <FILE> set config file to use
|
||||||
|
-C, --current-config show current config file
|
||||||
|
-d, --date <DATE> view a specific date's file (format: YYYY-MM-DD)
|
||||||
|
-p, --previous <PREVIOUS> view previous day's notes [default: 0]
|
||||||
|
-l, --list list closest files to date
|
||||||
|
-n, --number <NUMBER> number of files to list [default: 5]
|
||||||
|
-L, --list-all list closest files to date
|
||||||
|
-v, --verbose... increase logging level
|
||||||
|
-h, --help Print help
|
||||||
|
-V, --version Print version
|
||||||
|
```
|
||||||
|
|
||||||
|
Just use `rust-task` to access today's notes file.
|
||||||
|
|
||||||
|
Use `rust-task -p <n>` to access a previous day's file where `<n>` is the number
|
||||||
|
of days back you want to go. If a file does not exist for that day, it will
|
||||||
|
default to the closest to that date. A value of 0 represents today's file.
|
||||||
|
|
||||||
|
Alternatively, use `--date` or `-d` to specify a date specifically. Preferably
|
||||||
|
in the format year-month-day, padding with zero is optional. However, if the
|
||||||
|
year, or, year and month are omitted they will be filled in with the current
|
||||||
|
date's year and month. For example, If the current date is `2024-2-30`, the
|
||||||
|
string `4` will resolve to `2024-2-4`, and `1-4` will resolve to `2024-1-4`.
|
||||||
|
|
||||||
|
Specify a custom config location with `-c`, otherwise, it will scan for a config
|
||||||
|
in the locations specified in the [config section](#config). If no config
|
||||||
|
exists it will create one. To see what config is being loaded you can use `-C`.
|
||||||
|
|
||||||
|
To list your existing notes you can use `-L`. For a subset of these use
|
||||||
|
`-l` combined with `-n` to specify the number of files to list. This will be
|
||||||
|
the closest `n` files to the specified date, which is today by default. Specify
|
||||||
|
the target date using the `-p` as mentioned earlier
|
||||||
|
|
||||||
|
## Config
|
||||||
|
|
||||||
|
The config should be located in the following locations:
|
||||||
|
|
||||||
|
- `~/.config/rusty_task.json`
|
||||||
|
- `~/.rusty_task.json`
|
||||||
|
- `$PWD/.rusty_task.json`
|
||||||
|
|
||||||
|
If there is no config it will be created at `~/.config/rusty_task.json`.
|
||||||
|
|
||||||
|
Example config:
|
||||||
|
```
|
||||||
|
{
|
||||||
|
"editor": "nano",
|
||||||
|
"sections": [
|
||||||
|
"Daily",
|
||||||
|
"Weekly",
|
||||||
|
"Monthly"
|
||||||
|
],
|
||||||
|
"notes_dir": "~/notes"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- `editor` is the executable that will be launched to modify the notes file
|
||||||
|
- `sections` is a list of Sections that will be carried over from the previous
|
||||||
|
day's notes
|
||||||
|
* only uncompleted tasks are carried over
|
||||||
|
* You can use other sections for scratch space and other journaling tasks
|
||||||
|
- `notes_dir` is the directory that stores your daily notes
|
||||||
|
* this could be set to your obsidian vault if you want it to work with
|
||||||
|
all of your other notes (I recommend checking out [obsidian.nvim](https://github.com/epwalsh/obsidian.nvim)
|
||||||
|
if you want to interact with an obsidian vault in neovim)
|
||||||
|
|
||||||
|
|||||||
104
src/cli/mod.rs
Normal file
104
src/cli/mod.rs
Normal file
@@ -0,0 +1,104 @@
|
|||||||
|
use chrono::{Datelike, NaiveDate};
|
||||||
|
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 a specific date's file (YYYY-MM-DD)
|
||||||
|
#[arg(short, long)]
|
||||||
|
pub date: Option<String>,
|
||||||
|
/// 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,
|
||||||
|
/// number of files to list
|
||||||
|
#[arg(short, long, default_value_t = 5)]
|
||||||
|
pub number: usize,
|
||||||
|
/// list closest files to date
|
||||||
|
#[arg(short = 'L', long)]
|
||||||
|
pub list_all: bool,
|
||||||
|
|
||||||
|
/// increase logging level
|
||||||
|
#[arg(short, long, action = clap::ArgAction::Count)]
|
||||||
|
pub verbose: u8,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn smart_parse_date(date_str: &str, cur_date: &NaiveDate) -> Option<NaiveDate> {
|
||||||
|
let full_date_fmt = "%Y-%m-%d";
|
||||||
|
|
||||||
|
if let Ok(date) = NaiveDate::parse_from_str(date_str, &full_date_fmt) {
|
||||||
|
return Some(date);
|
||||||
|
}
|
||||||
|
let parts: Vec<&str> = date_str.split('-').collect();
|
||||||
|
|
||||||
|
match parts.len() {
|
||||||
|
1 => cur_date.with_day(parts[0].parse().unwrap_or(cur_date.day())),
|
||||||
|
2 => cur_date
|
||||||
|
.with_day(parts[1].parse().unwrap_or(cur_date.day()))?
|
||||||
|
.with_month(parts[0].parse().unwrap_or(cur_date.month())),
|
||||||
|
3 => NaiveDate::from_ymd_opt(
|
||||||
|
parts[0].parse().ok()?,
|
||||||
|
parts[1].parse().ok()?,
|
||||||
|
parts[2].parse().ok()?,
|
||||||
|
),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod test {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_smart_parse_date() {
|
||||||
|
let good_date = NaiveDate::from_ymd_opt(2024, 01, 03).expect("Invalid date specified");
|
||||||
|
let good_date_str = good_date.format("%Y-%m-%d").to_string();
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
Some(good_date),
|
||||||
|
smart_parse_date(&good_date_str, &good_date)
|
||||||
|
);
|
||||||
|
let no_padding_date_str = "2024-1-3";
|
||||||
|
assert_eq!(
|
||||||
|
Some(good_date),
|
||||||
|
smart_parse_date(no_padding_date_str, &good_date)
|
||||||
|
);
|
||||||
|
|
||||||
|
let bad_day_str = "2024-01-99";
|
||||||
|
assert_eq!(None, smart_parse_date(bad_day_str, &good_date));
|
||||||
|
let no_day_str = "2024-01";
|
||||||
|
assert_eq!(None, smart_parse_date(no_day_str, &good_date));
|
||||||
|
|
||||||
|
let bad_month_str = "2024-25-01";
|
||||||
|
assert_eq!(None, smart_parse_date(bad_month_str, &good_date));
|
||||||
|
let no_month_str = "2024-14";
|
||||||
|
assert_eq!(None, smart_parse_date(no_month_str, &good_date));
|
||||||
|
|
||||||
|
let no_year_str = "01-03";
|
||||||
|
assert_eq!(Some(good_date), smart_parse_date(no_year_str, &good_date));
|
||||||
|
let bad_month_no_year_str = "25-01";
|
||||||
|
assert_eq!(None, smart_parse_date(bad_month_no_year_str, &good_date));
|
||||||
|
let bad_day_no_year_str = "01-35";
|
||||||
|
assert_eq!(None, smart_parse_date(bad_day_no_year_str, &good_date));
|
||||||
|
|
||||||
|
let no_year_month_str = "03";
|
||||||
|
assert_eq!(
|
||||||
|
Some(good_date),
|
||||||
|
smart_parse_date(no_year_month_str, &good_date)
|
||||||
|
);
|
||||||
|
let bad_day_no_year_month_str = "35";
|
||||||
|
assert_eq!(
|
||||||
|
None,
|
||||||
|
smart_parse_date(bad_day_no_year_month_str, &good_date)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
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])
|
||||||
|
}
|
||||||
|
}
|
||||||
281
src/file/mod.rs
Normal file
281
src/file/mod.rs
Normal file
@@ -0,0 +1,281 @@
|
|||||||
|
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
|
||||||
|
}
|
||||||
|
|
||||||
|
/// generate strings from TaskGroups and date
|
||||||
|
pub fn generate_file_content(data: &Vec<TaskGroup>, date: &NaiveDate) -> String {
|
||||||
|
// TODO: This should be a type and then I can implement it with From<>
|
||||||
|
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}");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Load in text file as String
|
||||||
|
pub fn load_file(file: &TodoFile) -> String {
|
||||||
|
// TODO: This could be a TryFrom<>
|
||||||
|
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()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Parse contents of markdown file with Comrak ( relaxed tasklist matching is enabled)
|
||||||
|
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
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod test {
|
||||||
|
use super::*;
|
||||||
|
use crate::todo::{Status, Task};
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_extract_sections() {
|
||||||
|
let test_md = "\
|
||||||
|
# Test
|
||||||
|
## Content
|
||||||
|
- [ ] something
|
||||||
|
- [x] done
|
||||||
|
- [!] other
|
||||||
|
## Unused
|
||||||
|
### Sub section
|
||||||
|
- [ ] task
|
||||||
|
## Unrealated Stuff
|
||||||
|
- [ ] something else
|
||||||
|
+ [ ] subtask";
|
||||||
|
|
||||||
|
let arena = Arena::new();
|
||||||
|
let root = parse_todo_file(&test_md.to_string(), &arena);
|
||||||
|
|
||||||
|
let result = extract_secitons(root, &vec![]);
|
||||||
|
assert_eq!(result.keys().count(), 0);
|
||||||
|
|
||||||
|
let result = extract_secitons(root, &vec!["Not There".to_string()]);
|
||||||
|
assert_eq!(result.keys().count(), 0);
|
||||||
|
|
||||||
|
let sections = vec!["Unused".to_string()];
|
||||||
|
let result = extract_secitons(root, §ions);
|
||||||
|
assert_eq!(result.keys().count(), 0);
|
||||||
|
|
||||||
|
let sections = vec!["Sub section".to_string()];
|
||||||
|
let result = extract_secitons(root, §ions);
|
||||||
|
assert_eq!(result.keys().count(), 1);
|
||||||
|
assert!(result.get(sections.first().unwrap()).is_some());
|
||||||
|
assert_eq!(result.get(sections.first().unwrap()).unwrap().level, 3);
|
||||||
|
|
||||||
|
let sections = vec!["Content".to_string()];
|
||||||
|
let result = extract_secitons(root, §ions);
|
||||||
|
assert_eq!(result.keys().count(), 1);
|
||||||
|
assert!(result.get(sections.first().unwrap()).is_some());
|
||||||
|
assert_eq!(
|
||||||
|
result
|
||||||
|
.get(sections.first().unwrap())
|
||||||
|
.expect("No Value for \"Content\""),
|
||||||
|
&TaskGroup {
|
||||||
|
name: sections.first().unwrap().clone(),
|
||||||
|
tasks: vec![
|
||||||
|
Task {
|
||||||
|
status: TaskStatus::Empty,
|
||||||
|
text: "something".to_string(),
|
||||||
|
subtasks: None
|
||||||
|
},
|
||||||
|
Task {
|
||||||
|
status: TaskStatus::Todo('!'),
|
||||||
|
text: "other".to_string(),
|
||||||
|
subtasks: None
|
||||||
|
},
|
||||||
|
],
|
||||||
|
level: 2
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
let sections = vec!["Unrealated Stuff".to_string()];
|
||||||
|
let result = extract_secitons(root, §ions);
|
||||||
|
assert_eq!(result.keys().count(), 1);
|
||||||
|
assert!(result.get(sections.first().unwrap()).is_some());
|
||||||
|
assert_eq!(
|
||||||
|
result
|
||||||
|
.get(sections.first().unwrap())
|
||||||
|
.expect("No Value for \"Content\""),
|
||||||
|
&TaskGroup {
|
||||||
|
name: sections.first().unwrap().clone(),
|
||||||
|
tasks: vec![Task {
|
||||||
|
status: TaskStatus::Empty,
|
||||||
|
text: "something else".to_string(),
|
||||||
|
subtasks: Some(vec![Task {
|
||||||
|
status: TaskStatus::Empty,
|
||||||
|
text: "subtask".to_string(),
|
||||||
|
subtasks: None
|
||||||
|
}]),
|
||||||
|
}],
|
||||||
|
level: 2
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
let result = extract_secitons(
|
||||||
|
root,
|
||||||
|
&vec!["Content".to_string(), "Sub section".to_string()],
|
||||||
|
);
|
||||||
|
assert_eq!(result.keys().count(), 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_generate_file_content() {
|
||||||
|
let date = NaiveDate::from_ymd_opt(2024, 1, 1).unwrap();
|
||||||
|
let mut content: Vec<TaskGroup> = vec![];
|
||||||
|
|
||||||
|
let result = generate_file_content(&content, &date);
|
||||||
|
let expected = "# Today's tasks 2024-01-01\n";
|
||||||
|
assert_eq!(result, expected);
|
||||||
|
|
||||||
|
content.push(TaskGroup {
|
||||||
|
name: "Empty".into(),
|
||||||
|
tasks: vec![],
|
||||||
|
level: 2,
|
||||||
|
});
|
||||||
|
|
||||||
|
let result = generate_file_content(&content, &date);
|
||||||
|
let expected = "# Today's tasks 2024-01-01\n\n## Empty\n";
|
||||||
|
assert_eq!(result, expected);
|
||||||
|
|
||||||
|
content.push(TaskGroup {
|
||||||
|
name: "Subgroup".into(),
|
||||||
|
tasks: vec![],
|
||||||
|
level: 3,
|
||||||
|
});
|
||||||
|
|
||||||
|
let result = generate_file_content(&content, &date);
|
||||||
|
let expected = "# Today's tasks 2024-01-01\n\n## Empty\n\n### Subgroup\n";
|
||||||
|
assert_eq!(result, expected);
|
||||||
|
|
||||||
|
content.push(TaskGroup {
|
||||||
|
name: "Tasks".into(),
|
||||||
|
tasks: vec![
|
||||||
|
Task {
|
||||||
|
status: Status::Empty,
|
||||||
|
text: "task 1".into(),
|
||||||
|
subtasks: None,
|
||||||
|
},
|
||||||
|
Task {
|
||||||
|
status: Status::Done('x'),
|
||||||
|
text: "task 2".into(),
|
||||||
|
subtasks: None,
|
||||||
|
},
|
||||||
|
Task {
|
||||||
|
status: Status::Todo('>'),
|
||||||
|
text: "task 3".into(),
|
||||||
|
subtasks: None,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
level: 2,
|
||||||
|
});
|
||||||
|
|
||||||
|
let result = generate_file_content(&content, &date);
|
||||||
|
let expected = "\
|
||||||
|
# Today's tasks 2024-01-01
|
||||||
|
|
||||||
|
## Empty
|
||||||
|
|
||||||
|
### Subgroup
|
||||||
|
|
||||||
|
## Tasks
|
||||||
|
- [ ] task 1
|
||||||
|
- [x] task 2
|
||||||
|
- [>] task 3
|
||||||
|
";
|
||||||
|
assert_eq!(result, expected);
|
||||||
|
}
|
||||||
|
}
|
||||||
26
src/logging/mod.rs
Normal file
26
src/logging/mod.rs
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
use log::Level;
|
||||||
|
|
||||||
|
pub fn get_logging_level(verbose_level: u8) -> Level {
|
||||||
|
match verbose_level {
|
||||||
|
..=0 => Level::Error,
|
||||||
|
1 => Level::Warn,
|
||||||
|
2 => Level::Info,
|
||||||
|
3 => Level::Debug,
|
||||||
|
4.. => Level::Trace,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod test {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_get_logging_level() {
|
||||||
|
assert_eq!(get_logging_level(0), Level::Error);
|
||||||
|
assert_eq!(get_logging_level(1), Level::Warn);
|
||||||
|
assert_eq!(get_logging_level(2), Level::Info);
|
||||||
|
assert_eq!(get_logging_level(3), Level::Debug);
|
||||||
|
assert_eq!(get_logging_level(4), Level::Trace);
|
||||||
|
assert_eq!(get_logging_level(5), Level::Trace);
|
||||||
|
}
|
||||||
|
}
|
||||||
274
src/main.rs
274
src/main.rs
@@ -1,127 +1,191 @@
|
|||||||
|
mod cli;
|
||||||
|
mod config;
|
||||||
|
mod file;
|
||||||
|
mod logging;
|
||||||
|
mod todo;
|
||||||
|
|
||||||
use chrono::naive::NaiveDate;
|
use chrono::naive::NaiveDate;
|
||||||
use chrono::{Datelike, Local};
|
use chrono::{Local, TimeDelta};
|
||||||
use std::env;
|
use clap::Parser;
|
||||||
|
use cli::Args;
|
||||||
|
use comrak::Arena;
|
||||||
|
use config::Config;
|
||||||
|
use log;
|
||||||
|
use logging::get_logging_level;
|
||||||
|
use resolve_path::PathResolveExt;
|
||||||
|
use simple_logger::init_with_level;
|
||||||
use std::fs;
|
use std::fs;
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::Path;
|
||||||
use todo_file::TodoFile;
|
use std::process::Command;
|
||||||
|
use todo::{File as TodoFile, TaskGroup};
|
||||||
//TODO handle unwraps and errors more uniformly
|
|
||||||
//TODO move TodoFile into its file
|
|
||||||
|
|
||||||
|
// TODO: add options to use specific date instead of args.previous
|
||||||
fn main() {
|
fn main() {
|
||||||
let data_dir = get_data_dir("notes");
|
// setup
|
||||||
|
let args = Args::parse();
|
||||||
|
let _logger = init_with_level(get_logging_level(args.verbose)).unwrap();
|
||||||
|
log::debug!("{:?}", args);
|
||||||
|
|
||||||
println!("{}", data_dir.to_str().unwrap());
|
// getting config location
|
||||||
let latest_file = get_latest_file(&data_dir).unwrap();
|
let expected_cfg_files = match Config::expected_locations() {
|
||||||
//.expect(
|
Ok(cfg_files) => cfg_files,
|
||||||
// format!(
|
Err(e) => panic!("{:?}", e),
|
||||||
// "Could not find any notes files please use format: {}",
|
};
|
||||||
// get_file_regex().to_string()
|
|
||||||
// )
|
|
||||||
// .as_str(),
|
|
||||||
//);
|
|
||||||
println!("Latest file: {:?}", latest_file);
|
|
||||||
let now = Local::now();
|
|
||||||
let today = NaiveDate::from_ymd_opt(now.year(), now.month(), now.day());
|
|
||||||
match today {
|
|
||||||
Some(today) if latest_file.date == today => println!("Todays file was created"),
|
|
||||||
Some(today) if latest_file.date < today => println!("Todays file was not created"),
|
|
||||||
Some(today) if latest_file.date > today => println!("Future files were created"),
|
|
||||||
|
|
||||||
_ => println!("Today never happend!"),
|
// getting exising config files
|
||||||
|
let cfg_files: Vec<&Path> = expected_cfg_files
|
||||||
|
.iter()
|
||||||
|
.map(|file| Path::new(file))
|
||||||
|
.filter(|file| file.exists())
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
// writing default config if non exist
|
||||||
|
if cfg_files.len() <= 0 && args.config.is_none() {
|
||||||
|
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);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
mod todo_file {
|
// set witch config file to load
|
||||||
use chrono::naive::NaiveDate;
|
let cfg_file = match args.config {
|
||||||
use std::convert::TryFrom;
|
Some(file) => file,
|
||||||
use std::fs::DirEntry;
|
None => match cfg_files.last() {
|
||||||
use std::str::FromStr;
|
None => expected_cfg_files[0].to_string_lossy().to_string(),
|
||||||
use regex::Regex;
|
Some(file) => file.to_string_lossy().to_string(),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
#[derive(Debug)]
|
// show current config file or just log it based on args
|
||||||
pub struct TodoFile {
|
if args.current_config {
|
||||||
pub file: DirEntry,
|
print!("{}", &cfg_file);
|
||||||
pub date: NaiveDate,
|
return;
|
||||||
}
|
|
||||||
|
|
||||||
impl TodoFile {
|
|
||||||
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())?)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn latest_file(a: TodoFile, b: TodoFile) -> TodoFile {
|
|
||||||
if a.date > b.date {
|
|
||||||
a
|
|
||||||
} else {
|
} else {
|
||||||
b
|
log::debug!("config file: {}", &cfg_file);
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn get_file_regex() -> Regex {
|
// load config file
|
||||||
//TODO This would ideally be configurable
|
let cfg = match Config::load(&cfg_file) {
|
||||||
Regex::new(r"(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2}).md")
|
Ok(cfg) => cfg,
|
||||||
.expect("could not create regex")
|
Err(_e) => panic!("could not load config: {}", cfg_file),
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl TryFrom<DirEntry> for TodoFile {
|
|
||||||
type Error = String;
|
|
||||||
|
|
||||||
fn try_from(direntry: DirEntry) -> Result<Self, Self::Error> {
|
|
||||||
let re = TodoFile::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);
|
log::debug!("{:#?}", cfg);
|
||||||
|
|
||||||
if let Some(caps) = re.captures(file_name_str) {
|
// resolve data directory and create it if it does not exisit
|
||||||
let year: i32 = Self::capture_as_number(&caps, "year").unwrap();
|
let data_dir = cfg.notes_dir.resolve().to_path_buf();
|
||||||
let month: u32 = Self::capture_as_number(&caps, "month").unwrap();
|
if !fs::metadata(&data_dir).is_ok() {
|
||||||
let day: u32 = Self::capture_as_number(&caps, "day").unwrap();
|
match fs::create_dir_all(&data_dir) {
|
||||||
|
Err(_e) => panic!("Could not create default directory: {:?}", &data_dir),
|
||||||
return Ok(Self {
|
_ => log::info!("created dir {}", &data_dir.to_string_lossy()),
|
||||||
file: direntry,
|
|
||||||
date: NaiveDate::from_ymd_opt(year, month, day).unwrap(),
|
|
||||||
});
|
|
||||||
};
|
};
|
||||||
Err(format!(
|
}
|
||||||
"Could not parse file name => {{ name: {:?}, re: {:?} }}",
|
|
||||||
file_name, re
|
// get file paths of notes
|
||||||
|
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());
|
||||||
|
// list all notes
|
||||||
|
if args.list_all {
|
||||||
|
files
|
||||||
|
.into_iter()
|
||||||
|
.for_each(|f| println!("{}", f.canonicalize().unwrap().to_string_lossy()));
|
||||||
|
return ();
|
||||||
|
}
|
||||||
|
|
||||||
|
// get clossest files to specified date
|
||||||
|
let today = Local::now().date_naive();
|
||||||
|
let target = if let Some(date_str) = args.date {
|
||||||
|
cli::smart_parse_date(&date_str, &today).expect("Could not parse date")
|
||||||
|
} else {
|
||||||
|
today - TimeDelta::try_days(args.previous.into()).unwrap()
|
||||||
|
};
|
||||||
|
let closest_files = TodoFile::get_closest_files(files.collect(), target, args.number);
|
||||||
|
// list files
|
||||||
|
if args.list {
|
||||||
|
println!("Today - n\tFile");
|
||||||
|
closest_files.into_iter().for_each(|f| {
|
||||||
|
println!(
|
||||||
|
"{}\t\t{}",
|
||||||
|
(today - f.date).num_days(),
|
||||||
|
f.file.canonicalize().unwrap().to_string_lossy(),
|
||||||
)
|
)
|
||||||
.to_string())
|
});
|
||||||
}
|
return ();
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
// TODO: If the user did not pick a date that exist they should have the
|
||||||
|
// option to updated their choice
|
||||||
|
|
||||||
fn get_data_dir(dir_name: &str) -> PathBuf {
|
let latest_file = closest_files.first();
|
||||||
let mut dir = if let Ok(home) = env::var("HOME") {
|
let current_file = match latest_file {
|
||||||
let mut x = PathBuf::new();
|
// copy old file if the user specifies today's notes but it does not exist
|
||||||
x.push(home);
|
Some(todo_file) if todo_file.date < today && args.previous == 0 => {
|
||||||
x
|
let sections = &cfg.sections;
|
||||||
} else {
|
log::info!("looking for sections: {:?}", sections);
|
||||||
env::current_dir().expect("PWD environment variable not set")
|
let arena = Arena::new();
|
||||||
|
|
||||||
|
// attempt to load file
|
||||||
|
let root = {
|
||||||
|
log::info!(
|
||||||
|
"loading and parsing file: {}",
|
||||||
|
todo_file.file.to_string_lossy()
|
||||||
|
);
|
||||||
|
let contents = file::load_file(&todo_file);
|
||||||
|
let root = file::parse_todo_file(&contents, &arena);
|
||||||
|
root
|
||||||
};
|
};
|
||||||
dir = dir.join(dir_name);
|
log::trace!("file loaded");
|
||||||
dir
|
// extract sections specified in config
|
||||||
}
|
let groups = file::extract_secitons(root, sections);
|
||||||
|
log::trace!("sections extracted");
|
||||||
|
// create new sections and generate empty sections for any that are missing
|
||||||
|
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();
|
||||||
|
|
||||||
fn get_latest_file(dir: &Path) -> Result<TodoFile, String> {
|
// generate string for new file and write to filesystem
|
||||||
let dir = fs::read_dir(dir).expect(format!("Could not find notes folder: {:?}", dir).as_str());
|
let content = file::generate_file_content(&data, &today);
|
||||||
dir.filter_map(|f| f.ok())
|
let file_path = file::get_filepath(&data_dir, &today);
|
||||||
.filter_map(|file| TodoFile::try_from(file).ok())
|
log::info!("writing to file: {}", file_path.to_string_lossy());
|
||||||
.reduce(|a, b| TodoFile::latest_file(a, b))
|
file::write_file(&file_path, &content);
|
||||||
.ok_or("Could not reduce items".to_string())
|
// return file name
|
||||||
|
file_path
|
||||||
|
}
|
||||||
|
// returning the selected file
|
||||||
|
Some(todo_file) => todo_file.file.to_owned(),
|
||||||
|
// no note files exist creating based on template from config
|
||||||
|
None => {
|
||||||
|
// generate empty file
|
||||||
|
let sections = &cfg.sections;
|
||||||
|
log::info!("creating new empty file with sections: {:?}", 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);
|
||||||
|
log::info!("writing to file: {}", file_path.to_string_lossy());
|
||||||
|
// return file name
|
||||||
|
file_path
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// opening file
|
||||||
|
log::info!(
|
||||||
|
"Opening {} in {}",
|
||||||
|
current_file.to_string_lossy(),
|
||||||
|
cfg.editor
|
||||||
|
);
|
||||||
|
Command::new(&cfg.editor)
|
||||||
|
.args([current_file])
|
||||||
|
.status()
|
||||||
|
.expect(format!("failed to launch editor {}", &cfg.editor).as_str());
|
||||||
}
|
}
|
||||||
|
|||||||
116
src/todo/file.rs
Normal file
116
src/todo/file.rs
Normal file
@@ -0,0 +1,116 @@
|
|||||||
|
use chrono::naive::NaiveDate;
|
||||||
|
use std::cmp::min;
|
||||||
|
use std::convert::TryFrom;
|
||||||
|
use std::path::PathBuf;
|
||||||
|
|
||||||
|
use crate::file::FileNameParseError;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq)]
|
||||||
|
pub struct File {
|
||||||
|
pub file: PathBuf,
|
||||||
|
pub date: NaiveDate,
|
||||||
|
}
|
||||||
|
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
5
src/todo/mod.rs
Normal file
5
src/todo/mod.rs
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
mod file;
|
||||||
|
mod tasks;
|
||||||
|
|
||||||
|
pub use file::File;
|
||||||
|
pub use tasks::{Status, TaskGroup};
|
||||||
201
src/todo/tasks.rs
Normal file
201
src/todo/tasks.rs
Normal file
@@ -0,0 +1,201 @@
|
|||||||
|
use std::borrow::Borrow;
|
||||||
|
|
||||||
|
use comrak::nodes::AstNode;
|
||||||
|
use comrak::nodes::NodeValue;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq)]
|
||||||
|
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, PartialEq)]
|
||||||
|
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 = node
|
||||||
|
.first_child()
|
||||||
|
.ok_or(TaskError::ParsingError("Node has no children"))?;
|
||||||
|
|
||||||
|
let data_ref = first_child.data.borrow();
|
||||||
|
let name = if let NodeValue::Text(value) = &data_ref.value {
|
||||||
|
Ok(value.to_string())
|
||||||
|
} else {
|
||||||
|
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