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
use include_dir::{include_dir, Dir};
use std::{fs, path::{Path, PathBuf}};

static THEME_DIR: Dir = include_dir!("$CARGO_MANIFEST_DIR/themes");

pub struct Init;

impl Init {
    pub fn run(&self, path: &str) -> crate::BlogResult<()> {
        let posts_path = PathBuf::from(path).join("posts");
        let static_path = PathBuf::from(path).join("static");
        let template_path = PathBuf::from(path).join("templates");
        let assets_path = PathBuf::from(path).join("assets");
        // Create Posts directory
        fs::create_dir_all(posts_path)
            .map_err(|e| crate::BlogError::io(e, "Unable to create posts directory".to_string()))?;
        // Create Static directory
        fs::create_dir_all(static_path).map_err(|e| {
            crate::BlogError::io(e, "Unable to create static directory".to_string())
        })?;
        // Create Template directory
        fs::create_dir_all(&template_path).map_err(|e| {
            crate::BlogError::io(e, "Unable to create templates directory".to_string())
        })?;

        // Create Default Template
        let default_template_path = template_path.join("default");
        fs::create_dir_all(&default_template_path).map_err(|e| {
            crate::BlogError::io(e, "Unable to create default template directory".to_string())
        })?;
        // Create Assets directory
        fs::create_dir_all(assets_path).map_err(|e| {
            crate::BlogError::io(e, "Unable to create assets directory".to_string())
        })?;
        create_config_toml(&PathBuf::from(path))?;
        create_template_directories(&default_template_path)?;
        println!("Created blog-rs directory at {path:?}");
        Ok(())
    }
}

fn create_config_toml(path: &Path) -> crate::BlogResult<()> {
    let config = r#"
template = "default"
title = "My Blog"
"#;
    fs::write(path.join("config.toml"), config)
        .map_err(|e| crate::BlogError::io(e, "Unable to write config.toml".to_string()))?;
    Ok(())
}

fn create_template_directories(path: &PathBuf) -> crate::BlogResult<()> {
    THEME_DIR
        .extract(path)
        .map_err(|e| crate::BlogError::io(e, "Unable to extract theme".to_string()))
}