]>
Commit | Line | Data |
---|---|---|
1 | use std::fs::{create_dir_all, remove_dir_all, rename}; | |
2 | use std::io::{Result, Error}; | |
3 | use super::{ | |
4 | generate::Generate, | |
5 | sync_down::SyncDown, | |
6 | sync_up::SyncUp, | |
7 | update::Update | |
8 | }; | |
9 | use crate::configuration::Configuration; | |
10 | ||
11 | pub struct Add; | |
12 | ||
13 | impl Add { | |
14 | pub fn new() -> Self { | |
15 | Add | |
16 | } | |
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 | } | |
35 | } | |
36 | ||
37 | impl super::Command for Add { | |
38 | fn before_dependencies(&self) -> Vec<Box<dyn super::Command>> { | |
39 | vec![Box::new(SyncDown::new())] | |
40 | } | |
41 | ||
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 | } | |
59 | } | |
60 | ||
61 | fn after_dependencies(&self) -> Vec<Box<dyn super::Command>> { | |
62 | vec![ | |
63 | Box::new(Update::new()), | |
64 | Box::new(Generate::new()), | |
65 | Box::new(SyncUp::new()) | |
66 | ] | |
67 | } | |
68 | ||
69 | fn command(&self) -> &'static str { | |
70 | "add" | |
71 | } | |
72 | ||
73 | fn help(&self) -> &'static str { | |
74 | "<path_to_post>\t\t\tCreates new blog post" | |
75 | } | |
76 | } |