You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

282 lines
8.7KB

  1. #[macro_use]
  2. extern crate serde_derive;
  3. extern crate toml;
  4. #[macro_use]
  5. extern crate errors;
  6. extern crate rendering;
  7. extern crate chrono;
  8. use std::collections::HashMap;
  9. use std::fs::File;
  10. use std::io::prelude::*;
  11. use std::path::{Path, PathBuf};
  12. use toml::{Value as Toml};
  13. use chrono::Utc;
  14. use errors::{Result, ResultExt};
  15. use rendering::highlighting::THEME_SET;
  16. mod theme;
  17. use theme::Theme;
  18. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
  19. pub struct Config {
  20. /// Base URL of the site, the only required config argument
  21. pub base_url: String,
  22. /// Theme to use
  23. pub theme: Option<String>,
  24. /// Title of the site. Defaults to None
  25. pub title: Option<String>,
  26. /// Whether to highlight all code blocks found in markdown files. Defaults to false
  27. pub highlight_code: Option<bool>,
  28. /// Which themes to use for code highlighting. See Readme for supported themes
  29. pub highlight_theme: Option<String>,
  30. /// Description of the site
  31. pub description: Option<String>,
  32. /// The language used in the site. Defaults to "en"
  33. pub language_code: Option<String>,
  34. /// Whether to generate RSS. Defaults to false
  35. pub generate_rss: Option<bool>,
  36. /// The number of articles to include in the RSS feed. Defaults to unlimited
  37. pub rss_limit: Option<usize>,
  38. /// Whether to generate tags and individual tag pages if some pages have them. Defaults to true
  39. pub generate_tags_pages: Option<bool>,
  40. /// Whether to generate categories and individual tag categories if some pages have them. Defaults to true
  41. pub generate_categories_pages: Option<bool>,
  42. /// Whether to compile the `sass` directory and output the css files into the static folder
  43. pub compile_sass: Option<bool>,
  44. /// All user params set in [extra] in the config
  45. pub extra: Option<HashMap<String, Toml>>,
  46. /// Set automatically when instantiating the config. Used for cachebusting
  47. pub build_timestamp: Option<i64>,
  48. }
  49. macro_rules! set_default {
  50. ($key: expr, $default: expr) => {
  51. if $key.is_none() {
  52. $key = Some($default);
  53. }
  54. }
  55. }
  56. impl Config {
  57. /// Parses a string containing TOML to our Config struct
  58. /// Any extra parameter will end up in the extra field
  59. pub fn parse(content: &str) -> Result<Config> {
  60. let mut config: Config = match toml::from_str(content) {
  61. Ok(c) => c,
  62. Err(e) => bail!(e)
  63. };
  64. set_default!(config.language_code, "en".to_string());
  65. set_default!(config.highlight_code, false);
  66. set_default!(config.generate_rss, false);
  67. set_default!(config.rss_limit, 20);
  68. set_default!(config.generate_tags_pages, false);
  69. set_default!(config.generate_categories_pages, false);
  70. set_default!(config.compile_sass, false);
  71. set_default!(config.extra, HashMap::new());
  72. match config.highlight_theme {
  73. Some(ref t) => {
  74. if !THEME_SET.themes.contains_key(t) {
  75. bail!("Theme {} not available", t)
  76. }
  77. }
  78. None => config.highlight_theme = Some("base16-ocean-dark".to_string())
  79. };
  80. config.build_timestamp = Some(Utc::now().timestamp());
  81. Ok(config)
  82. }
  83. /// Parses a config file from the given path
  84. pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Config> {
  85. let mut content = String::new();
  86. File::open(path)
  87. .chain_err(|| "No `config.toml` file found. Are you in the right directory?")?
  88. .read_to_string(&mut content)?;
  89. Config::parse(&content)
  90. }
  91. /// Makes a url, taking into account that the base url might have a trailing slash
  92. pub fn make_permalink(&self, path: &str) -> String {
  93. let trailing_bit = if path.ends_with('/') { "" } else { "/" };
  94. // Index section with a base url that has a trailing slash
  95. if self.base_url.ends_with('/') && path == "/" {
  96. self.base_url.clone()
  97. } else if path == "/" {
  98. // index section with a base url that doesn't have a trailing slash
  99. format!("{}/", self.base_url)
  100. } else if self.base_url.ends_with('/') && path.starts_with('/') {
  101. format!("{}{}{}", self.base_url, &path[1..], trailing_bit)
  102. } else if self.base_url.ends_with('/') {
  103. format!("{}{}{}", self.base_url, path, trailing_bit)
  104. } else {
  105. format!("{}/{}{}", self.base_url, path, trailing_bit)
  106. }
  107. }
  108. /// Merges the extra data from the theme with the config extra data
  109. fn add_theme_extra(&mut self, theme: &Theme) -> Result<()> {
  110. if let Some(ref mut config_extra) = self.extra {
  111. // 3 pass merging
  112. // 1. save config to preserve user
  113. let original = config_extra.clone();
  114. // 2. inject theme extra values
  115. for (key, val) in &theme.extra {
  116. config_extra.entry(key.to_string()).or_insert_with(|| val.clone());
  117. }
  118. // 3. overwrite with original config
  119. for (key, val) in &original {
  120. config_extra.entry(key.to_string()).or_insert_with(|| val.clone());
  121. }
  122. }
  123. Ok(())
  124. }
  125. /// Parse the theme.toml file and merges the extra data from the theme
  126. /// with the config extra data
  127. pub fn merge_with_theme(&mut self, path: &PathBuf) -> Result<()> {
  128. let theme = Theme::from_file(path)?;
  129. self.add_theme_extra(&theme)
  130. }
  131. }
  132. /// Exists only for testing purposes
  133. #[doc(hidden)]
  134. impl Default for Config {
  135. fn default() -> Config {
  136. Config {
  137. title: Some("".to_string()),
  138. theme: None,
  139. base_url: "http://a-website.com/".to_string(),
  140. highlight_code: Some(true),
  141. highlight_theme: Some("base16-ocean-dark".to_string()),
  142. description: None,
  143. language_code: Some("en".to_string()),
  144. generate_rss: Some(false),
  145. rss_limit: Some(10_000),
  146. generate_tags_pages: Some(true),
  147. generate_categories_pages: Some(true),
  148. compile_sass: Some(false),
  149. extra: None,
  150. build_timestamp: Some(1),
  151. }
  152. }
  153. }
  154. /// Get and parse the config.
  155. /// If it doesn't succeed, exit
  156. pub fn get_config(path: &Path, filename: &str) -> Config {
  157. match Config::from_file(path.join(filename)) {
  158. Ok(c) => c,
  159. Err(e) => {
  160. println!("Failed to load {}", filename);
  161. println!("Error: {}", e);
  162. ::std::process::exit(1);
  163. }
  164. }
  165. }
  166. #[cfg(test)]
  167. mod tests {
  168. use super::{Config, Theme};
  169. #[test]
  170. fn can_import_valid_config() {
  171. let config = r#"
  172. title = "My site"
  173. base_url = "https://replace-this-with-your-url.com"
  174. "#;
  175. let config = Config::parse(config).unwrap();
  176. assert_eq!(config.title.unwrap(), "My site".to_string());
  177. }
  178. #[test]
  179. fn errors_when_invalid_type() {
  180. let config = r#"
  181. title = 1
  182. base_url = "https://replace-this-with-your-url.com"
  183. "#;
  184. let config = Config::parse(config);
  185. assert!(config.is_err());
  186. }
  187. #[test]
  188. fn errors_when_missing_required_field() {
  189. // base_url is required
  190. let config = r#"
  191. title = ""
  192. "#;
  193. let config = Config::parse(config);
  194. assert!(config.is_err());
  195. }
  196. #[test]
  197. fn can_add_extra_values() {
  198. let config = r#"
  199. title = "My site"
  200. base_url = "https://replace-this-with-your-url.com"
  201. [extra]
  202. hello = "world"
  203. "#;
  204. let config = Config::parse(config);
  205. assert!(config.is_ok());
  206. assert_eq!(config.unwrap().extra.unwrap().get("hello").unwrap().as_str().unwrap(), "world");
  207. }
  208. #[test]
  209. fn can_make_url_with_non_trailing_slash_base_url() {
  210. let mut config = Config::default();
  211. config.base_url = "http://vincent.is".to_string();
  212. assert_eq!(config.make_permalink("hello"), "http://vincent.is/hello/");
  213. }
  214. #[test]
  215. fn can_make_url_with_trailing_slash_path() {
  216. let mut config = Config::default();
  217. config.base_url = "http://vincent.is/".to_string();
  218. assert_eq!(config.make_permalink("/hello"), "http://vincent.is/hello/");
  219. }
  220. #[test]
  221. fn can_merge_with_theme_data_and_preserve_config_value() {
  222. let config_str = r#"
  223. title = "My site"
  224. base_url = "https://replace-this-with-your-url.com"
  225. [extra]
  226. hello = "world"
  227. "#;
  228. let mut config = Config::parse(config_str).unwrap();
  229. let theme_str = r#"
  230. [extra]
  231. hello = "foo"
  232. a_value = 10
  233. "#;
  234. let theme = Theme::parse(theme_str).unwrap();
  235. assert!(config.add_theme_extra(&theme).is_ok());
  236. let extra = config.extra.unwrap();
  237. assert_eq!(extra["hello"].as_str().unwrap(), "world".to_string());
  238. assert_eq!(extra["a_value"].as_integer().unwrap(), 10);
  239. }
  240. }