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.

402 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. let path = path.as_ref();
  102. let file_name = path.file_name().unwrap();
  103. File::open(path)
  104. .chain_err(|| format!("No `{:?}` file found. Are you in the right directory?", file_name))?
  105. .read_to_string(&mut content)?;
  106. Config::parse(&content)
  107. }
  108. /// Makes a url, taking into account that the base url might have a trailing slash
  109. pub fn make_permalink(&self, path: &str) -> String {
  110. let trailing_bit = if path.ends_with('/') || path.is_empty() { "" } else { "/" };
  111. // Index section with a base url that has a trailing slash
  112. if self.base_url.ends_with('/') && path == "/" {
  113. self.base_url.clone()
  114. } else if path == "/" {
  115. // index section with a base url that doesn't have a trailing slash
  116. format!("{}/", self.base_url)
  117. } else if self.base_url.ends_with('/') && path.starts_with('/') {
  118. format!("{}{}{}", self.base_url, &path[1..], trailing_bit)
  119. } else if self.base_url.ends_with('/') {
  120. format!("{}{}{}", self.base_url, path, trailing_bit)
  121. } else if path.starts_with('/') {
  122. format!("{}{}{}", self.base_url, path, trailing_bit)
  123. } else {
  124. format!("{}/{}{}", self.base_url, path, trailing_bit)
  125. }
  126. }
  127. /// Merges the extra data from the theme with the config extra data
  128. fn add_theme_extra(&mut self, theme: &Theme) -> Result<()> {
  129. // 3 pass merging
  130. // 1. save config to preserve user
  131. let original = self.extra.clone();
  132. // 2. inject theme extra values
  133. for (key, val) in &theme.extra {
  134. self.extra.entry(key.to_string()).or_insert_with(|| val.clone());
  135. }
  136. // 3. overwrite with original config
  137. for (key, val) in &original {
  138. self.extra.entry(key.to_string()).or_insert_with(|| val.clone());
  139. }
  140. Ok(())
  141. }
  142. /// Parse the theme.toml file and merges the extra data from the theme
  143. /// with the config extra data
  144. pub fn merge_with_theme(&mut self, path: &PathBuf) -> Result<()> {
  145. let theme = Theme::from_file(path)?;
  146. self.add_theme_extra(&theme)
  147. }
  148. }
  149. impl Default for Config {
  150. fn default() -> Config {
  151. Config {
  152. base_url: DEFAULT_BASE_URL.to_string(),
  153. title: None,
  154. description: None,
  155. theme: None,
  156. highlight_code: true,
  157. highlight_theme: "base16-ocean-dark".to_string(),
  158. default_language: "en".to_string(),
  159. generate_rss: false,
  160. rss_limit: 10_000,
  161. generate_tags_pages: true,
  162. generate_categories_pages: true,
  163. compile_sass: false,
  164. build_search_index: false,
  165. ignored_content: Vec::new(),
  166. ignored_content_globset: None,
  167. translations: HashMap::new(),
  168. extra: HashMap::new(),
  169. build_timestamp: Some(1),
  170. }
  171. }
  172. }
  173. /// Get and parse the config.
  174. /// If it doesn't succeed, exit
  175. pub fn get_config(path: &Path, filename: &str) -> Config {
  176. match Config::from_file(path.join(filename)) {
  177. Ok(c) => c,
  178. Err(e) => {
  179. println!("Failed to load {}", filename);
  180. println!("Error: {}", e);
  181. ::std::process::exit(1);
  182. }
  183. }
  184. }
  185. #[cfg(test)]
  186. mod tests {
  187. use super::{Config, Theme};
  188. #[test]
  189. fn can_import_valid_config() {
  190. let config = r#"
  191. title = "My site"
  192. base_url = "https://replace-this-with-your-url.com"
  193. "#;
  194. let config = Config::parse(config).unwrap();
  195. assert_eq!(config.title.unwrap(), "My site".to_string());
  196. }
  197. #[test]
  198. fn errors_when_invalid_type() {
  199. let config = r#"
  200. title = 1
  201. base_url = "https://replace-this-with-your-url.com"
  202. "#;
  203. let config = Config::parse(config);
  204. assert!(config.is_err());
  205. }
  206. #[test]
  207. fn errors_when_missing_required_field() {
  208. // base_url is required
  209. let config = r#"
  210. title = ""
  211. "#;
  212. let config = Config::parse(config);
  213. assert!(config.is_err());
  214. }
  215. #[test]
  216. fn can_add_extra_values() {
  217. let config = r#"
  218. title = "My site"
  219. base_url = "https://replace-this-with-your-url.com"
  220. [extra]
  221. hello = "world"
  222. "#;
  223. let config = Config::parse(config);
  224. assert!(config.is_ok());
  225. assert_eq!(config.unwrap().extra.get("hello").unwrap().as_str().unwrap(), "world");
  226. }
  227. #[test]
  228. fn can_make_url_index_page_with_non_trailing_slash_url() {
  229. let mut config = Config::default();
  230. config.base_url = "http://vincent.is".to_string();
  231. assert_eq!(config.make_permalink(""), "http://vincent.is/");
  232. }
  233. #[test]
  234. fn can_make_url_index_page_with_railing_slash_url() {
  235. let mut config = Config::default();
  236. config.base_url = "http://vincent.is/".to_string();
  237. assert_eq!(config.make_permalink(""), "http://vincent.is/");
  238. }
  239. #[test]
  240. fn can_make_url_with_non_trailing_slash_base_url() {
  241. let mut config = Config::default();
  242. config.base_url = "http://vincent.is".to_string();
  243. assert_eq!(config.make_permalink("hello"), "http://vincent.is/hello/");
  244. }
  245. #[test]
  246. fn can_make_url_with_trailing_slash_path() {
  247. let mut config = Config::default();
  248. config.base_url = "http://vincent.is/".to_string();
  249. assert_eq!(config.make_permalink("/hello"), "http://vincent.is/hello/");
  250. }
  251. #[test]
  252. fn can_make_url_with_localhost() {
  253. let mut config = Config::default();
  254. config.base_url = "http://127.0.0.1:1111".to_string();
  255. assert_eq!(config.make_permalink("/tags/rust"), "http://127.0.0.1:1111/tags/rust/");
  256. }
  257. #[test]
  258. fn can_merge_with_theme_data_and_preserve_config_value() {
  259. let config_str = r#"
  260. title = "My site"
  261. base_url = "https://replace-this-with-your-url.com"
  262. [extra]
  263. hello = "world"
  264. "#;
  265. let mut config = Config::parse(config_str).unwrap();
  266. let theme_str = r#"
  267. [extra]
  268. hello = "foo"
  269. a_value = 10
  270. "#;
  271. let theme = Theme::parse(theme_str).unwrap();
  272. assert!(config.add_theme_extra(&theme).is_ok());
  273. let extra = config.extra;
  274. assert_eq!(extra["hello"].as_str().unwrap(), "world".to_string());
  275. assert_eq!(extra["a_value"].as_integer().unwrap(), 10);
  276. }
  277. #[test]
  278. fn can_use_language_configuration() {
  279. let config = r#"
  280. base_url = "https://remplace-par-ton-url.fr"
  281. default_language = "fr"
  282. [translations]
  283. [translations.fr]
  284. title = "Un titre"
  285. [translations.en]
  286. title = "A title"
  287. "#;
  288. let config = Config::parse(config);
  289. assert!(config.is_ok());
  290. let translations = config.unwrap().translations;
  291. assert_eq!(translations["fr"]["title"].as_str().unwrap(), "Un titre");
  292. assert_eq!(translations["en"]["title"].as_str().unwrap(), "A title");
  293. }
  294. #[test]
  295. fn missing_ignored_content_results_in_empty_vector_and_empty_globset() {
  296. let config_str = r#"
  297. title = "My site"
  298. base_url = "example.com"
  299. "#;
  300. let config = Config::parse(config_str).unwrap();
  301. let v = config.ignored_content;
  302. assert_eq!(v.len(), 0);
  303. assert!(config.ignored_content_globset.is_none());
  304. }
  305. #[test]
  306. fn empty_ignored_content_results_in_empty_vector_and_empty_globset() {
  307. let config_str = r#"
  308. title = "My site"
  309. base_url = "example.com"
  310. ignored_content = []
  311. "#;
  312. let config = Config::parse(config_str).unwrap();
  313. assert_eq!(config.ignored_content.len(), 0);
  314. assert!(config.ignored_content_globset.is_none());
  315. }
  316. #[test]
  317. fn non_empty_ignored_content_results_in_vector_of_patterns_and_configured_globset() {
  318. let config_str = r#"
  319. title = "My site"
  320. base_url = "example.com"
  321. ignored_content = ["*.{graphml,iso}", "*.py?"]
  322. "#;
  323. let config = Config::parse(config_str).unwrap();
  324. let v = config.ignored_content;
  325. assert_eq!(v, vec!["*.{graphml,iso}", "*.py?"]);
  326. let g = config.ignored_content_globset.unwrap();
  327. assert_eq!(g.len(), 2);
  328. assert!(g.is_match("foo.graphml"));
  329. assert!(g.is_match("foo.iso"));
  330. assert!(!g.is_match("foo.png"));
  331. assert!(g.is_match("foo.py2"));
  332. assert!(g.is_match("foo.py3"));
  333. assert!(!g.is_match("foo.py"));
  334. }
  335. }