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.

234 lines
7.4KB

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