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.4KB

7 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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 Gutenberg
  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(|| "No `theme.toml` file found. Are you in the right directory?")?
  39. .read_to_string(&mut content)?;
  40. Theme::parse(&content)
  41. }
  42. }