config.rs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. use serde::{Deserialize, Serialize};
  2. use std::collections::HashMap;
  3. use std::path::PathBuf;
  4. use std::fs::{
  5. File,
  6. read_to_string
  7. };
  8. use std::io::Write;
  9. use home::home_dir;
  10. use crate::lib::repository::{
  11. Repository
  12. };
  13. use crate::lib::repotype::{
  14. RepoType
  15. };
  16. use crate::lib::action::{
  17. Action
  18. };
  19. use crate::lib::group::{
  20. Group
  21. };
  22. #[derive(Serialize, Deserialize)]
  23. pub struct Config {
  24. #[serde(rename(serialize = "repo_type", deserialize = "repo_type"), default)]
  25. repo_types: HashMap<String, RepoType>,
  26. #[serde(rename(serialize = "repository", deserialize = "repository"), default)]
  27. pub repositories: HashMap<String, Repository>,
  28. #[serde(rename(serialize = "action", deserialize = "action"), default)]
  29. actions: HashMap<String, Action>,
  30. #[serde(rename(serialize = "group", deserialize = "group"), default)]
  31. groups: HashMap<String, Group>,
  32. }
  33. pub fn find_config_file(original: Option<&str>) -> PathBuf {
  34. match original {
  35. None => {
  36. let config_name = PathBuf::from(".config/sync-it/config.toml");
  37. let mut path_name = home_dir().unwrap().join(config_name);
  38. if path_name.exists() {
  39. return path_name;
  40. }
  41. path_name = home_dir().unwrap().join(PathBuf::from(".sync-it.toml"));
  42. return path_name;
  43. },
  44. Some(p) => return PathBuf::from(&p),
  45. }
  46. }
  47. pub fn read_configuration_file(filename: &PathBuf) -> Config {
  48. let text = read_to_string(filename);
  49. match text {
  50. Err(_) => {
  51. let config = Config {
  52. repo_types: HashMap::new(),
  53. repositories: HashMap::new(),
  54. actions: HashMap::new(),
  55. groups: HashMap::new()
  56. };
  57. return config;
  58. },
  59. Ok(s) => return toml::from_str(&s).unwrap()
  60. }
  61. }
  62. pub fn write_configuration_file(filename: PathBuf, configuration: Config) -> std::io::Result<()> {
  63. let toml = toml::to_string(&configuration).unwrap();
  64. let mut file = File::create(filename)?;
  65. file.write_all(toml.as_bytes())?;
  66. Ok(())
  67. }