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.

51 lines
1.5KB

  1. use std::collections::HashMap;
  2. use std::path::PathBuf;
  3. use toml::Value as Toml;
  4. use errors::Result;
  5. use utils::fs::read_file_with_error;
  6. /// Holds the data from a `theme.toml` file.
  7. /// There are other fields than `extra` in it but Zola
  8. /// itself doesn't care about them.
  9. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
  10. pub struct Theme {
  11. /// All user params set in [extra] in the theme.toml
  12. pub extra: HashMap<String, Toml>,
  13. }
  14. impl Theme {
  15. /// Parses a TOML string to our Theme struct
  16. pub fn parse(content: &str) -> Result<Theme> {
  17. let theme = match content.parse::<Toml>() {
  18. Ok(t) => t,
  19. Err(e) => bail!(e),
  20. };
  21. let mut extra = HashMap::new();
  22. if let Some(theme_table) = theme.as_table() {
  23. if let Some(ex) = theme_table.get("extra") {
  24. if ex.is_table() {
  25. extra = ex.clone().try_into().unwrap();
  26. }
  27. }
  28. } else {
  29. bail!("Expected the `theme.toml` to be a TOML table")
  30. }
  31. Ok(Theme { extra })
  32. }
  33. /// Parses a theme file from the given path
  34. pub fn from_file(path: &PathBuf) -> Result<Theme> {
  35. let content = read_file_with_error(
  36. path,
  37. "No `theme.toml` file found. \
  38. Is the `theme` defined in your `config.toml present in the `themes` directory \
  39. and does it have a `theme.toml` inside?",
  40. )?;
  41. Theme::parse(&content)
  42. }
  43. }