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.

288 lines
9.1KB

  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 insert a link for each header like in Github READMEs. Defaults to false
  43. /// The default template can be overridden by creating a `anchor-link.html` template and CSS will need to be
  44. /// written if you turn that on.
  45. pub insert_anchor_links: Option<bool>,
  46. /// Whether to compile the `sass` directory and output the css files into the static folder
  47. pub compile_sass: Option<bool>,
  48. /// All user params set in [extra] in the config
  49. pub extra: Option<HashMap<String, Toml>>,
  50. /// Set automatically when instantiating the config. Used for cachebusting
  51. pub build_timestamp: Option<i64>,
  52. }
  53. macro_rules! set_default {
  54. ($key: expr, $default: expr) => {
  55. if $key.is_none() {
  56. $key = Some($default);
  57. }
  58. }
  59. }
  60. impl Config {
  61. /// Parses a string containing TOML to our Config struct
  62. /// Any extra parameter will end up in the extra field
  63. pub fn parse(content: &str) -> Result<Config> {
  64. let mut config: Config = match toml::from_str(content) {
  65. Ok(c) => c,
  66. Err(e) => bail!(e)
  67. };
  68. set_default!(config.language_code, "en".to_string());
  69. set_default!(config.highlight_code, false);
  70. set_default!(config.generate_rss, false);
  71. set_default!(config.rss_limit, 20);
  72. set_default!(config.generate_tags_pages, false);
  73. set_default!(config.generate_categories_pages, false);
  74. set_default!(config.insert_anchor_links, false);
  75. set_default!(config.compile_sass, false);
  76. set_default!(config.extra, HashMap::new());
  77. match config.highlight_theme {
  78. Some(ref t) => {
  79. if !THEME_SET.themes.contains_key(t) {
  80. bail!("Theme {} not available", t)
  81. }
  82. }
  83. None => config.highlight_theme = Some("base16-ocean-dark".to_string())
  84. };
  85. config.build_timestamp = Some(Utc::now().timestamp());
  86. Ok(config)
  87. }
  88. /// Parses a config file from the given path
  89. pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Config> {
  90. let mut content = String::new();
  91. File::open(path)
  92. .chain_err(|| "No `config.toml` file found. Are you in the right directory?")?
  93. .read_to_string(&mut content)?;
  94. Config::parse(&content)
  95. }
  96. /// Makes a url, taking into account that the base url might have a trailing slash
  97. pub fn make_permalink(&self, path: &str) -> String {
  98. let trailing_bit = if path.ends_with('/') { "" } else { "/" };
  99. // Index section with a base url that has a trailing slash
  100. if self.base_url.ends_with('/') && path == "/" {
  101. self.base_url.clone()
  102. } else if path == "/" {
  103. // index section with a base url that doesn't have a trailing slash
  104. format!("{}/", self.base_url)
  105. } else if self.base_url.ends_with('/') && path.starts_with('/') {
  106. format!("{}{}{}", self.base_url, &path[1..], trailing_bit)
  107. } else if self.base_url.ends_with('/') {
  108. format!("{}{}{}", self.base_url, path, trailing_bit)
  109. } else {
  110. format!("{}/{}{}", self.base_url, path, trailing_bit)
  111. }
  112. }
  113. /// Merges the extra data from the theme with the config extra data
  114. fn add_theme_extra(&mut self, theme: &Theme) -> Result<()> {
  115. if let Some(ref mut config_extra) = self.extra {
  116. // 3 pass merging
  117. // 1. save config to preserve user
  118. let original = config_extra.clone();
  119. // 2. inject theme extra values
  120. for (key, val) in &theme.extra {
  121. config_extra.entry(key.to_string()).or_insert(val.clone());
  122. }
  123. // 3. overwrite with original config
  124. for (key, val) in &original {
  125. config_extra.entry(key.to_string()).or_insert(val.clone());
  126. }
  127. }
  128. Ok(())
  129. }
  130. /// Parse the theme.toml file and merges the extra data from the theme
  131. /// with the config extra data
  132. pub fn merge_with_theme(&mut self, path: &PathBuf) -> Result<()> {
  133. let theme = Theme::from_file(path)?;
  134. self.add_theme_extra(&theme)
  135. }
  136. }
  137. /// Exists only for testing purposes
  138. #[doc(hidden)]
  139. impl Default for Config {
  140. fn default() -> Config {
  141. Config {
  142. title: Some("".to_string()),
  143. theme: None,
  144. base_url: "http://a-website.com/".to_string(),
  145. highlight_code: Some(true),
  146. highlight_theme: Some("base16-ocean-dark".to_string()),
  147. description: None,
  148. language_code: Some("en".to_string()),
  149. generate_rss: Some(false),
  150. rss_limit: Some(10000),
  151. generate_tags_pages: Some(true),
  152. generate_categories_pages: Some(true),
  153. insert_anchor_links: Some(false),
  154. compile_sass: Some(false),
  155. extra: None,
  156. build_timestamp: Some(1),
  157. }
  158. }
  159. }
  160. /// Get and parse the config.
  161. /// If it doesn't succeed, exit
  162. pub fn get_config(path: &Path, filename: &str) -> Config {
  163. match Config::from_file(path.join(filename)) {
  164. Ok(c) => c,
  165. Err(e) => {
  166. println!("Failed to load {}", filename);
  167. println!("Error: {}", e);
  168. ::std::process::exit(1);
  169. }
  170. }
  171. }
  172. #[cfg(test)]
  173. mod tests {
  174. use super::{Config, Theme};
  175. #[test]
  176. fn can_import_valid_config() {
  177. let config = r#"
  178. title = "My site"
  179. base_url = "https://replace-this-with-your-url.com"
  180. "#;
  181. let config = Config::parse(config).unwrap();
  182. assert_eq!(config.title.unwrap(), "My site".to_string());
  183. }
  184. #[test]
  185. fn errors_when_invalid_type() {
  186. let config = r#"
  187. title = 1
  188. base_url = "https://replace-this-with-your-url.com"
  189. "#;
  190. let config = Config::parse(config);
  191. assert!(config.is_err());
  192. }
  193. #[test]
  194. fn errors_when_missing_required_field() {
  195. // base_url is required
  196. let config = r#"
  197. title = ""
  198. "#;
  199. let config = Config::parse(config);
  200. assert!(config.is_err());
  201. }
  202. #[test]
  203. fn can_add_extra_values() {
  204. let config = r#"
  205. title = "My site"
  206. base_url = "https://replace-this-with-your-url.com"
  207. [extra]
  208. hello = "world"
  209. "#;
  210. let config = Config::parse(config);
  211. assert!(config.is_ok());
  212. assert_eq!(config.unwrap().extra.unwrap().get("hello").unwrap().as_str().unwrap(), "world");
  213. }
  214. #[test]
  215. fn can_make_url_with_non_trailing_slash_base_url() {
  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_make_url_with_trailing_slash_path() {
  222. let mut config = Config::default();
  223. config.base_url = "http://vincent.is/".to_string();
  224. assert_eq!(config.make_permalink("/hello"), "http://vincent.is/hello/");
  225. }
  226. #[test]
  227. fn can_merge_with_theme_data_and_preserve_config_value() {
  228. let config_str = r#"
  229. title = "My site"
  230. base_url = "https://replace-this-with-your-url.com"
  231. [extra]
  232. hello = "world"
  233. "#;
  234. let mut config = Config::parse(config_str).unwrap();
  235. let theme_str = r#"
  236. [extra]
  237. hello = "foo"
  238. a_value = 10
  239. "#;
  240. let theme = Theme::parse(theme_str).unwrap();
  241. assert!(config.add_theme_extra(&theme).is_ok());
  242. let extra = config.extra.unwrap();
  243. assert_eq!(extra["hello"].as_str().unwrap(), "world".to_string());
  244. assert_eq!(extra["a_value"].as_integer().unwrap(), 10);
  245. }
  246. }