settings.rs 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. use anyhow::anyhow;
  2. use serde::{Deserialize, Serialize};
  3. use std::fs::File;
  4. use std::io::Write;
  5. use std::path::Path;
  6. use tauri_api::file::read_string;
  7. use tauri_api::path::{resolve_path, BaseDirectory};
  8. /// Tauri Settings.
  9. #[derive(Default, Deserialize, Serialize)]
  10. pub struct Settings {
  11. /// Whether the user allows notifications or not.
  12. #[cfg(notification)]
  13. pub allow_notification: Option<bool>,
  14. }
  15. /// Gets the path to the settings file
  16. fn get_settings_path() -> tauri_api::Result<String> {
  17. resolve_path(".tauri-settings.json".to_string(), Some(BaseDirectory::App))
  18. }
  19. /// Write the settings to the file system.
  20. pub(crate) fn write_settings(settings: Settings) -> crate::Result<()> {
  21. let settings_path = get_settings_path()?;
  22. let settings_folder = Path::new(&settings_path).parent().unwrap();
  23. if !settings_folder.exists() {
  24. std::fs::create_dir(settings_folder)?;
  25. }
  26. File::create(settings_path)
  27. .map_err(|e| anyhow!(e))
  28. .and_then(|mut f| {
  29. f.write_all(serde_json::to_string(&settings)?.as_bytes())
  30. .map_err(|err| anyhow!(err))
  31. })
  32. }
  33. /// Reads the settings from the file system.
  34. pub fn read_settings() -> crate::Result<Settings> {
  35. let settings_path = get_settings_path()?;
  36. if Path::new(settings_path.as_str()).exists() {
  37. read_string(settings_path)
  38. .and_then(|settings| serde_json::from_str(settings.as_str()).map_err(|e| anyhow!(e)))
  39. } else {
  40. Ok(Default::default())
  41. }
  42. }