1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
use std::fs::OpenOptions;
use std::io::Write;
use std::path::Path;

use crate::learned::Learned;

mod path {
    extern crate directories;

    use chrono::prelude::*;
    use directories::UserDirs;
    use std::fs::DirBuilder;

    use std::path::{Path, PathBuf};

    extern crate chrono;

    pub fn get_file_name_from_path(file_path: &Path) -> &str {
        let path: &str = file_path.to_str().unwrap();
        let path_bits: Vec<&str> = path.rsplit("/").collect();
        return path_bits[0];
    }

    pub fn get_til_path() -> PathBuf {
        let user_dirs = UserDirs::new().expect("Could not find valid $HOME path");
        let docs_dir = user_dirs.document_dir().expect("Could not locate user documents directory");

        let mut til_dir: PathBuf = docs_dir.to_path_buf();
        til_dir.push(".til");

        if false == til_dir.exists() {
            DirBuilder::new().create(&til_dir).expect("Could not create til directory in user documents");
        }

        til_dir
    }

    pub fn get_til_file_path(root_path: &Path, file_date: Date<Local>) -> PathBuf {
        let mut file_path = root_path.to_path_buf();
        file_path.push(file_date.format("%Y-%m-%d.md").to_string());
        file_path
    }
}


fn append_to_file(file_path: &Path, to_write: &str, prefix: &str) {
    let mut file = OpenOptions::new()
        .create(true)
        .append(true)
        .open(file_path)
        .expect("Could not open file for appending.");

    writeln!(file, "* {}", [prefix, to_write].join(" "))
        .expect("Could not append to file");
}


pub fn write_til_file(learned: &Learned) {
    let til_path = path::get_til_path();
    let til_path = til_path.as_path();

    let file_to_learn_into = path::get_til_file_path(til_path, learned.date);

    if !file_to_learn_into.exists() {
        append_to_file(&file_to_learn_into, &path::get_file_name_from_path(&file_to_learn_into).replace(".md", ""), "#");
    }

    append_to_file(&file_to_learn_into, learned.description.as_str(), "*");
}