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.

90 lines
2.1KB

  1. use std::default::Default;
  2. use std::fs::File;
  3. use std::io::prelude::*;
  4. use std::path::Path;
  5. use toml::Parser;
  6. use errors::{Result, ErrorKind};
  7. #[derive(Debug, PartialEq)]
  8. pub struct Config {
  9. pub title: String,
  10. pub base_url: String,
  11. pub favicon: Option<String>,
  12. }
  13. impl Default for Config {
  14. fn default() -> Config {
  15. Config {
  16. title: "".to_string(),
  17. base_url: "".to_string(),
  18. favicon: None,
  19. }
  20. }
  21. }
  22. impl Config {
  23. pub fn from_str(content: &str) -> Result<Config> {
  24. let mut parser = Parser::new(&content);
  25. if let Some(value) = parser.parse() {
  26. let mut config = Config::default();
  27. for (key, value) in value.iter() {
  28. if key == "title" {
  29. config.title = value.as_str().ok_or(ErrorKind::InvalidConfig)?.to_string();
  30. } else if key == "base_url" {
  31. config.base_url = value.as_str().ok_or(ErrorKind::InvalidConfig)?.to_string();
  32. } else if key == "favicon" {
  33. config.favicon = Some(value.as_str().ok_or(ErrorKind::InvalidConfig)?.to_string());
  34. }
  35. }
  36. return Ok(config);
  37. } else {
  38. // TODO: handle error in parsing TOML
  39. println!("parse errors: {:?}", parser.errors);
  40. }
  41. unreachable!()
  42. }
  43. pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Config> {
  44. let mut content = String::new();
  45. File::open(path)?.read_to_string(&mut content)?;
  46. Config::from_str(&content)
  47. }
  48. }
  49. #[cfg(test)]
  50. mod tests {
  51. use super::{Config};
  52. #[test]
  53. fn test_can_import_valid_config() {
  54. let config = r#"
  55. title = "My site"
  56. base_url = "https://replace-this-with-your-url.com"
  57. "#;
  58. let config = Config::from_str(config).unwrap();
  59. assert_eq!(config.title, "My site".to_string());
  60. }
  61. #[test]
  62. fn test_errors_when_invalid_type() {
  63. let config = r#"
  64. title = 1
  65. base_url = "https://replace-this-with-your-url.com"
  66. "#;
  67. let config = Config::from_str(config);
  68. assert!(config.is_err());
  69. }
  70. }