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.

config.rs 5.3KB

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