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.

224 lines
7.0KB

  1. #[macro_use]
  2. extern crate serde_derive;
  3. extern crate toml;
  4. #[macro_use]
  5. extern crate errors;
  6. extern crate rendering;
  7. use std::collections::HashMap;
  8. use std::fs::File;
  9. use std::io::prelude::*;
  10. use std::path::Path;
  11. use toml::{Value as Toml};
  12. use errors::{Result, ResultExt};
  13. use rendering::highlighting::THEME_SET;
  14. #[derive(Debug, PartialEq, Serialize, Deserialize)]
  15. pub struct Config {
  16. /// Base URL of the site, the only required config argument
  17. pub base_url: String,
  18. /// Title of the site. Defaults to None
  19. pub title: Option<String>,
  20. /// Whether to highlight all code blocks found in markdown files. Defaults to false
  21. pub highlight_code: Option<bool>,
  22. /// Which themes to use for code highlighting. See Readme for supported themes
  23. pub highlight_theme: Option<String>,
  24. /// Description of the site
  25. pub description: Option<String>,
  26. /// The language used in the site. Defaults to "en"
  27. pub language_code: Option<String>,
  28. /// Whether to generate RSS. Defaults to false
  29. pub generate_rss: Option<bool>,
  30. /// The number of articles to include in the RSS feed. Defaults to unlimited
  31. pub rss_limit: Option<usize>,
  32. /// Whether to generate tags and individual tag pages if some pages have them. Defaults to true
  33. pub generate_tags_pages: Option<bool>,
  34. /// Whether to generate categories and individual tag categories if some pages have them. Defaults to true
  35. pub generate_categories_pages: Option<bool>,
  36. /// Whether to insert a link for each header like in Github READMEs. Defaults to false
  37. /// The default template can be overridden by creating a `anchor-link.html` template and CSS will need to be
  38. /// written if you turn that on.
  39. pub insert_anchor_links: Option<bool>,
  40. /// Whether to compile the `sass` directory and output the css files into the static folder
  41. pub compile_sass: Option<bool>,
  42. /// All user params set in [extra] in the config
  43. pub extra: Option<HashMap<String, Toml>>,
  44. }
  45. macro_rules! set_default {
  46. ($key: expr, $default: expr) => {
  47. if $key.is_none() {
  48. $key = Some($default);
  49. }
  50. }
  51. }
  52. impl Config {
  53. /// Parses a string containing TOML to our Config struct
  54. /// Any extra parameter will end up in the extra field
  55. pub fn parse(content: &str) -> Result<Config> {
  56. let mut config: Config = match toml::from_str(content) {
  57. Ok(c) => c,
  58. Err(e) => bail!(e)
  59. };
  60. set_default!(config.language_code, "en".to_string());
  61. set_default!(config.highlight_code, false);
  62. set_default!(config.generate_rss, false);
  63. set_default!(config.rss_limit, 20);
  64. set_default!(config.generate_tags_pages, false);
  65. set_default!(config.generate_categories_pages, false);
  66. set_default!(config.insert_anchor_links, false);
  67. set_default!(config.compile_sass, false);
  68. match config.highlight_theme {
  69. Some(ref t) => {
  70. if !THEME_SET.themes.contains_key(t) {
  71. bail!("Theme {} not available", t)
  72. }
  73. }
  74. None => config.highlight_theme = Some("base16-ocean-dark".to_string())
  75. };
  76. Ok(config)
  77. }
  78. /// Parses a config file from the given path
  79. pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Config> {
  80. let mut content = String::new();
  81. File::open(path)
  82. .chain_err(|| "No `config.toml` file found. Are you in the right directory?")?
  83. .read_to_string(&mut content)?;
  84. Config::parse(&content)
  85. }
  86. /// Makes a url, taking into account that the base url might have a trailing slash
  87. pub fn make_permalink(&self, path: &str) -> String {
  88. let trailing_bit = if path.ends_with('/') { "" } else { "/" };
  89. // Index section with a base url that has a trailing slash
  90. if self.base_url.ends_with('/') && path == "/" {
  91. self.base_url.clone()
  92. } else if path == "/" {
  93. // index section with a base url that doesn't have a trailing slash
  94. format!("{}/", self.base_url)
  95. } else if self.base_url.ends_with('/') && path.starts_with('/') {
  96. format!("{}{}{}", self.base_url, &path[1..], trailing_bit)
  97. } else if self.base_url.ends_with('/') {
  98. format!("{}{}{}", self.base_url, path, trailing_bit)
  99. } else {
  100. format!("{}/{}{}", self.base_url, path, trailing_bit)
  101. }
  102. }
  103. }
  104. /// Exists only for testing purposes
  105. #[doc(hidden)]
  106. impl Default for Config {
  107. fn default() -> Config {
  108. Config {
  109. title: Some("".to_string()),
  110. base_url: "http://a-website.com/".to_string(),
  111. highlight_code: Some(true),
  112. highlight_theme: Some("base16-ocean-dark".to_string()),
  113. description: None,
  114. language_code: Some("en".to_string()),
  115. generate_rss: Some(false),
  116. rss_limit: Some(10000),
  117. generate_tags_pages: Some(true),
  118. generate_categories_pages: Some(true),
  119. insert_anchor_links: Some(false),
  120. compile_sass: Some(false),
  121. extra: None,
  122. }
  123. }
  124. }
  125. /// Get and parse the config.
  126. /// If it doesn't succeed, exit
  127. pub fn get_config(path: &Path, filename: &str) -> Config {
  128. match Config::from_file(path.join(filename)) {
  129. Ok(c) => c,
  130. Err(e) => {
  131. println!("Failed to load {}", filename);
  132. println!("Error: {}", e);
  133. ::std::process::exit(1);
  134. }
  135. }
  136. }
  137. #[cfg(test)]
  138. mod tests {
  139. use super::{Config};
  140. #[test]
  141. fn can_import_valid_config() {
  142. let config = r#"
  143. title = "My site"
  144. base_url = "https://replace-this-with-your-url.com"
  145. "#;
  146. let config = Config::parse(config).unwrap();
  147. assert_eq!(config.title.unwrap(), "My site".to_string());
  148. }
  149. #[test]
  150. fn errors_when_invalid_type() {
  151. let config = r#"
  152. title = 1
  153. base_url = "https://replace-this-with-your-url.com"
  154. "#;
  155. let config = Config::parse(config);
  156. assert!(config.is_err());
  157. }
  158. #[test]
  159. fn errors_when_missing_required_field() {
  160. // base_url is required
  161. let config = r#"
  162. title = ""
  163. "#;
  164. let config = Config::parse(config);
  165. assert!(config.is_err());
  166. }
  167. #[test]
  168. fn can_add_extra_values() {
  169. let config = r#"
  170. title = "My site"
  171. base_url = "https://replace-this-with-your-url.com"
  172. [extra]
  173. hello = "world"
  174. "#;
  175. let config = Config::parse(config);
  176. assert!(config.is_ok());
  177. assert_eq!(config.unwrap().extra.unwrap().get("hello").unwrap().as_str().unwrap(), "world");
  178. }
  179. #[test]
  180. fn can_make_url_with_non_trailing_slash_base_url() {
  181. let mut config = Config::default();
  182. config.base_url = "http://vincent.is".to_string();
  183. assert_eq!(config.make_permalink("hello"), "http://vincent.is/hello/");
  184. }
  185. #[test]
  186. fn can_make_url_with_trailing_slash_path() {
  187. let mut config = Config::default();
  188. config.base_url = "http://vincent.is/".to_string();
  189. assert_eq!(config.make_permalink("/hello"), "http://vincent.is/hello/");
  190. }
  191. }