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.

186 lines
4.9KB

  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. // TO ADD:
  9. // highlight code theme
  10. // generate_tags_pages
  11. // generate_categories_pages
  12. #[derive(Debug, PartialEq, Serialize, Deserialize)]
  13. pub struct Config {
  14. /// Title of the site
  15. pub title: String,
  16. /// Base URL of the site
  17. pub base_url: String,
  18. /// Whether to highlight all code blocks found in markdown files. Defaults to false
  19. pub highlight_code: Option<bool>,
  20. /// Which themes to use for code highlighting. See Readme for supported themes
  21. pub highlight_theme: Option<String>,
  22. /// Description of the site
  23. pub description: Option<String>,
  24. /// The language used in the site. Defaults to "en"
  25. pub language_code: Option<String>,
  26. /// Whether to generate RSS, defaults to false
  27. pub generate_rss: Option<bool>,
  28. /// All user params set in [extra] in the config
  29. pub extra: Option<HashMap<String, Toml>>,
  30. }
  31. impl Config {
  32. /// Parses a string containing TOML to our Config struct
  33. /// Any extra parameter will end up in the extra field
  34. pub fn parse(content: &str) -> Result<Config> {
  35. let mut config: Config = match toml::from_str(content) {
  36. Ok(c) => c,
  37. Err(e) => bail!(e)
  38. };
  39. if config.language_code.is_none() {
  40. config.language_code = Some("en".to_string());
  41. }
  42. if config.highlight_code.is_none() {
  43. config.highlight_code = Some(false);
  44. }
  45. match config.highlight_theme {
  46. Some(ref t) => {
  47. if !SETUP.theme_set.themes.contains_key(t) {
  48. bail!("Theme {} not available", t)
  49. }
  50. },
  51. None => config.highlight_theme = Some("base16-ocean-dark".to_string())
  52. };
  53. if config.generate_rss.is_none() {
  54. config.generate_rss = Some(false);
  55. }
  56. Ok(config)
  57. }
  58. /// Parses a config file from the given path
  59. pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Config> {
  60. let mut content = String::new();
  61. File::open(path)
  62. .chain_err(|| "No `config.toml` file found. Are you in the right directory?")?
  63. .read_to_string(&mut content)?;
  64. Config::parse(&content)
  65. }
  66. /// Makes a url, taking into account that the base url might have a trailing slash
  67. pub fn make_permalink(&self, path: &str) -> String {
  68. if self.base_url.ends_with('/') {
  69. format!("{}{}", self.base_url, path)
  70. } else {
  71. format!("{}/{}", self.base_url, path)
  72. }
  73. }
  74. }
  75. impl Default for Config {
  76. /// Exists for testing purposes
  77. fn default() -> Config {
  78. Config {
  79. title: "".to_string(),
  80. base_url: "http://a-website.com/".to_string(),
  81. highlight_code: Some(true),
  82. highlight_theme: Some("base16-ocean-dark".to_string()),
  83. description: None,
  84. language_code: Some("en".to_string()),
  85. generate_rss: Some(false),
  86. extra: None,
  87. }
  88. }
  89. }
  90. /// Get and parse the config.
  91. /// If it doesn't succeed, exit
  92. pub fn get_config(path: &Path) -> Config {
  93. match Config::from_file(path.join("config.toml")) {
  94. Ok(c) => c,
  95. Err(e) => {
  96. println!("Failed to load config.toml");
  97. println!("Error: {}", e);
  98. ::std::process::exit(1);
  99. }
  100. }
  101. }
  102. #[cfg(test)]
  103. mod tests {
  104. use super::{Config};
  105. #[test]
  106. fn test_can_import_valid_config() {
  107. let config = r#"
  108. title = "My site"
  109. base_url = "https://replace-this-with-your-url.com"
  110. "#;
  111. let config = Config::parse(config).unwrap();
  112. assert_eq!(config.title, "My site".to_string());
  113. }
  114. #[test]
  115. fn test_errors_when_invalid_type() {
  116. let config = r#"
  117. title = 1
  118. base_url = "https://replace-this-with-your-url.com"
  119. "#;
  120. let config = Config::parse(config);
  121. assert!(config.is_err());
  122. }
  123. #[test]
  124. fn test_errors_when_missing_required_field() {
  125. let config = r#"
  126. title = ""
  127. "#;
  128. let config = Config::parse(config);
  129. assert!(config.is_err());
  130. }
  131. #[test]
  132. fn test_can_add_extra_values() {
  133. let config = r#"
  134. title = "My site"
  135. base_url = "https://replace-this-with-your-url.com"
  136. [extra]
  137. hello = "world"
  138. "#;
  139. let config = Config::parse(config);
  140. assert!(config.is_ok());
  141. assert_eq!(config.unwrap().extra.unwrap().get("hello").unwrap().as_str().unwrap(), "world");
  142. }
  143. #[test]
  144. fn test_language_defaults_to_en() {
  145. let config = r#"
  146. title = "My site"
  147. base_url = "https://replace-this-with-your-url.com""#;
  148. let config = Config::parse(config);
  149. assert!(config.is_ok());
  150. let config = config.unwrap();
  151. assert_eq!(config.language_code.unwrap(), "en");
  152. }
  153. }