blog_rs/commands/
init.rs

1use include_dir::{include_dir, Dir};
2use std::{fs, path::{Path, PathBuf}};
3
4static THEME_DIR: Dir = include_dir!("$CARGO_MANIFEST_DIR/themes");
5
6pub struct Init;
7
8impl Init {
9    pub fn run(&self, path: &str) -> crate::BlogResult<()> {
10        let posts_path = PathBuf::from(path).join("posts");
11        let static_path = PathBuf::from(path).join("static");
12        let template_path = PathBuf::from(path).join("templates");
13        let assets_path = PathBuf::from(path).join("assets");
14        // Create Posts directory
15        fs::create_dir_all(posts_path)
16            .map_err(|e| crate::BlogError::io(e, "Unable to create posts directory".to_string()))?;
17        // Create Static directory
18        fs::create_dir_all(static_path).map_err(|e| {
19            crate::BlogError::io(e, "Unable to create static directory".to_string())
20        })?;
21        // Create Template directory
22        fs::create_dir_all(&template_path).map_err(|e| {
23            crate::BlogError::io(e, "Unable to create templates directory".to_string())
24        })?;
25
26        // Create Default Template
27        let default_template_path = template_path.join("default");
28        fs::create_dir_all(&default_template_path).map_err(|e| {
29            crate::BlogError::io(e, "Unable to create default template directory".to_string())
30        })?;
31        // Create Assets directory
32        fs::create_dir_all(assets_path).map_err(|e| {
33            crate::BlogError::io(e, "Unable to create assets directory".to_string())
34        })?;
35        create_config_toml(&PathBuf::from(path))?;
36        create_template_directories(&default_template_path)?;
37        println!("Created blog-rs directory at {path:?}");
38        Ok(())
39    }
40}
41
42fn create_config_toml(path: &Path) -> crate::BlogResult<()> {
43    let config = r#"
44template = "default"
45title = "My Blog"
46"#;
47    fs::write(path.join("config.toml"), config)
48        .map_err(|e| crate::BlogError::io(e, "Unable to write config.toml".to_string()))?;
49    Ok(())
50}
51
52fn create_template_directories(path: &PathBuf) -> crate::BlogResult<()> {
53    THEME_DIR
54        .extract(path)
55        .map_err(|e| crate::BlogError::io(e, "Unable to extract theme".to_string()))
56}