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.

213 lines
6.7KB

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