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.

411 lines
13KB

  1. #[macro_use]
  2. extern crate serde_derive;
  3. extern crate toml;
  4. #[macro_use]
  5. extern crate errors;
  6. extern crate highlighting;
  7. extern crate chrono;
  8. extern crate globset;
  9. use std::collections::HashMap;
  10. use std::fs::File;
  11. use std::io::prelude::*;
  12. use std::path::{Path, PathBuf};
  13. use toml::{Value as Toml};
  14. use chrono::Utc;
  15. use globset::{Glob, GlobSet, GlobSetBuilder};
  16. use errors::{Result, ResultExt};
  17. use highlighting::THEME_SET;
  18. mod theme;
  19. use theme::Theme;
  20. #[derive(Clone, Debug, Serialize, Deserialize)]
  21. pub struct Config {
  22. /// Base URL of the site, the only required config argument
  23. pub base_url: String,
  24. /// Theme to use
  25. pub theme: Option<String>,
  26. /// Title of the site. Defaults to None
  27. pub title: Option<String>,
  28. /// Whether to highlight all code blocks found in markdown files. Defaults to false
  29. pub highlight_code: Option<bool>,
  30. /// Which themes to use for code highlighting. See Readme for supported themes
  31. pub highlight_theme: Option<String>,
  32. /// Description of the site
  33. pub description: Option<String>,
  34. /// The language used in the site. Defaults to "en"
  35. pub default_language: Option<String>,
  36. /// Whether to generate RSS. Defaults to false
  37. pub generate_rss: Option<bool>,
  38. /// The number of articles to include in the RSS feed. Defaults to unlimited
  39. pub rss_limit: Option<usize>,
  40. /// Whether to generate tags and individual tag pages if some pages have them. Defaults to true
  41. pub generate_tags_pages: Option<bool>,
  42. /// Whether to generate categories and individual tag categories if some pages have them. Defaults to true
  43. pub generate_categories_pages: 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. /// A list of file glob patterns to ignore when processing the content folder. Defaults to none.
  47. /// Had to remove the PartialEq derive because GlobSet does not implement it. No impact
  48. /// because it's unused anyway (who wants to sort Configs?).
  49. pub ignored_content: Option<Vec<String>>,
  50. #[serde(skip_serializing, skip_deserializing)] // not a typo, 2 are needed
  51. pub ignored_content_globber: Option<GlobSet>,
  52. /// Languages list and translated strings
  53. pub translations: Option<HashMap<String, Toml>>,
  54. /// All user params set in [extra] in the config
  55. pub extra: Option<HashMap<String, Toml>>,
  56. /// Set automatically when instantiating the config. Used for cachebusting
  57. pub build_timestamp: Option<i64>,
  58. }
  59. macro_rules! set_default {
  60. ($key: expr, $default: expr) => {
  61. if $key.is_none() {
  62. $key = Some($default);
  63. }
  64. }
  65. }
  66. impl Config {
  67. /// Parses a string containing TOML to our Config struct
  68. /// Any extra parameter will end up in the extra field
  69. pub fn parse(content: &str) -> Result<Config> {
  70. let mut config: Config = match toml::from_str(content) {
  71. Ok(c) => c,
  72. Err(e) => bail!(e)
  73. };
  74. set_default!(config.default_language, "en".to_string());
  75. set_default!(config.highlight_code, false);
  76. set_default!(config.generate_rss, false);
  77. set_default!(config.rss_limit, 20);
  78. set_default!(config.generate_tags_pages, false);
  79. set_default!(config.generate_categories_pages, false);
  80. set_default!(config.compile_sass, false);
  81. set_default!(config.ignored_content, Vec::new());
  82. set_default!(config.translations, HashMap::new());
  83. set_default!(config.extra, HashMap::new());
  84. match config.highlight_theme {
  85. Some(ref t) => {
  86. if !THEME_SET.themes.contains_key(t) {
  87. bail!("Theme {} not available", t)
  88. }
  89. }
  90. None => config.highlight_theme = Some("base16-ocean-dark".to_string())
  91. };
  92. config.build_timestamp = Some(Utc::now().timestamp());
  93. // Convert the file glob strings into a compiled glob set matcher. We want to do this once,
  94. // at program initialization, rather than for every page, for example. We arrange for the
  95. // globset matcher to always exist (even though it has to be an inside an Option at the
  96. // moment because of the TOML serializer); if the glob set is empty the `is_match` function
  97. // of the globber always returns false.
  98. let mut glob_set_builder = GlobSetBuilder::new();
  99. if let Some(ref v) = config.ignored_content {
  100. for pat in v {
  101. let glob = match Glob::new(pat) {
  102. Ok(g) => g,
  103. Err(e) => bail!("Invalid ignored_content glob pattern: {}, error = {}", pat, e)
  104. };
  105. glob_set_builder.add(glob);
  106. }
  107. }
  108. config.ignored_content_globber = Some(glob_set_builder.build().expect("Bad ignored_content in config file."));
  109. Ok(config)
  110. }
  111. /// Parses a config file from the given path
  112. pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Config> {
  113. let mut content = String::new();
  114. File::open(path)
  115. .chain_err(|| "No `config.toml` file found. Are you in the right directory?")?
  116. .read_to_string(&mut content)?;
  117. Config::parse(&content)
  118. }
  119. /// Makes a url, taking into account that the base url might have a trailing slash
  120. pub fn make_permalink(&self, path: &str) -> String {
  121. let trailing_bit = if path.ends_with('/') || path.is_empty() { "" } else { "/" };
  122. // Index section with a base url that has a trailing slash
  123. if self.base_url.ends_with('/') && path == "/" {
  124. self.base_url.clone()
  125. } else if path == "/" {
  126. // index section with a base url that doesn't have a trailing slash
  127. format!("{}/", self.base_url)
  128. } else if self.base_url.ends_with('/') && path.starts_with('/') {
  129. format!("{}{}{}", self.base_url, &path[1..], trailing_bit)
  130. } else if self.base_url.ends_with('/') {
  131. format!("{}{}{}", self.base_url, path, trailing_bit)
  132. } else if path.starts_with('/') {
  133. format!("{}{}{}", self.base_url, path, trailing_bit)
  134. } else {
  135. format!("{}/{}{}", self.base_url, path, trailing_bit)
  136. }
  137. }
  138. /// Merges the extra data from the theme with the config extra data
  139. fn add_theme_extra(&mut self, theme: &Theme) -> Result<()> {
  140. if let Some(ref mut config_extra) = self.extra {
  141. // 3 pass merging
  142. // 1. save config to preserve user
  143. let original = config_extra.clone();
  144. // 2. inject theme extra values
  145. for (key, val) in &theme.extra {
  146. config_extra.entry(key.to_string()).or_insert_with(|| val.clone());
  147. }
  148. // 3. overwrite with original config
  149. for (key, val) in &original {
  150. config_extra.entry(key.to_string()).or_insert_with(|| val.clone());
  151. }
  152. }
  153. Ok(())
  154. }
  155. /// Parse the theme.toml file and merges the extra data from the theme
  156. /// with the config extra data
  157. pub fn merge_with_theme(&mut self, path: &PathBuf) -> Result<()> {
  158. let theme = Theme::from_file(path)?;
  159. self.add_theme_extra(&theme)
  160. }
  161. }
  162. /// Exists only for testing purposes
  163. #[doc(hidden)]
  164. impl Default for Config {
  165. fn default() -> Config {
  166. Config {
  167. title: Some("".to_string()),
  168. theme: None,
  169. base_url: "http://a-website.com/".to_string(),
  170. highlight_code: Some(true),
  171. highlight_theme: Some("base16-ocean-dark".to_string()),
  172. description: None,
  173. default_language: Some("en".to_string()),
  174. generate_rss: Some(false),
  175. rss_limit: Some(10_000),
  176. generate_tags_pages: Some(true),
  177. generate_categories_pages: Some(true),
  178. compile_sass: Some(false),
  179. ignored_content: Some(Vec::new()),
  180. ignored_content_globber: Some(GlobSetBuilder::new().build().unwrap()),
  181. translations: None,
  182. extra: None,
  183. build_timestamp: Some(1),
  184. }
  185. }
  186. }
  187. /// Get and parse the config.
  188. /// If it doesn't succeed, exit
  189. pub fn get_config(path: &Path, filename: &str) -> Config {
  190. match Config::from_file(path.join(filename)) {
  191. Ok(c) => c,
  192. Err(e) => {
  193. println!("Failed to load {}", filename);
  194. println!("Error: {}", e);
  195. ::std::process::exit(1);
  196. }
  197. }
  198. }
  199. #[cfg(test)]
  200. mod tests {
  201. use super::{Config, Theme};
  202. #[test]
  203. fn can_import_valid_config() {
  204. let config = r#"
  205. title = "My site"
  206. base_url = "https://replace-this-with-your-url.com"
  207. "#;
  208. let config = Config::parse(config).unwrap();
  209. assert_eq!(config.title.unwrap(), "My site".to_string());
  210. }
  211. #[test]
  212. fn errors_when_invalid_type() {
  213. let config = r#"
  214. title = 1
  215. base_url = "https://replace-this-with-your-url.com"
  216. "#;
  217. let config = Config::parse(config);
  218. assert!(config.is_err());
  219. }
  220. #[test]
  221. fn errors_when_missing_required_field() {
  222. // base_url is required
  223. let config = r#"
  224. title = ""
  225. "#;
  226. let config = Config::parse(config);
  227. assert!(config.is_err());
  228. }
  229. #[test]
  230. fn can_add_extra_values() {
  231. let config = r#"
  232. title = "My site"
  233. base_url = "https://replace-this-with-your-url.com"
  234. [extra]
  235. hello = "world"
  236. "#;
  237. let config = Config::parse(config);
  238. assert!(config.is_ok());
  239. assert_eq!(config.unwrap().extra.unwrap().get("hello").unwrap().as_str().unwrap(), "world");
  240. }
  241. #[test]
  242. fn can_make_url_index_page_with_non_trailing_slash_url() {
  243. let mut config = Config::default();
  244. config.base_url = "http://vincent.is".to_string();
  245. assert_eq!(config.make_permalink(""), "http://vincent.is/");
  246. }
  247. #[test]
  248. fn can_make_url_index_page_with_railing_slash_url() {
  249. let mut config = Config::default();
  250. config.base_url = "http://vincent.is/".to_string();
  251. assert_eq!(config.make_permalink(""), "http://vincent.is/");
  252. }
  253. #[test]
  254. fn can_make_url_with_non_trailing_slash_base_url() {
  255. let mut config = Config::default();
  256. config.base_url = "http://vincent.is".to_string();
  257. assert_eq!(config.make_permalink("hello"), "http://vincent.is/hello/");
  258. }
  259. #[test]
  260. fn can_make_url_with_trailing_slash_path() {
  261. let mut config = Config::default();
  262. config.base_url = "http://vincent.is/".to_string();
  263. assert_eq!(config.make_permalink("/hello"), "http://vincent.is/hello/");
  264. }
  265. #[test]
  266. fn can_make_url_with_localhost() {
  267. let mut config = Config::default();
  268. config.base_url = "http://127.0.0.1:1111".to_string();
  269. assert_eq!(config.make_permalink("/tags/rust"), "http://127.0.0.1:1111/tags/rust/");
  270. }
  271. #[test]
  272. fn can_merge_with_theme_data_and_preserve_config_value() {
  273. let config_str = r#"
  274. title = "My site"
  275. base_url = "https://replace-this-with-your-url.com"
  276. [extra]
  277. hello = "world"
  278. "#;
  279. let mut config = Config::parse(config_str).unwrap();
  280. let theme_str = r#"
  281. [extra]
  282. hello = "foo"
  283. a_value = 10
  284. "#;
  285. let theme = Theme::parse(theme_str).unwrap();
  286. assert!(config.add_theme_extra(&theme).is_ok());
  287. let extra = config.extra.unwrap();
  288. assert_eq!(extra["hello"].as_str().unwrap(), "world".to_string());
  289. assert_eq!(extra["a_value"].as_integer().unwrap(), 10);
  290. }
  291. #[test]
  292. fn can_use_language_configuration() {
  293. let config = r#"
  294. base_url = "https://remplace-par-ton-url.fr"
  295. default_language = "fr"
  296. [translations]
  297. [translations.fr]
  298. title = "Un titre"
  299. [translations.en]
  300. title = "A title"
  301. "#;
  302. let config = Config::parse(config);
  303. assert!(config.is_ok());
  304. let translations = config.unwrap().translations.unwrap();
  305. assert_eq!(translations["fr"]["title"].as_str().unwrap(), "Un titre");
  306. assert_eq!(translations["en"]["title"].as_str().unwrap(), "A title");
  307. }
  308. #[test]
  309. fn missing_ignored_content_results_in_empty_vector_and_empty_globber() {
  310. let config_str = r#"
  311. title = "My site"
  312. base_url = "example.com"
  313. "#;
  314. let config = Config::parse(config_str).unwrap();
  315. let v = config.ignored_content.unwrap();
  316. assert_eq!(v.len(), 0);
  317. assert!(config.ignored_content_globber.unwrap().is_empty());
  318. }
  319. #[test]
  320. fn empty_ignored_content_results_in_empty_vector_and_empty_globber() {
  321. let config_str = r#"
  322. title = "My site"
  323. base_url = "example.com"
  324. ignored_content = []
  325. "#;
  326. let config = Config::parse(config_str).unwrap();
  327. assert_eq!(config.ignored_content.unwrap().len(), 0);
  328. assert!(config.ignored_content_globber.unwrap().is_empty());
  329. }
  330. #[test]
  331. fn non_empty_ignored_content_results_in_vector_of_patterns_and_configured_globber() {
  332. let config_str = r#"
  333. title = "My site"
  334. base_url = "example.com"
  335. ignored_content = ["*.{graphml,iso}", "*.py?"]
  336. "#;
  337. let config = Config::parse(config_str).unwrap();
  338. let v = config.ignored_content.unwrap();
  339. assert_eq!(v, vec!["*.{graphml,iso}", "*.py?"]);
  340. let g = config.ignored_content_globber.unwrap();
  341. assert_eq!(g.len(), 2);
  342. assert!(g.is_match("foo.graphml"));
  343. assert!(g.is_match("foo.iso"));
  344. assert!(!g.is_match("foo.png"));
  345. assert!(g.is_match("foo.py2"));
  346. assert!(g.is_match("foo.py3"));
  347. assert!(!g.is_match("foo.py"));
  348. }
  349. }