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.

559 lines
18KB

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