use std::{fs, path::Path};
use serde::{Deserialize, Serialize};
use crate::{BookEngine, BookyardError, Result, error::io_error};
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DetectedBookSource {
pub engine: BookEngine,
pub title: Option<String>,
}
pub fn detect_book_source(path: impl AsRef<Path>) -> Result<DetectedBookSource> {
let path = path.as_ref();
let book_toml = path.join("book.toml");
if !book_toml.exists() {
return Err(BookyardError::UnsupportedBookSource(path.to_path_buf()));
}
let raw = fs::read_to_string(&book_toml).map_err(|source| io_error(&book_toml, source))?;
let value = toml::from_str::<MdBookToml>(&raw).ok();
let title = value.and_then(|v| v.book.and_then(|book| book.title));
Ok(DetectedBookSource {
engine: BookEngine::MdBook,
title,
})
}
#[derive(Debug, Deserialize)]
struct MdBookToml {
book: Option<MdBookSection>,
}
#[derive(Debug, Deserialize)]
struct MdBookSection {
title: Option<String>,
}