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.

306 lines
9.6KB

  1. #[macro_use]
  2. extern crate serde_derive;
  3. extern crate toml;
  4. #[macro_use]
  5. extern crate errors;
  6. extern crate highlighting;
  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 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('/') || path.is_empty() { "" } 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 if path.starts_with('/') {
  105. format!("{}{}{}", self.base_url, path, trailing_bit)
  106. } else {
  107. format!("{}/{}{}", self.base_url, path, trailing_bit)
  108. }
  109. }
  110. /// Merges the extra data from the theme with the config extra data
  111. fn add_theme_extra(&mut self, theme: &Theme) -> Result<()> {
  112. if let Some(ref mut config_extra) = self.extra {
  113. // 3 pass merging
  114. // 1. save config to preserve user
  115. let original = config_extra.clone();
  116. // 2. inject theme extra values
  117. for (key, val) in &theme.extra {
  118. config_extra.entry(key.to_string()).or_insert_with(|| val.clone());
  119. }
  120. // 3. overwrite with original config
  121. for (key, val) in &original {
  122. config_extra.entry(key.to_string()).or_insert_with(|| val.clone());
  123. }
  124. }
  125. Ok(())
  126. }
  127. /// Parse the theme.toml file and merges the extra data from the theme
  128. /// with the config extra data
  129. pub fn merge_with_theme(&mut self, path: &PathBuf) -> Result<()> {
  130. let theme = Theme::from_file(path)?;
  131. self.add_theme_extra(&theme)
  132. }
  133. }
  134. /// Exists only for testing purposes
  135. #[doc(hidden)]
  136. impl Default for Config {
  137. fn default() -> Config {
  138. Config {
  139. title: Some("".to_string()),
  140. theme: None,
  141. base_url: "http://a-website.com/".to_string(),
  142. highlight_code: Some(true),
  143. highlight_theme: Some("base16-ocean-dark".to_string()),
  144. description: None,
  145. language_code: Some("en".to_string()),
  146. generate_rss: Some(false),
  147. rss_limit: Some(10_000),
  148. generate_tags_pages: Some(true),
  149. generate_categories_pages: Some(true),
  150. compile_sass: Some(false),
  151. extra: None,
  152. build_timestamp: Some(1),
  153. }
  154. }
  155. }
  156. /// Get and parse the config.
  157. /// If it doesn't succeed, exit
  158. pub fn get_config(path: &Path, filename: &str) -> Config {
  159. match Config::from_file(path.join(filename)) {
  160. Ok(c) => c,
  161. Err(e) => {
  162. println!("Failed to load {}", filename);
  163. println!("Error: {}", e);
  164. ::std::process::exit(1);
  165. }
  166. }
  167. }
  168. #[cfg(test)]
  169. mod tests {
  170. use super::{Config, Theme};
  171. #[test]
  172. fn can_import_valid_config() {
  173. let config = r#"
  174. title = "My site"
  175. base_url = "https://replace-this-with-your-url.com"
  176. "#;
  177. let config = Config::parse(config).unwrap();
  178. assert_eq!(config.title.unwrap(), "My site".to_string());
  179. }
  180. #[test]
  181. fn errors_when_invalid_type() {
  182. let config = r#"
  183. title = 1
  184. base_url = "https://replace-this-with-your-url.com"
  185. "#;
  186. let config = Config::parse(config);
  187. assert!(config.is_err());
  188. }
  189. #[test]
  190. fn errors_when_missing_required_field() {
  191. // base_url is required
  192. let config = r#"
  193. title = ""
  194. "#;
  195. let config = Config::parse(config);
  196. assert!(config.is_err());
  197. }
  198. #[test]
  199. fn can_add_extra_values() {
  200. let config = r#"
  201. title = "My site"
  202. base_url = "https://replace-this-with-your-url.com"
  203. [extra]
  204. hello = "world"
  205. "#;
  206. let config = Config::parse(config);
  207. assert!(config.is_ok());
  208. assert_eq!(config.unwrap().extra.unwrap().get("hello").unwrap().as_str().unwrap(), "world");
  209. }
  210. #[test]
  211. fn can_make_url_index_page_with_non_trailing_slash_url() {
  212. let mut config = Config::default();
  213. config.base_url = "http://vincent.is".to_string();
  214. assert_eq!(config.make_permalink(""), "http://vincent.is/");
  215. }
  216. #[test]
  217. fn can_make_url_index_page_with_railing_slash_url() {
  218. let mut config = Config::default();
  219. config.base_url = "http://vincent.is/".to_string();
  220. assert_eq!(config.make_permalink(""), "http://vincent.is/");
  221. }
  222. #[test]
  223. fn can_make_url_with_non_trailing_slash_base_url() {
  224. let mut config = Config::default();
  225. config.base_url = "http://vincent.is".to_string();
  226. assert_eq!(config.make_permalink("hello"), "http://vincent.is/hello/");
  227. }
  228. #[test]
  229. fn can_make_url_with_trailing_slash_path() {
  230. let mut config = Config::default();
  231. config.base_url = "http://vincent.is/".to_string();
  232. assert_eq!(config.make_permalink("/hello"), "http://vincent.is/hello/");
  233. }
  234. #[test]
  235. fn can_make_url_with_localhost() {
  236. let mut config = Config::default();
  237. config.base_url = "http://127.0.0.1:1111".to_string();
  238. assert_eq!(config.make_permalink("/tags/rust"), "http://127.0.0.1:1111/tags/rust/");
  239. }
  240. #[test]
  241. fn can_merge_with_theme_data_and_preserve_config_value() {
  242. let config_str = r#"
  243. title = "My site"
  244. base_url = "https://replace-this-with-your-url.com"
  245. [extra]
  246. hello = "world"
  247. "#;
  248. let mut config = Config::parse(config_str).unwrap();
  249. let theme_str = r#"
  250. [extra]
  251. hello = "foo"
  252. a_value = 10
  253. "#;
  254. let theme = Theme::parse(theme_str).unwrap();
  255. assert!(config.add_theme_extra(&theme).is_ok());
  256. let extra = config.extra.unwrap();
  257. assert_eq!(extra["hello"].as_str().unwrap(), "world".to_string());
  258. assert_eq!(extra["a_value"].as_integer().unwrap(), 10);
  259. }
  260. }