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.

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