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.

theme.rs 1.6KB

7 years ago
6 years ago
6 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. use std::collections::HashMap;
  2. use std::fs::File;
  3. use std::io::prelude::*;
  4. use std::path::PathBuf;
  5. use toml::Value as Toml;
  6. use errors::{Result, ResultExt};
  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 mut content = String::new();
  37. File::open(path)
  38. .chain_err(|| {
  39. "No `theme.toml` file found. \
  40. Is the `theme` defined in your `config.toml present in the `themes` directory \
  41. and does it have a `theme.toml` inside?"
  42. })?
  43. .read_to_string(&mut content)?;
  44. Theme::parse(&content)
  45. }
  46. }