]> git.r.bdr.sh - rbdr/blog/blame - src/command/add.rs
Add part of the implementation for add
[rbdr/blog] / src / command / add.rs
CommitLineData
a9c6be41
RBR
1use std::fs::{create_dir_all, remove_dir_all, rename};
2use std::io::{Result, Error};
5f81d796
RBR
3use super::{
4 generate::Generate,
5 sync_down::SyncDown,
6 sync_up::SyncUp,
7 update::Update
8};
a9c6be41 9use crate::configuration::Configuration;
d620665f
RBR
10
11pub struct Add;
12
13impl Add {
14 pub fn new() -> Self {
15 Add
16 }
a9c6be41
RBR
17
18 // moves posts to their next
19 fn shift(&self, configuration: &Configuration) -> Result<()> {
20 for i in (0..configuration.max_posts).rev() {
21 let source = configuration.posts_directory.join(i.to_string());
22 let target = configuration.posts_directory.join((i + 1).to_string());
23
24 println!("Moving {} source to {}", source.display(), target.display());
25
26 if source.exists() {
27 match rename(&source, &target) {
28 Ok(_) => continue,
29 Err(e) => return Err(Error::new(e.kind(), format!("Could not shift post {} to {}", source.display(), target.display())))
30 }
31 }
32 }
33 Ok(())
34 }
d620665f
RBR
35}
36
37impl super::Command for Add {
38 fn before_dependencies(&self) -> Vec<Box<dyn super::Command>> {
5f81d796 39 vec![Box::new(SyncDown::new())]
d620665f
RBR
40 }
41
a9c6be41
RBR
42 fn execute(&self, _: Option<&String>, configuration: &Configuration, _: &String) -> Result<()> {
43 match create_dir_all(&configuration.posts_directory) {
44 Ok(_) => {
45 match self.shift(configuration) {
46 Ok(_) => {
47 let first_directory = configuration.posts_directory.join("0");
48 let _ = remove_dir_all(&first_directory);
49 match create_dir_all(&configuration.posts_directory) {
50 Ok(_) => Ok(()),
51 Err(e) => Err(Error::new(e.kind(), format!("Could not create first post directory")))
52 }
53 },
54 Err(e) => Err(e)
55 }
56 },
57 Err(e) => Err(Error::new(e.kind(), format!("Could not create posts directory")))
58 }
d620665f
RBR
59 }
60
61 fn after_dependencies(&self) -> Vec<Box<dyn super::Command>> {
5f81d796
RBR
62 vec![
63 Box::new(Update::new()),
64 Box::new(Generate::new()),
65 Box::new(SyncUp::new())
66 ]
d620665f
RBR
67 }
68
69 fn command(&self) -> &'static str {
70 "add"
71 }
72
73 fn help(&self) -> &'static str {
2f579cf4 74 "<path_to_post>\t\t\tCreates new blog post"
d620665f
RBR
75 }
76}