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.

334 lines
10KB

  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 default_language: 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. /// Languages list and translated strings
  45. pub translations: Option<HashMap<String, Toml>>,
  46. /// All user params set in [extra] in the config
  47. pub extra: Option<HashMap<String, Toml>>,
  48. /// Set automatically when instantiating the config. Used for cachebusting
  49. pub build_timestamp: Option<i64>,
  50. }
  51. macro_rules! set_default {
  52. ($key: expr, $default: expr) => {
  53. if $key.is_none() {
  54. $key = Some($default);
  55. }
  56. }
  57. }
  58. impl Config {
  59. /// Parses a string containing TOML to our Config struct
  60. /// Any extra parameter will end up in the extra field
  61. pub fn parse(content: &str) -> Result<Config> {
  62. let mut config: Config = match toml::from_str(content) {
  63. Ok(c) => c,
  64. Err(e) => bail!(e)
  65. };
  66. set_default!(config.default_language, "en".to_string());
  67. set_default!(config.highlight_code, false);
  68. set_default!(config.generate_rss, false);
  69. set_default!(config.rss_limit, 20);
  70. set_default!(config.generate_tags_pages, false);
  71. set_default!(config.generate_categories_pages, false);
  72. set_default!(config.compile_sass, false);
  73. set_default!(config.translations, HashMap::new());
  74. set_default!(config.extra, HashMap::new());
  75. match config.highlight_theme {
  76. Some(ref t) => {
  77. if !THEME_SET.themes.contains_key(t) {
  78. bail!("Theme {} not available", t)
  79. }
  80. }
  81. None => config.highlight_theme = Some("base16-ocean-dark".to_string())
  82. };
  83. config.build_timestamp = Some(Utc::now().timestamp());
  84. Ok(config)
  85. }
  86. /// Parses a config file from the given path
  87. pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Config> {
  88. let mut content = String::new();
  89. File::open(path)
  90. .chain_err(|| "No `config.toml` file found. Are you in the right directory?")?
  91. .read_to_string(&mut content)?;
  92. Config::parse(&content)
  93. }
  94. /// Makes a url, taking into account that the base url might have a trailing slash
  95. pub fn make_permalink(&self, path: &str) -> String {
  96. let trailing_bit = if path.ends_with('/') || path.is_empty() { "" } else { "/" };
  97. // Index section with a base url that has a trailing slash
  98. if self.base_url.ends_with('/') && path == "/" {
  99. self.base_url.clone()
  100. } else if path == "/" {
  101. // index section with a base url that doesn't have a trailing slash
  102. format!("{}/", self.base_url)
  103. } else if self.base_url.ends_with('/') && path.starts_with('/') {
  104. format!("{}{}{}", self.base_url, &path[1..], trailing_bit)
  105. } else if self.base_url.ends_with('/') {
  106. format!("{}{}{}", self.base_url, path, trailing_bit)
  107. } else if path.starts_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_with(|| val.clone());
  122. }
  123. // 3. overwrite with original config
  124. for (key, val) in &original {
  125. config_extra.entry(key.to_string()).or_insert_with(|| 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. default_language: Some("en".to_string()),
  149. generate_rss: Some(false),
  150. rss_limit: Some(10_000),
  151. generate_tags_pages: Some(true),
  152. generate_categories_pages: Some(true),
  153. compile_sass: Some(false),
  154. translations: None,
  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_index_page_with_non_trailing_slash_url() {
  216. let mut config = Config::default();
  217. config.base_url = "http://vincent.is".to_string();
  218. assert_eq!(config.make_permalink(""), "http://vincent.is/");
  219. }
  220. #[test]
  221. fn can_make_url_index_page_with_railing_slash_url() {
  222. let mut config = Config::default();
  223. config.base_url = "http://vincent.is/".to_string();
  224. assert_eq!(config.make_permalink(""), "http://vincent.is/");
  225. }
  226. #[test]
  227. fn can_make_url_with_non_trailing_slash_base_url() {
  228. let mut config = Config::default();
  229. config.base_url = "http://vincent.is".to_string();
  230. assert_eq!(config.make_permalink("hello"), "http://vincent.is/hello/");
  231. }
  232. #[test]
  233. fn can_make_url_with_trailing_slash_path() {
  234. let mut config = Config::default();
  235. config.base_url = "http://vincent.is/".to_string();
  236. assert_eq!(config.make_permalink("/hello"), "http://vincent.is/hello/");
  237. }
  238. #[test]
  239. fn can_make_url_with_localhost() {
  240. let mut config = Config::default();
  241. config.base_url = "http://127.0.0.1:1111".to_string();
  242. assert_eq!(config.make_permalink("/tags/rust"), "http://127.0.0.1:1111/tags/rust/");
  243. }
  244. #[test]
  245. fn can_merge_with_theme_data_and_preserve_config_value() {
  246. let config_str = r#"
  247. title = "My site"
  248. base_url = "https://replace-this-with-your-url.com"
  249. [extra]
  250. hello = "world"
  251. "#;
  252. let mut config = Config::parse(config_str).unwrap();
  253. let theme_str = r#"
  254. [extra]
  255. hello = "foo"
  256. a_value = 10
  257. "#;
  258. let theme = Theme::parse(theme_str).unwrap();
  259. assert!(config.add_theme_extra(&theme).is_ok());
  260. let extra = config.extra.unwrap();
  261. assert_eq!(extra["hello"].as_str().unwrap(), "world".to_string());
  262. assert_eq!(extra["a_value"].as_integer().unwrap(), 10);
  263. }
  264. #[test]
  265. fn can_use_language_configuration() {
  266. let config = r#"
  267. base_url = "https://remplace-par-ton-url.fr"
  268. default_language = "fr"
  269. [translations]
  270. [translations.fr]
  271. title = "Un titre"
  272. [translations.en]
  273. title = "A title"
  274. "#;
  275. let config = Config::parse(config);
  276. assert!(config.is_ok());
  277. let translations = config.unwrap().translations.unwrap();
  278. assert_eq!(translations["fr"]["title"].as_str().unwrap(), "Un titre");
  279. assert_eq!(translations["en"]["title"].as_str().unwrap(), "A title");
  280. }
  281. }