natter/src/command/build/runner.rs

51 lines
1.8 KiB
Rust
Raw Normal View History

2023-10-22 14:40:59 -04:00
use std::path::PathBuf;
use crate::blog_post::BlogPost;
use crate::cli::parameters::BuildArgs;
use crate::config::Config;
use crate::error::CustomError;
use walkdir::WalkDir;
pub(crate) async fn build_site(args: BuildArgs) -> Result<(), CustomError> {
let config = Config::load_from_file(args.config).await?;
let root_directory = config.get_root_directory().to_owned();
2023-10-22 14:40:59 -04:00
let output_directory = get_output_directory(&config).await?;
let post_directories = WalkDir::new(config.get_posts_directory())
.into_iter()
.filter(|e| match e {
Ok(entry) if entry.depth() == 1 && entry.file_type().is_dir() => true,
Ok(_) => false,
Err(_) => true,
})
.collect::<Result<Vec<_>, _>>()?;
let load_jobs = post_directories
.into_iter()
.map(walkdir::DirEntry::into_path)
.map(|path| tokio::spawn(BlogPost::load_blog_post(root_directory.clone(), path)));
let mut blog_posts = Vec::new();
for job in load_jobs {
blog_posts.push(job.await??);
}
println!("{:?}", blog_posts);
Ok(())
}
2023-10-22 14:40:59 -04:00
/// Delete everything inside the output directory and return the path to that directory.
async fn get_output_directory(config: &Config) -> Result<PathBuf, CustomError> {
let output_directory = config.get_output_directory();
if !output_directory.exists() {
tokio::fs::create_dir(&output_directory).await?;
} else {
let mut existing_entries = tokio::fs::read_dir(&output_directory).await?;
while let Some(entry) = existing_entries.next_entry().await? {
let file_type = entry.file_type().await?;
if file_type.is_dir() {
tokio::fs::remove_dir_all(entry.path()).await?;
} else {
tokio::fs::remove_file(entry.path()).await?;
}
}
}
Ok(output_directory)
}