2023-10-20 18:39:26 -04:00
use std ::path ::Path ;
2023-10-18 21:25:37 -04:00
use std ::path ::PathBuf ;
use tokio ::fs ::File ;
use tokio ::io ::AsyncWriteExt ;
2023-10-22 13:44:03 -04:00
use crate ::error ::CustomError ;
2023-10-18 21:25:37 -04:00
use super ::raw ::RawConfig ;
/// This is the config struct used by most of the code, which is an interpreted version of the RawConfig struct which is the raw disk-representation of the config.
pub ( crate ) struct Config {
raw : RawConfig ,
2023-10-20 18:45:24 -04:00
config_path : PathBuf ,
2023-10-18 21:25:37 -04:00
}
impl Config {
2023-10-22 13:44:03 -04:00
pub ( crate ) fn new < P : AsRef < Path > > ( root_dir : P ) -> Result < Config , CustomError > {
fn inner ( root_dir : & Path ) -> Result < Config , CustomError > {
2023-10-20 18:45:24 -04:00
let file_path = root_dir . join ( " writer.toml " ) ;
Ok ( Config {
raw : RawConfig ::default ( ) ,
config_path : file_path ,
} )
}
inner ( root_dir . as_ref ( ) )
2023-10-18 21:25:37 -04:00
}
2023-10-22 13:44:03 -04:00
pub ( crate ) async fn load_from_file < P : Into < PathBuf > > ( path : P ) -> Result < Config , CustomError > {
async fn inner ( path : PathBuf ) -> Result < Config , CustomError > {
2023-10-20 18:45:24 -04:00
let contents = tokio ::fs ::read_to_string ( & path ) . await ? ;
2023-10-20 18:39:26 -04:00
let parsed_contents : RawConfig = toml ::from_str ( contents . as_str ( ) ) ? ;
Ok ( Config {
raw : parsed_contents ,
2023-10-20 18:45:24 -04:00
config_path : path ,
2023-10-20 18:39:26 -04:00
} )
}
2023-10-20 18:45:24 -04:00
inner ( path . into ( ) ) . await
2023-10-20 18:39:26 -04:00
}
2023-10-22 13:44:03 -04:00
pub ( crate ) async fn write_to_disk ( & self ) -> Result < ( ) , CustomError > {
2023-10-20 18:45:24 -04:00
let mut config_file = File ::create ( & self . config_path ) . await ? ;
2023-10-18 21:25:37 -04:00
config_file
. write_all ( toml ::to_string ( & self . raw ) ? . as_bytes ( ) )
. await ? ;
Ok ( ( ) )
}
2023-10-20 20:16:22 -04:00
pub ( crate ) fn get_root_directory ( & self ) -> & Path {
& self
. config_path
. parent ( )
. expect ( " Config file must exist inside a directory. " )
}
2023-10-22 13:44:03 -04:00
pub ( crate ) fn get_posts_directory ( & self ) -> PathBuf {
self . get_root_directory ( ) . join ( " posts " )
}
2023-10-22 14:40:59 -04:00
pub ( crate ) fn get_output_directory ( & self ) -> PathBuf {
self . get_root_directory ( ) . join ( " output " )
}
2023-10-23 21:51:15 -04:00
pub ( crate ) fn use_relative_paths ( & self ) -> bool {
self . raw . use_relative_paths . unwrap_or ( true )
}
pub ( crate ) fn get_web_root ( & self ) -> Option < & str > {
self . raw . web_root . as_deref ( )
}
2023-10-18 21:25:37 -04:00
}