1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
//! Mdbookshelf's configuration.
//!
//! Heavily inspired by mdbook's Config.

#![deny(missing_docs)]

use failure::Error;
use serde::{Deserialize, Deserializer, Serialize};
use std::fs::File;
use std::io::Read;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use toml::{self, Value};

/// The overall configuration object for MDBookshelf, essentially an in-memory
/// representation of `bookshelf.toml`.
#[derive(Debug, Clone, PartialEq)]
pub struct Config {
    /// An array of BookRepoConfig
    pub book_repo_configs: Vec<BookRepoConfig>,
    /// Destination directory.
    pub destination_dir: Option<PathBuf>,
    /// Templates directory (if not set, will generate manifest.json).
    pub templates_dir: Option<PathBuf>,
    /// Title of the book collection.
    pub title: String,
    /// Working directory.
    pub working_dir: Option<PathBuf>,
}

impl Config {
    /// Load the configuration file from disk.
    pub fn from_disk<P: AsRef<Path>>(config_file: P) -> Result<Config, Error> {
        let mut buffer = String::new();
        File::open(config_file)?.read_to_string(&mut buffer)?;

        Config::from_str(&buffer)
    }
}

impl FromStr for Config {
    type Err = Error;

    /// Load a `Config` from some string.
    fn from_str(src: &str) -> Result<Self, Self::Err> {
        toml::from_str(src).map_err(|e| format_err!("{}", e))
    }
}

impl Default for Config {
    fn default() -> Self {
        Config {
            book_repo_configs: Vec::new(),
            destination_dir: None,
            templates_dir: None,
            title: String::default(),
            working_dir: None,
        }
    }
}
impl<'de> Deserialize<'de> for Config {
    fn deserialize<D: Deserializer<'de>>(de: D) -> Result<Self, D::Error> {
        let raw = Value::deserialize(de)?;

        let mut table = match raw {
            Value::Table(t) => t,
            _ => {
                use serde::de::Error;
                return Err(D::Error::custom(
                    "A config file should always be a toml table",
                ));
            }
        };

        let book_repo_configs: Vec<BookRepoConfig> = table
            .remove("book")
            .and_then(|value| value.try_into().ok())
            .unwrap_or_default();
        let destination_dir: Option<PathBuf> = table
            .remove("destination-dir")
            .and_then(|value| value.try_into().ok())
            .unwrap_or_default();
        let templates_dir: Option<PathBuf> = table
            .remove("templates-dir")
            .and_then(|value| value.try_into().ok())
            .unwrap_or_default();
        let title: String = table
            .remove("title")
            .and_then(|value| value.try_into().ok())
            .unwrap_or_default();
        let working_dir: Option<PathBuf> = table
            .remove("working-dir")
            .and_then(|value| value.try_into().ok())
            .unwrap_or_default();

        Ok(Config {
            book_repo_configs,
            destination_dir,
            templates_dir,
            title,
            working_dir,
        })
    }
}

/// The configuration for a single book
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "kebab-case")]
pub struct BookRepoConfig {
    /// The book's title.  
    /// If set, overwrites the value read from the book itself when generating the manifest.
    pub title: Option<String>,
    /// The book root directory.
    pub folder: Option<PathBuf>,
    /// The git repository url.
    pub repo_url: String,
    /// The online rendered book url.
    pub url: String,
}

impl Default for BookRepoConfig {
    fn default() -> Self {
        BookRepoConfig {
            title: None,
            folder: None,
            repo_url: String::default(),
            url: String::default(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    const COMPLEX_CONFIG: &'static str = r#"
        title = "My bookshelf"
        templates-dir = "templates/"

        [[book]]
        title = "Some Book"
        repo-url = "git_source"
        url = "source"
        folder = "./foo"

        [[book]]
        repo-url = "git_source2"
        url = "source2"
        "#;

    #[test]
    fn load_config_file() {
        let src = COMPLEX_CONFIG;

        let book_repo_configs = vec![
            BookRepoConfig {
                title: Some(String::from("Some Book")),
                folder: Some(PathBuf::from("./foo")),
                repo_url: String::from("git_source"),
                url: String::from("source"),
                ..Default::default()
            },
            BookRepoConfig {
                repo_url: String::from("git_source2"),
                url: String::from("source2"),
                ..Default::default()
            },
        ];

        let got = Config::from_str(src).unwrap();

        assert_eq!(got.title, "My bookshelf");
        assert_eq!(got.templates_dir.unwrap().to_str().unwrap(), "templates/");
        assert_eq!(got.book_repo_configs, book_repo_configs);
    }
}