nix-configs/programs/jrnl/src/commands/add_entry.rs

61 lines
1.4 KiB
Rust
Raw Normal View History

2024-04-22 21:25:29 +02:00
use std::{
env,
fs::{self, OpenOptions},
io::{self, Write},
path::PathBuf,
process::Command,
};
2024-05-06 21:33:14 +02:00
use inquire::Text;
2024-04-22 21:25:29 +02:00
use temp_file::{TempFile, TempFileBuilder};
use crate::md::{Entry, ToMd};
// TODO: the usual (better error handling)
pub fn add_entry(path: PathBuf, title: Option<String>) -> io::Result<()> {
if !path.exists() {
eprintln!("Journal file does not exist at {path:?}, exiting...");
std::process::exit(1);
}
2024-05-06 21:33:14 +02:00
let title = Text::new("Title").prompt().unwrap();
2024-04-22 21:25:29 +02:00
let tmp = TempFileBuilder::new()
.suffix(".jrnl-entry.md")
.build()
.unwrap();
let editor = match env::var("EDITOR") {
Ok(val) => val,
Err(env::VarError::NotPresent) => {
eprintln!("EDITOR not set, exiting...");
std::process::exit(1);
}
_ => unreachable!(),
};
let mut editor_cmd = Command::new(&editor);
editor_cmd.arg(tmp.path());
editor_cmd.status().unwrap();
let content = fs::read_to_string(tmp.path()).unwrap();
let now = chrono::offset::Local::now();
let entry = Entry {
timestamp: now.fixed_offset(),
title: &title,
content: &content,
};
let mut file = OpenOptions::new()
.write(true)
.append(true)
.open(path)
.unwrap();
write!(file, "{}", entry.to_md())?;
Ok(())
}