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.

476 lines
15KB

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