settings.rs 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. // Copyright 2019-2021 Tauri Programme within The Commons Conservancy
  2. // SPDX-License-Identifier: Apache-2.0
  3. // SPDX-License-Identifier: MIT
  4. use crate::{
  5. api::{
  6. file::read_string,
  7. path::{resolve_path, BaseDirectory},
  8. },
  9. Config,
  10. };
  11. use serde::{Deserialize, Serialize};
  12. use std::{
  13. fs::File,
  14. io::Write,
  15. path::{Path, PathBuf},
  16. };
  17. /// Tauri Settings.
  18. #[derive(Default, Deserialize, Serialize)]
  19. #[non_exhaustive]
  20. pub struct Settings {
  21. /// Whether the user allows notifications or not.
  22. #[cfg(notification_all)]
  23. pub allow_notification: Option<bool>,
  24. }
  25. /// Gets the path to the settings file
  26. fn get_settings_path(config: &Config) -> crate::api::Result<PathBuf> {
  27. resolve_path(config, ".tauri-settings.json", Some(BaseDirectory::App))
  28. }
  29. /// Write the settings to the file system.
  30. #[allow(dead_code)]
  31. pub(crate) fn write_settings(config: &Config, settings: Settings) -> crate::Result<()> {
  32. let settings_path = get_settings_path(config)?;
  33. let settings_folder = Path::new(&settings_path).parent().unwrap();
  34. if !settings_folder.exists() {
  35. std::fs::create_dir(settings_folder)?;
  36. }
  37. File::create(settings_path)
  38. .map_err(Into::into)
  39. .and_then(|mut f| {
  40. f.write_all(serde_json::to_string(&settings)?.as_bytes())
  41. .map_err(Into::into)
  42. })
  43. }
  44. /// Reads the settings from the file system.
  45. pub fn read_settings(config: &Config) -> crate::Result<Settings> {
  46. let settings_path = get_settings_path(config)?;
  47. if settings_path.exists() {
  48. read_string(settings_path)
  49. .and_then(|settings| serde_json::from_str(settings.as_str()).map_err(Into::into))
  50. .map_err(Into::into)
  51. } else {
  52. Ok(Default::default())
  53. }
  54. }