nix-configs/programs/jrnl/src/main.rs

99 lines
2.6 KiB
Rust
Raw Normal View History

2024-04-16 22:06:12 +02:00
use clap::{Parser, Subcommand};
use std::{fs, path::PathBuf};
use time::format_description::well_known::{iso8601, Iso8601};
use crate::md::Doc;
const DATETIME_CONFIG: iso8601::EncodedConfig = iso8601::Config::DEFAULT
.set_time_precision(iso8601::TimePrecision::Minute {
decimal_digits: None,
})
.encode();
const DT_FORMAT: Iso8601<DATETIME_CONFIG> = Iso8601::<DATETIME_CONFIG>;
2024-04-16 22:06:12 +02:00
#[derive(Debug, Parser)]
struct Cli {
#[arg(env)]
s10e_jrnl_file_loc: PathBuf,
#[command(subcommand)]
command: Option<Command>,
}
#[derive(Debug, Subcommand)]
enum Command {
List,
Add,
}
2024-04-16 21:37:01 +02:00
fn main() {
2024-04-16 22:06:12 +02:00
let cli = Cli::parse();
2024-04-16 21:37:01 +02:00
println!("Hello, world!");
println!("cli: {cli:#?}");
// TODO: handle btter
let file = fs::read_to_string(cli.s10e_jrnl_file_loc).unwrap();
let doc = Doc::new(&file);
dbg!(doc);
}
mod md {
use markdown::{Block, Span};
use time::PrimitiveDateTime;
use crate::DT_FORMAT;
#[derive(Debug)]
pub struct Doc {
title: Vec<Span>,
entries: Vec<Entry>,
}
impl Doc {
pub fn new(f: &str) -> Self {
let mut entries = Vec::new();
let mut doc_title = vec![Span::Text("Journal".to_owned())];
let toks = markdown::tokenize(f);
let mut current = None;
for tok in toks {
match tok {
Block::Header(title, 1) => doc_title = title,
Block::Header(entry_title, 2) => {
if let Some(cur) = current.take() {
entries.push(cur);
}
let Some(Span::Text(title)) = entry_title.first() else {
eprintln!("Error: Titles should be text.");
std::process::exit(1);
};
let (ts, entry_title) = title.split_once(": ").unwrap();
let ts = PrimitiveDateTime::parse(ts, &DT_FORMAT).unwrap();
current = Some(Entry {
timestamp: ts,
title: entry_title.to_owned(),
content: Vec::new(),
});
}
other => current.as_mut().unwrap().content.push(other),
}
}
Self {
title: doc_title,
entries,
}
}
}
#[derive(Debug)]
pub struct Entry {
timestamp: PrimitiveDateTime,
title: String,
content: Vec<Block>,
}
2024-04-16 21:37:01 +02:00
}