til_cli/
file.rs

1use std::fs::OpenOptions;
2use std::io::Write;
3use std::path::Path;
4
5use crate::learned::Learned;
6
7mod path {
8    extern crate directories;
9
10    use chrono::prelude::*;
11    use directories::UserDirs;
12    use std::fs::DirBuilder;
13
14    use std::path::{Path, PathBuf};
15
16    extern crate chrono;
17
18    pub fn get_file_name_from_path(file_path: &Path) -> &str {
19        let path: &str = file_path.to_str().unwrap();
20        let path_bits: Vec<&str> = path.rsplit("/").collect();
21        return path_bits[0];
22    }
23
24    pub fn get_til_path() -> PathBuf {
25        let user_dirs = UserDirs::new().expect("Could not find valid $HOME path");
26        let docs_dir = user_dirs.document_dir().expect("Could not locate user documents directory");
27
28        let mut til_dir: PathBuf = docs_dir.to_path_buf();
29        til_dir.push(".til");
30
31        if false == til_dir.exists() {
32            DirBuilder::new().create(&til_dir).expect("Could not create til directory in user documents");
33        }
34
35        til_dir
36    }
37
38    pub fn get_til_file_path(root_path: &Path, file_date: Date<Local>) -> PathBuf {
39        let mut file_path = root_path.to_path_buf();
40        file_path.push(file_date.format("%Y-%m-%d.md").to_string());
41        file_path
42    }
43}
44
45
46fn append_to_file(file_path: &Path, to_write: &str, prefix: &str) {
47    let mut file = OpenOptions::new()
48        .create(true)
49        .append(true)
50        .open(file_path)
51        .expect("Could not open file for appending.");
52
53    writeln!(file, "{}", [prefix, to_write].join(" "))
54        .expect("Could not append to file");
55}
56
57
58pub fn write_til_file(learned: &Learned) {
59    let til_path = path::get_til_path();
60    let til_path = til_path.as_path();
61
62    let file_to_learn_into = path::get_til_file_path(til_path, learned.date);
63
64    if !file_to_learn_into.exists() {
65        append_to_file(&file_to_learn_into, &path::get_file_name_from_path(&file_to_learn_into).replace(".md", ""), "#");
66    }
67
68    append_to_file(&file_to_learn_into, learned.description.as_str(), "*");
69}