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.

488 lines
16KB

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