summary refs log tree commit diff stats
path: root/src/new/section.rs
blob: 5e9f08c1e292269e9ca394815d02773d6af0f08a (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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
use std::{
    fs,
    path::Path,
    time::{SystemTime, UNIX_EPOCH},
};

use anyhow::Context;
use chrono::{Local, TimeDelta, TimeZone};
use log::debug;

use crate::{
    config_file::Config,
    file_tree::{FileTree, GeneratedFile},
    new::MangledName,
};

fn get_current_date() -> String {
    let start = SystemTime::now();
    let seconds_since_epoch: TimeDelta = TimeDelta::from_std(
        start
            .duration_since(UNIX_EPOCH)
            .expect("Time went backwards"),
    )
    .expect("Time does not go backwards");

    debug!(
        "Adding a date with timestamp: {}",
        seconds_since_epoch.num_seconds()
    );

    let our_date = format!(
        "{}",
        Local
            .timestamp_opt(seconds_since_epoch.num_seconds(), 0)
            // only has unwrap, no expect. But should always work
            .unwrap()
            .format("%Y-%m-%d %H:%M:%S%.f %:z")
    );

    // let date = Command::new("date")
    //     .args(["-d", &format!("@{}", seconds_since_epoch.num_seconds())])
    //     .output()
    //     .unwrap()
    //     .stdout;

    // info!(
    //     "This is dated: '{}' vs. our date: '{}'",
    //     String::from_utf8(date).unwrap().strip_suffix('\n').unwrap(),
    //     our_date
    // );

    our_date
}

pub fn generate_new_section(
    config: &Config,
    name: String,
    project_root: &Path,
    chapter_name: &str,
) -> anyhow::Result<FileTree> {
    let chapter_root = project_root.join("content").join(chapter_name);
    debug!("Chapter root is: {}", chapter_root.display());

    let mut file_tree = FileTree::new();

    let new_section_text = config
        .templates
        .section
        .replace("REPLACMENT_SECTION_TITLE", &name)
        .replace("DATE", &get_current_date());

    file_tree.add_file(GeneratedFile::new_clobber(
        chapter_root
            .join("sections")
            .join(format!("{}.tex", MangledName::new(&name))),
        new_section_text,
        false,
    ));

    let chapter_file_path = chapter_root.join("chapter.tex");
    let mut chapter_file_text = fs::read_to_string(&chapter_file_path).with_context(|| {
        format!(
            "Failed to read the chapter main file ('{}') to string",
            &chapter_file_path.display(),
        )
    })?;

    chapter_file_text.push_str(&format!(
        "\\input{{content/{}/sections/{}}}\n",
        chapter_name,
        &MangledName::new(&name)
    ));

    let chapter_file = GeneratedFile::new(chapter_file_path, chapter_file_text);
    file_tree.add_file(chapter_file);

    Ok(file_tree)
}