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.

485 lines
15KB

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