aboutsummaryrefslogtreecommitdiff
path: root/src/command/add.rs
blob: 3e0e9876cbb5268aacace5762a202ea74de38a98 (plain)
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
use std::fs::{create_dir_all, remove_dir_all, rename};
use std::io::{Result, Error};
use super::{
    generate::Generate,
    sync_down::SyncDown,
    sync_up::SyncUp,
    update::Update
};
use crate::configuration::Configuration;

pub struct Add;

impl Add {
    pub fn new() -> Self {
        Add
    }

    // moves posts to their next
    fn shift(&self, configuration: &Configuration) -> Result<()> {
        for i in (0..configuration.max_posts).rev() {
            let source = configuration.posts_directory.join(i.to_string());
            let target = configuration.posts_directory.join((i + 1).to_string());

            println!("Moving {} source to {}", source.display(), target.display());

            if source.exists() {
                match rename(&source, &target) {
                    Ok(_) => continue,
                    Err(e) => return Err(Error::new(e.kind(), format!("Could not shift post {} to {}", source.display(), target.display())))
                }
            }
        }
        Ok(())
    }
}

impl super::Command for Add {
    fn before_dependencies(&self) -> Vec<Box<dyn super::Command>> {
        vec![Box::new(SyncDown::new())]
    }

    fn execute(&self, _: Option<&String>, configuration: &Configuration, _: &String) -> Result<()> {
        match create_dir_all(&configuration.posts_directory) {
            Ok(_) => {
                match self.shift(configuration) {
                    Ok(_) => {
                        let first_directory = configuration.posts_directory.join("0");
                        let _ = remove_dir_all(&first_directory);
                        match create_dir_all(&configuration.posts_directory) {
                            Ok(_) => Ok(()),
                            Err(e) => Err(Error::new(e.kind(), format!("Could not create first post directory")))
                        }
                    },
                    Err(e) => Err(e)
                }
            },
            Err(e) => Err(Error::new(e.kind(), format!("Could not create posts directory")))
        }
    }

    fn after_dependencies(&self) -> Vec<Box<dyn super::Command>> {
        vec![
            Box::new(Update::new()),
            Box::new(Generate::new()),
            Box::new(SyncUp::new())
        ]
    }

    fn command(&self) -> &'static str {
        "add"
    }

    fn help(&self) -> &'static str {
        "<path_to_post>\t\t\tCreates new blog post"
    }
}