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.

85 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. // TODO: handle error in parsing TOML
  36. println!("parse errors: {:?}", parser.errors);
  37. }
  38. unreachable!()
  39. }
  40. pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Config> {
  41. let mut content = String::new();
  42. File::open(path)?.read_to_string(&mut content)?;
  43. Config::from_str(&content)
  44. }
  45. }
  46. #[cfg(test)]
  47. mod tests {
  48. use super::{Config};
  49. #[test]
  50. fn test_can_import_valid_config() {
  51. let config = r#"
  52. title = "My site"
  53. base_url = "https://replace-this-with-your-url.com"
  54. "#;
  55. let config = Config::from_str(config).unwrap();
  56. assert_eq!(config.title, "My site".to_string());
  57. }
  58. #[test]
  59. fn test_errors_when_invalid_type() {
  60. let config = r#"
  61. title = 1
  62. base_url = "https://replace-this-with-your-url.com"
  63. "#;
  64. let config = Config::from_str(config);
  65. assert!(config.is_err());
  66. }
  67. }