natter/src/blog_post/convert.rs
Tom Alexander 3ac7826d2c
Move the logic into convert_blog_post_page_to_render_context.
I was writing it in the build command's rust files for convenience, but now its getting long enough to warrant moving it into its final location.
2023-10-23 22:10:26 -04:00

76 lines
2.4 KiB
Rust

use std::path::Path;
use std::path::PathBuf;
use crate::config::Config;
use crate::error::CustomError;
use super::render_context::GlobalSettings;
use super::render_context::RenderBlogPostPage;
use super::BlogPost;
use super::BlogPostPage;
pub(crate) fn convert_blog_post_page_to_render_context<D: AsRef<Path>, F: AsRef<Path>>(
config: &Config,
output_directory: D,
output_file: F,
_post: &BlogPost,
page: &BlogPostPage,
) -> Result<RenderBlogPostPage, CustomError> {
let output_directory = output_directory.as_ref();
let output_file = output_file.as_ref();
let css_files = vec![get_web_path(
config,
output_directory,
output_file,
"main.css",
)?];
let js_files = vec![get_web_path(
config,
output_directory,
output_file,
"blog_post.js",
)?];
let global_settings = GlobalSettings::new(page.title.clone(), css_files, js_files);
let ret = RenderBlogPostPage::new(global_settings, page.title.clone());
Ok(ret)
}
fn get_web_path<D: AsRef<Path>, F: AsRef<Path>, P: AsRef<Path>>(
config: &Config,
output_directory: D,
containing_file: F,
path_from_web_root: P,
) -> Result<String, CustomError> {
let path_from_web_root = path_from_web_root.as_ref();
if config.use_relative_paths() {
let output_directory = output_directory.as_ref();
let containing_file = containing_file.as_ref();
// Subtracting 1 from the depth to "remove" the file name.
let depth_from_web_root = containing_file
.strip_prefix(output_directory)?
.components()
.count()
- 1;
let prefix = "../".repeat(depth_from_web_root);
let final_path = PathBuf::from(prefix).join(path_from_web_root);
let final_string = final_path
.as_path()
.to_str()
.map(str::to_string)
.ok_or("Path should be valid utf-8.")?;
Ok(final_string)
} else {
let web_root = config
.get_web_root()
.ok_or("Must either use_relative_paths or set the web_root in the config.")?;
let final_path = PathBuf::from(web_root).join(path_from_web_root);
let final_string = final_path
.as_path()
.to_str()
.map(str::to_string)
.ok_or("Path should be valid utf-8.")?;
Ok(final_string)
}
}