config.rs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. use serde::{Deserialize, Serialize};
  2. use std::collections::BTreeMap;
  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(skip)]
  25. pub is_changed: bool,
  26. #[serde(skip)]
  27. pub is_not_default: bool,
  28. #[serde(skip)]
  29. pub base_path: PathBuf,
  30. #[serde(rename(serialize = "repo_type", deserialize = "repo_type"), default)]
  31. pub repo_types: BTreeMap<String, RepoType>,
  32. #[serde(rename(serialize = "repository", deserialize = "repository"), default)]
  33. pub repositories: BTreeMap<String, Repository>,
  34. #[serde(rename(serialize = "action", deserialize = "action"), default)]
  35. pub actions: BTreeMap<String, Action>,
  36. #[serde(rename(serialize = "group", deserialize = "group"), default)]
  37. pub groups: BTreeMap<String, Group>,
  38. }
  39. pub fn find_config_file(original: Option<&str>) -> PathBuf {
  40. match original {
  41. None => {
  42. let config_name = PathBuf::from(".config/sync-it/config.toml");
  43. let mut path_name = home_dir().unwrap().join(config_name);
  44. if path_name.exists() {
  45. return path_name;
  46. }
  47. path_name = home_dir().unwrap().join(PathBuf::from(".sync-it.toml"));
  48. return path_name;
  49. },
  50. Some(p) => return PathBuf::from(&p),
  51. }
  52. }
  53. pub fn read_configuration_file(filename: &PathBuf) -> Config {
  54. let text = read_to_string(filename);
  55. match text {
  56. Err(_) => {
  57. let config = Config {
  58. is_changed: true,
  59. is_not_default: false,
  60. base_path: filename.parent().unwrap().to_path_buf(),
  61. repo_types: BTreeMap::new(),
  62. repositories: BTreeMap::new(),
  63. actions: BTreeMap::new(),
  64. groups: BTreeMap::new()
  65. };
  66. return config;
  67. },
  68. Ok(s) => {
  69. let mut config: Config = toml::from_str(&s).unwrap();
  70. config.is_changed = false;
  71. return config;
  72. }
  73. }
  74. }
  75. pub fn write_configuration_file(filename: PathBuf, configuration: Config) -> std::io::Result<()> {
  76. if configuration.is_changed {
  77. let toml = toml::to_string_pretty(&configuration).unwrap();
  78. let mut file = File::create(filename)?;
  79. file.write_all(toml.as_bytes())?;
  80. Ok(())
  81. } else {
  82. Ok(())
  83. }
  84. }