summary refs log tree commit diff stats
path: root/src/new/section.rs
blob: 31742c23bb50741c64682446761eb5ca6fa8b64d (plain) (blame)
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
use std::{
    env,
    fs::{self, read_dir},
    io::{self, ErrorKind},
    path::PathBuf,
    time::SystemTime,
};

use chrono::{DateTime, Local};
use convert_case::{Case, Casing};

use super::SECTION;

pub fn generate_new_section(name: String) -> io::Result<()> {
    let chapter_root = get_section_root()?;
    let chapter_main_file_path = read_dir(&chapter_root)?
        .into_iter()
        .map(|path| path.unwrap())
        .filter(|path| path.file_name().to_str().unwrap().contains("chapter_"))
        .last()
        .unwrap()
        .path();
    let mut main_file = fs::read_to_string(&chapter_main_file_path).unwrap();

    main_file.push_str(&format!(
        "\\input{{content/{}/sections/{}}}\n",
        chapter_root.file_name().unwrap().to_str().unwrap(),
        &name.to_case(Case::Snake)
    ));
    fs::write(chapter_main_file_path, main_file)?;
    fs::write(
        chapter_root.join(format!("sections/{}.tex", name.to_case(Case::Snake))),
        SECTION.replace("REPLACMENT_SECTION_TITLE", &name).replace(
            "DATE",
            &format!(
                "{}",
                DateTime::<Local>::from(SystemTime::now()).format("%Y-%m-%d")
            ),
        ),
    )?;
    Ok(())
}

pub fn get_section_root() -> io::Result<PathBuf> {
    let path = env::current_dir()?;
    let mut path_ancestors = path.as_path().ancestors();

    while let Some(path_segment) = path_ancestors.next() {
        if read_dir(path_segment)?.into_iter().any(|path| {
            path.expect("The read_dir shouldn't error out here")
                .file_name()
                .to_str()
                .unwrap()
                .contains("chapter_")
        }) {
            return Ok(PathBuf::from(path_segment));
        }
    }
    Err(io::Error::new(
        ErrorKind::NotFound,
        "Ran out of places to find chapter_root",
    ))
}