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.

231 lines
7.3KB

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