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.

185 lines
5.4KB

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