Skip to main content

bookyard_core/
discover.rs

1use std::{fs, path::Path};
2
3use serde::{Deserialize, Serialize};
4
5use crate::{BookEngine, BookyardError, Result, error::io_error};
6
7#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
8pub struct DetectedBookSource {
9    pub engine: BookEngine,
10    pub title: Option<String>,
11}
12
13pub fn detect_book_source(path: impl AsRef<Path>) -> Result<DetectedBookSource> {
14    let path = path.as_ref();
15    let book_toml = path.join("book.toml");
16    if !book_toml.exists() {
17        return Err(BookyardError::UnsupportedBookSource(path.to_path_buf()));
18    }
19    let raw = fs::read_to_string(&book_toml).map_err(|source| io_error(&book_toml, source))?;
20    let value = toml::from_str::<MdBookToml>(&raw).ok();
21    let title = value.and_then(|v| v.book.and_then(|book| book.title));
22    Ok(DetectedBookSource {
23        engine: BookEngine::MdBook,
24        title,
25    })
26}
27
28#[derive(Debug, Deserialize)]
29struct MdBookToml {
30    book: Option<MdBookSection>,
31}
32
33#[derive(Debug, Deserialize)]
34struct MdBookSection {
35    title: Option<String>,
36}