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.

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