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.

220 lines
6.8KB

  1. #[macro_use]
  2. extern crate serde_derive;
  3. extern crate toml;
  4. #[macro_use]
  5. extern crate errors;
  6. extern crate rendering;
  7. use std::collections::HashMap;
  8. use std::fs::File;
  9. use std::io::prelude::*;
  10. use std::path::Path;
  11. use toml::{Value as Toml};
  12. use errors::{Result, ResultExt};
  13. use rendering::highlighting::THEME_SET;
  14. #[derive(Debug, PartialEq, Serialize, Deserialize)]
  15. pub struct Config {
  16. /// Title of the site
  17. pub title: String,
  18. /// Base URL of the site
  19. pub base_url: String,
  20. /// Whether to highlight all code blocks found in markdown files. Defaults to false
  21. pub highlight_code: Option<bool>,
  22. /// Which themes to use for code highlighting. See Readme for supported themes
  23. pub highlight_theme: Option<String>,
  24. /// Description of the site
  25. pub description: Option<String>,
  26. /// The language used in the site. Defaults to "en"
  27. pub language_code: Option<String>,
  28. /// Whether to generate RSS. Defaults to false
  29. pub generate_rss: Option<bool>,
  30. /// The number of articles to include in the RSS feed. Defaults to unlimited
  31. pub rss_limit: Option<usize>,
  32. /// Whether to generate tags and individual tag pages if some pages have them. Defaults to true
  33. pub generate_tags_pages: Option<bool>,
  34. /// Whether to generate categories and individual tag categories if some pages have them. Defaults to true
  35. pub generate_categories_pages: Option<bool>,
  36. /// Whether to insert a link for each header like in Github READMEs. Defaults to false
  37. /// The default template can be overridden by creating a `anchor-link.html` template and CSS will need to be
  38. /// written if you turn that on.
  39. pub insert_anchor_links: Option<bool>,
  40. /// All user params set in [extra] in the config
  41. pub extra: Option<HashMap<String, Toml>>,
  42. }
  43. macro_rules! set_default {
  44. ($key: expr, $default: expr) => {
  45. if $key.is_none() {
  46. $key = Some($default);
  47. }
  48. }
  49. }
  50. impl Config {
  51. /// Parses a string containing TOML to our Config struct
  52. /// Any extra parameter will end up in the extra field
  53. pub fn parse(content: &str) -> Result<Config> {
  54. let mut config: Config = match toml::from_str(content) {
  55. Ok(c) => c,
  56. Err(e) => bail!(e)
  57. };
  58. set_default!(config.language_code, "en".to_string());
  59. set_default!(config.highlight_code, false);
  60. set_default!(config.generate_rss, false);
  61. set_default!(config.rss_limit, 20);
  62. set_default!(config.generate_tags_pages, false);
  63. set_default!(config.generate_categories_pages, false);
  64. set_default!(config.insert_anchor_links, false);
  65. match config.highlight_theme {
  66. Some(ref t) => {
  67. if !THEME_SET.themes.contains_key(t) {
  68. bail!("Theme {} not available", t)
  69. }
  70. }
  71. None => config.highlight_theme = Some("base16-ocean-dark".to_string())
  72. };
  73. Ok(config)
  74. }
  75. /// Parses a config file from the given path
  76. pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Config> {
  77. let mut content = String::new();
  78. File::open(path)
  79. .chain_err(|| "No `config.toml` file found. Are you in the right directory?")?
  80. .read_to_string(&mut content)?;
  81. Config::parse(&content)
  82. }
  83. /// Makes a url, taking into account that the base url might have a trailing slash
  84. pub fn make_permalink(&self, path: &str) -> String {
  85. let trailing_bit = if path.ends_with('/') { "" } else { "/" };
  86. // Index section with a base url that has a trailing slash
  87. if self.base_url.ends_with('/') && path == "/" {
  88. self.base_url.clone()
  89. } else if path == "/" {
  90. // index section with a base url that doesn't have a trailing slash
  91. format!("{}/", self.base_url)
  92. } else if self.base_url.ends_with('/') && path.starts_with('/') {
  93. format!("{}{}{}", self.base_url, &path[1..], trailing_bit)
  94. } else if self.base_url.ends_with('/') {
  95. format!("{}{}{}", self.base_url, path, trailing_bit)
  96. } else {
  97. format!("{}/{}{}", self.base_url, path, trailing_bit)
  98. }
  99. }
  100. }
  101. /// Exists only for testing purposes
  102. #[doc(hidden)]
  103. impl Default for Config {
  104. fn default() -> Config {
  105. Config {
  106. title: "".to_string(),
  107. base_url: "http://a-website.com/".to_string(),
  108. highlight_code: Some(true),
  109. highlight_theme: Some("base16-ocean-dark".to_string()),
  110. description: None,
  111. language_code: Some("en".to_string()),
  112. generate_rss: Some(false),
  113. rss_limit: Some(10000),
  114. generate_tags_pages: Some(true),
  115. generate_categories_pages: Some(true),
  116. insert_anchor_links: Some(false),
  117. extra: None,
  118. }
  119. }
  120. }
  121. /// Get and parse the config.
  122. /// If it doesn't succeed, exit
  123. pub fn get_config(path: &Path, filename: &str) -> Config {
  124. match Config::from_file(path.join(filename)) {
  125. Ok(c) => c,
  126. Err(e) => {
  127. println!("Failed to load {}", filename);
  128. println!("Error: {}", e);
  129. ::std::process::exit(1);
  130. }
  131. }
  132. }
  133. #[cfg(test)]
  134. mod tests {
  135. use super::{Config};
  136. #[test]
  137. fn can_import_valid_config() {
  138. let config = r#"
  139. title = "My site"
  140. base_url = "https://replace-this-with-your-url.com"
  141. "#;
  142. let config = Config::parse(config).unwrap();
  143. assert_eq!(config.title, "My site".to_string());
  144. }
  145. #[test]
  146. fn errors_when_invalid_type() {
  147. let config = r#"
  148. title = 1
  149. base_url = "https://replace-this-with-your-url.com"
  150. "#;
  151. let config = Config::parse(config);
  152. assert!(config.is_err());
  153. }
  154. #[test]
  155. fn errors_when_missing_required_field() {
  156. // base_url is required
  157. let config = r#"
  158. title = ""
  159. "#;
  160. let config = Config::parse(config);
  161. assert!(config.is_err());
  162. }
  163. #[test]
  164. fn can_add_extra_values() {
  165. let config = r#"
  166. title = "My site"
  167. base_url = "https://replace-this-with-your-url.com"
  168. [extra]
  169. hello = "world"
  170. "#;
  171. let config = Config::parse(config);
  172. assert!(config.is_ok());
  173. assert_eq!(config.unwrap().extra.unwrap().get("hello").unwrap().as_str().unwrap(), "world");
  174. }
  175. #[test]
  176. fn can_make_url_with_non_trailing_slash_base_url() {
  177. let mut config = Config::default();
  178. config.base_url = "http://vincent.is".to_string();
  179. assert_eq!(config.make_permalink("hello"), "http://vincent.is/hello/");
  180. }
  181. #[test]
  182. fn can_make_url_with_trailing_slash_path() {
  183. let mut config = Config::default();
  184. config.base_url = "http://vincent.is/".to_string();
  185. assert_eq!(config.make_permalink("/hello"), "http://vincent.is/hello/");
  186. }
  187. }