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.

201 lines
6.0KB

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