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.

84 lines
1.9KB

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