1 use super::{generate::Generate, sync_down::SyncDown, sync_up::SyncUp};
2 use crate::configuration::Configuration;
3 use crate::constants::METADATA_FILENAME;
4 use crate::metadata::Metadata;
6 use std::fs::{copy, create_dir_all, read_dir, remove_dir_all, write};
7 use std::io::{Error, ErrorKind, Result};
8 use std::path::{Path, PathBuf};
13 pub fn new() -> Self {
17 fn copy_post(source: &PathBuf, target: &Path) -> Result<()> {
18 let post_name = source
20 .ok_or_else(|| Error::new(ErrorKind::InvalidInput, "Could not get post filename."))?;
22 let target_post = target.join(post_name);
23 copy(source, target_post)?;
27 fn write_metadata(metadata: &Metadata, metadata_location: &PathBuf) -> Result<()> {
28 let serialized_metadata = serde_json::to_string(&metadata)?;
29 write(metadata_location, serialized_metadata)?;
33 fn archive(source: &PathBuf, target: &Path) -> Result<()> {
34 let entries = read_dir(source)?;
35 for entry in entries {
37 let entry_type = entry.file_type()?;
38 let entry_name = entry.file_name();
39 let entry_source = entry.path();
40 let entry_target = target.join(entry_name);
42 if entry_type.is_dir() {
43 Update::archive(&entry_source, &entry_target)?;
45 copy(&entry_source, &entry_target)?;
53 impl super::Command for Update {
54 fn before_dependencies(&self) -> Vec<Box<dyn super::Command>> {
55 vec![Box::new(SyncDown::new())]
60 input: Option<&String>,
61 configuration: &Configuration,
64 let input = input.ok_or_else(|| {
65 Error::new(ErrorKind::InvalidInput, "You must provide a path to a post")
67 let post_location = PathBuf::from(input);
68 if !post_location.exists() {
69 return Err(Error::new(
71 "The path provided does not exist",
75 // Step 1. Write into the ephemeral posts
77 create_dir_all(&configuration.posts_directory)?;
79 let first_post_path = configuration.posts_directory.join("0");
80 let metadata_file_path = first_post_path.join(METADATA_FILENAME);
81 let metadata = Metadata::read_or_create(&metadata_file_path);
83 let _ = remove_dir_all(&first_post_path);
84 create_dir_all(&first_post_path)?;
86 Update::copy_post(&post_location, &first_post_path)?;
87 Update::write_metadata(&metadata, &metadata_file_path)?;
89 // Step 2. Write into the archive
91 create_dir_all(&configuration.archive_directory)?;
93 let post_archive_path = configuration.archive_directory.join(metadata.id);
94 let _ = remove_dir_all(&post_archive_path);
95 create_dir_all(&post_archive_path)?;
97 Update::archive(&first_post_path, &post_archive_path)?;
101 fn after_dependencies(&self) -> Vec<Box<dyn super::Command>> {
102 vec![Box::new(Generate::new()), Box::new(SyncUp::new())]
105 fn command(&self) -> &'static str {
109 fn help(&self) -> &'static str {
110 "<path_to_post>\t\tUpdates latest blog post"