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.

205 lines
6.2KB

  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. if self.base_url.ends_with('/') && path.starts_with('/') {
  80. format!("{}{}", self.base_url, &path[1..])
  81. } else if self.base_url.ends_with('/') {
  82. format!("{}{}", self.base_url, path)
  83. } else {
  84. format!("{}/{}", self.base_url, path)
  85. }
  86. }
  87. }
  88. /// Exists only for testing purposes
  89. #[doc(hidden)]
  90. impl Default for Config {
  91. fn default() -> Config {
  92. Config {
  93. title: "".to_string(),
  94. base_url: "http://a-website.com/".to_string(),
  95. highlight_code: Some(true),
  96. highlight_theme: Some("base16-ocean-dark".to_string()),
  97. description: None,
  98. language_code: Some("en".to_string()),
  99. generate_rss: Some(false),
  100. rss_limit: Some(10000),
  101. generate_tags_pages: Some(true),
  102. generate_categories_pages: Some(true),
  103. insert_anchor_links: Some(false),
  104. extra: None,
  105. }
  106. }
  107. }
  108. /// Get and parse the config.
  109. /// If it doesn't succeed, exit
  110. pub fn get_config(path: &Path, filename: &str) -> Config {
  111. match Config::from_file(path.join(filename)) {
  112. Ok(c) => c,
  113. Err(e) => {
  114. println!("Failed to load {}", filename);
  115. println!("Error: {}", e);
  116. ::std::process::exit(1);
  117. }
  118. }
  119. }
  120. #[cfg(test)]
  121. mod tests {
  122. use super::{Config};
  123. #[test]
  124. fn can_import_valid_config() {
  125. let config = r#"
  126. title = "My site"
  127. base_url = "https://replace-this-with-your-url.com"
  128. "#;
  129. let config = Config::parse(config).unwrap();
  130. assert_eq!(config.title, "My site".to_string());
  131. }
  132. #[test]
  133. fn errors_when_invalid_type() {
  134. let config = r#"
  135. title = 1
  136. base_url = "https://replace-this-with-your-url.com"
  137. "#;
  138. let config = Config::parse(config);
  139. assert!(config.is_err());
  140. }
  141. #[test]
  142. fn errors_when_missing_required_field() {
  143. // base_url is required
  144. let config = r#"
  145. title = ""
  146. "#;
  147. let config = Config::parse(config);
  148. assert!(config.is_err());
  149. }
  150. #[test]
  151. fn can_add_extra_values() {
  152. let config = r#"
  153. title = "My site"
  154. base_url = "https://replace-this-with-your-url.com"
  155. [extra]
  156. hello = "world"
  157. "#;
  158. let config = Config::parse(config);
  159. assert!(config.is_ok());
  160. assert_eq!(config.unwrap().extra.unwrap().get("hello").unwrap().as_str().unwrap(), "world");
  161. }
  162. #[test]
  163. fn can_make_url_with_non_trailing_slash_base_url() {
  164. let mut config = Config::default();
  165. config.base_url = "http://vincent.is".to_string();
  166. assert_eq!(config.make_permalink("hello"), "http://vincent.is/hello");
  167. }
  168. #[test]
  169. fn can_make_url_with_trailing_slash_path() {
  170. let mut config = Config::default();
  171. config.base_url = "http://vincent.is/".to_string();
  172. assert_eq!(config.make_permalink("/hello"), "http://vincent.is/hello");
  173. }
  174. }