config.rs 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. // SPDX-FileCopyrightText: 2021 - 2022 Samuel W. Flint <swflint@flintfam.org>
  2. //
  3. // SPDX-License-Identifier: GPL-3.0-or-later
  4. use serde::{Deserialize, Serialize};
  5. use std::collections::BTreeMap;
  6. use std::path::PathBuf;
  7. use std::fs::{
  8. File,
  9. read_to_string
  10. };
  11. use std::io::Write;
  12. use home::home_dir;
  13. use crate::lib::repository::{
  14. Repository
  15. };
  16. use crate::lib::repotype::{
  17. RepoType
  18. };
  19. use crate::lib::action::{
  20. Action
  21. };
  22. use crate::lib::group::{
  23. Group
  24. };
  25. #[derive(Serialize, Deserialize)]
  26. pub struct Config {
  27. #[serde(skip)]
  28. pub is_changed: bool,
  29. #[serde(skip)]
  30. pub is_not_default: bool,
  31. #[serde(skip)]
  32. pub base_path: PathBuf,
  33. #[serde(rename(serialize = "repo_type", deserialize = "repo_type"), default)]
  34. pub repo_types: BTreeMap<String, RepoType>,
  35. #[serde(rename(serialize = "repository", deserialize = "repository"), default)]
  36. pub repositories: BTreeMap<String, Repository>,
  37. #[serde(rename(serialize = "action", deserialize = "action"), default)]
  38. pub actions: BTreeMap<String, Action>,
  39. #[serde(rename(serialize = "group", deserialize = "group"), default)]
  40. pub groups: BTreeMap<String, Group>,
  41. }
  42. pub fn find_config_file(original: Option<&String>) -> PathBuf {
  43. match original {
  44. None => {
  45. let config_name = PathBuf::from(".config/sync-it/config.toml");
  46. let mut path_name = home_dir().unwrap().join(config_name);
  47. if path_name.exists() {
  48. return path_name;
  49. }
  50. path_name = home_dir().unwrap().join(PathBuf::from(".sync-it.toml"));
  51. return path_name;
  52. },
  53. Some(p) => return PathBuf::from(&p),
  54. }
  55. }
  56. pub fn read_configuration_file(filename: &PathBuf) -> Config {
  57. let text = read_to_string(filename);
  58. match text {
  59. Err(_) => {
  60. let config = Config {
  61. is_changed: true,
  62. is_not_default: false,
  63. base_path: filename.parent().unwrap().to_path_buf(),
  64. repo_types: BTreeMap::new(),
  65. repositories: BTreeMap::new(),
  66. actions: BTreeMap::new(),
  67. groups: BTreeMap::new()
  68. };
  69. return config;
  70. },
  71. Ok(s) => {
  72. let mut config: Config = toml::from_str(&s).unwrap();
  73. config.is_changed = false;
  74. return config;
  75. }
  76. }
  77. }
  78. pub fn write_configuration_file(filename: PathBuf, configuration: Config) -> std::io::Result<()> {
  79. if configuration.is_changed {
  80. let toml = toml::to_string_pretty(&configuration).unwrap();
  81. let mut file = File::create(filename)?;
  82. file.write_all(toml.as_bytes())?;
  83. Ok(())
  84. } else {
  85. Ok(())
  86. }
  87. }