config.rs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. extern crate serde;
  2. extern crate serde_yaml;
  3. use std::fs::{File};
  4. use std::path::Path;
  5. use std::io::prelude::*;
  6. use std::process::exit;
  7. use std::env;
  8. use self::serde::{Deserialize};
  9. mod config {}
  10. #[derive(Debug, PartialEq, Deserialize)]
  11. pub struct Config {
  12. pub words: Vec<String>,
  13. pub choose: u32
  14. }
  15. // const CONFIG_FOLDERS: &'static [&'static str] = &["XDG_CONFIG_HOME", "HOME"];
  16. pub fn default_config_file() -> String {
  17. let config_folders = [
  18. env::var("XDG_CONFIG_HOME"),
  19. env::var("HOME").and_then(|s| Ok(String::from(Path::new(&s).join(".config").to_str().unwrap()))),
  20. Ok(String::from("./"))
  21. ];
  22. for f in config_folders.iter() {
  23. match f {
  24. Err(_) => continue,
  25. Ok(dir) => {
  26. let config_file_location = Path::new(dir).join("fallout-terminal.yaml");
  27. if Path::is_file(&config_file_location) {
  28. return config_file_location.into_os_string().into_string().unwrap()
  29. }
  30. }
  31. }
  32. }
  33. String::from("")
  34. }
  35. pub fn load_config_file(config_file_path: String) -> Config {
  36. let mut config_file = match File::open(config_file_path.as_str()) {
  37. Ok(config_file) => config_file,
  38. Err(e) => {
  39. println!("Could not open {}: {}", config_file_path, e);
  40. exit(1);
  41. }
  42. };
  43. let mut config_str = String::new();
  44. let config: Config;
  45. match config_file.read_to_string(&mut config_str) {
  46. Ok(_) => {
  47. config = match serde_yaml::from_str(&config_str) {
  48. Ok(conf) => conf,
  49. Err(e) => {
  50. println!("Could not parse YAML in {}: {}", config_file_path, e);
  51. exit(1);
  52. }
  53. };
  54. }
  55. Err(e) => {
  56. println!("Could not read {}: {}", config_file_path, e);
  57. exit(1);
  58. }
  59. };
  60. validate(&config);
  61. config
  62. }
  63. fn validate(config: &Config) {
  64. if config.words.is_empty() {
  65. println!("Config file validation error: word list must not be empty");
  66. exit(1)
  67. }
  68. let first_len = config.words[0].len();
  69. for s in &config.words[1..] {
  70. if s.len() != first_len {
  71. println!("Config file validation error: All words must be the same length [len({}) != len({})]", config.words[0], s);
  72. exit(1)
  73. }
  74. }
  75. }