use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use std::path::Path;
use crate::config::{ApplyLayer, ApplyOptExt, ApplyValExt};
use crate::errors::*;
#[derive(Debug, Clone)]
pub struct MdBookConfig {
pub path: Option<String>,
pub theme: bool,
}
#[derive(Debug, Default, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct MdBookLayer {
pub path: Option<String>,
pub theme: Option<bool>,
}
impl Default for MdBookConfig {
fn default() -> Self {
MdBookConfig {
path: None,
theme: true,
}
}
}
impl ApplyLayer for MdBookConfig {
type Layer = MdBookLayer;
fn apply_layer(&mut self, layer: Self::Layer) {
let MdBookLayer { path, theme } = layer;
self.path.apply_opt(path);
self.theme.apply_val(theme);
}
}
impl MdBookConfig {
pub fn find_paths(config: &mut Option<MdBookConfig>, start_dir: &Path) -> Result<()> {
let Some(this) = config else {
return Ok(());
};
if this.path.is_none() {
let possible_paths = vec!["./", "./book/", "./docs/"];
for book_dir in possible_paths {
let book_path = start_dir.join(book_dir).join("book.toml");
if book_path.exists() {
this.path = Some(book_dir.to_owned());
return Ok(());
}
}
}
let MdBookConfig { path, theme } = this;
let cant_find_files = path.is_none();
let has_user_config = *theme != MdBookConfig::default().theme;
if cant_find_files {
if has_user_config {
return Err(OrandaError::MdBookConfigInvalid);
} else {
*config = None;
}
}
Ok(())
}
}