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.

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