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.

52 lines
1.5KB

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