fix: remove panics and unblock flows
This commit is contained in:
@@ -49,11 +49,7 @@ impl Default for GraspServersSettings {
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct LocalReposSettings {
|
||||
/// The directories scanned for local git repositories,
|
||||
/// Defaults:
|
||||
///
|
||||
/// - `~/Desktop`
|
||||
/// - `~/Documents`
|
||||
/// Directories scanned for local git repositories. `~/Desktop` and `~/Documents` by default.
|
||||
pub scan_paths: Vec<PathBuf>,
|
||||
}
|
||||
|
||||
@@ -65,10 +61,7 @@ impl Default for LocalReposSettings {
|
||||
}
|
||||
}
|
||||
|
||||
/// A remembered association between a local checkout folder and an announced repository,
|
||||
/// recorded when the user clones a repository or picks a folder in the New PR panel.
|
||||
///
|
||||
/// The panel can then prefill the folder later without asking again.
|
||||
/// A checkout folder paired with its announced repository, so the New PR panel can prefill it.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
|
||||
#[serde(default)]
|
||||
pub struct CheckoutRecord {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use anyhow::Result;
|
||||
use anyhow::{Result, bail};
|
||||
use gpui::{App, Context, Entity, Global};
|
||||
|
||||
use crate::Settings;
|
||||
@@ -9,13 +9,14 @@ struct GlobalSettingsStore(Entity<SettingsStore>);
|
||||
|
||||
impl Global for GlobalSettingsStore {}
|
||||
|
||||
/// The application settings,
|
||||
/// loaded from disk at startup and saved whenever they change.
|
||||
///
|
||||
/// Installed as a global by the app so any part of the UI can read and edit them.
|
||||
/// The application settings, loaded from disk and saved on change; installed as a global.
|
||||
pub struct SettingsStore {
|
||||
path: PathBuf,
|
||||
settings: Settings,
|
||||
/// Why the on-disk file was not loaded; such a file is never overwritten.
|
||||
unreadable: Option<String>,
|
||||
/// Why the settings are currently not persisted.
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
impl SettingsStore {
|
||||
@@ -34,15 +35,14 @@ impl SettingsStore {
|
||||
cx.set_global(GlobalSettingsStore(entity));
|
||||
}
|
||||
|
||||
/// Load the settings from `path`,
|
||||
/// falls back to defaults when the file is missing or unreadable.
|
||||
///
|
||||
/// Missing keys merge with the defaults,
|
||||
/// older settings files keep working as new settings are added.
|
||||
pub fn new(path: impl AsRef<Path>, _cx: &mut Context<Self>) -> Self {
|
||||
/// Loads the settings from `path`, with defaults for a missing or unreadable file.
|
||||
pub fn new(path: impl AsRef<Path>) -> Self {
|
||||
let (settings, error) = Self::load(path.as_ref());
|
||||
Self {
|
||||
path: path.as_ref().to_path_buf(),
|
||||
settings: Self::load(path.as_ref()),
|
||||
settings,
|
||||
unreadable: error.clone(),
|
||||
error,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -54,103 +54,59 @@ impl SettingsStore {
|
||||
/// Mutate the settings, persist them to disk, and notify observers.
|
||||
pub fn edit(&mut self, f: impl FnOnce(&mut Settings), cx: &mut Context<Self>) {
|
||||
f(&mut self.settings);
|
||||
if let Err(err) = self.save() {
|
||||
log::error!(
|
||||
"failed to save settings to {}: {err:#}",
|
||||
self.path.display()
|
||||
);
|
||||
match self.save() {
|
||||
Ok(()) => self.error = None,
|
||||
Err(err) => {
|
||||
log::error!(
|
||||
"failed to save settings to {}: {err:#}",
|
||||
self.path.display()
|
||||
);
|
||||
self.error = Some(format!("{err:#}"));
|
||||
}
|
||||
}
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
/// Read the settings file, merging any missing fields with the defaults.
|
||||
fn load(path: &Path) -> Settings {
|
||||
fn load(path: &Path) -> (Settings, Option<String>) {
|
||||
match std::fs::read_to_string(path) {
|
||||
Ok(contents) => match serde_json::from_str::<Settings>(&contents) {
|
||||
Ok(settings) => settings,
|
||||
Ok(settings) => (settings, None),
|
||||
Err(err) => {
|
||||
log::error!(
|
||||
"failed to parse settings file {}: {err}; using defaults",
|
||||
path.display()
|
||||
);
|
||||
Settings::default()
|
||||
let error = format!("failed to parse settings file {}: {err}", path.display());
|
||||
log::error!("{error}; using defaults");
|
||||
(Settings::default(), Some(error))
|
||||
}
|
||||
},
|
||||
Err(err) if err.kind() == std::io::ErrorKind::NotFound => Settings::default(),
|
||||
Err(err) if err.kind() == std::io::ErrorKind::NotFound => (Settings::default(), None),
|
||||
Err(err) => {
|
||||
log::error!(
|
||||
"failed to read settings file {}: {err}; using defaults",
|
||||
path.display()
|
||||
);
|
||||
Settings::default()
|
||||
let error = format!("failed to read settings file {}: {err}", path.display());
|
||||
log::error!("{error}; using defaults");
|
||||
(Settings::default(), Some(error))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Write the settings to disk, replacing the file atomically.
|
||||
fn save(&self) -> Result<()> {
|
||||
if let Some(reason) = &self.unreadable {
|
||||
bail!("settings file was not loaded and is left untouched: {reason}");
|
||||
}
|
||||
|
||||
if let Some(parent) = self.path.parent() {
|
||||
std::fs::create_dir_all(parent)?;
|
||||
}
|
||||
|
||||
let json = serde_json::to_string_pretty(&self.settings)?;
|
||||
let tmp = self.path.with_extension("json.tmp");
|
||||
std::fs::write(&tmp, json)?;
|
||||
|
||||
// `rename` cannot replace an existing file on Windows.
|
||||
if cfg!(target_os = "windows") && self.path.exists() {
|
||||
std::fs::remove_file(&self.path)?;
|
||||
}
|
||||
|
||||
std::fs::rename(&tmp, &self.path)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
use super::*;
|
||||
|
||||
static TEST_FILE_COUNTER: AtomicUsize = AtomicUsize::new(0);
|
||||
|
||||
/// A unique, temporary settings path for one test.
|
||||
fn temp_settings_path() -> PathBuf {
|
||||
let n = TEST_FILE_COUNTER.fetch_add(1, Ordering::SeqCst);
|
||||
std::env::temp_dir().join(format!(
|
||||
"signed-settings-test-{}-{n}.json",
|
||||
std::process::id()
|
||||
))
|
||||
}
|
||||
|
||||
fn cleanup(path: &Path) {
|
||||
let _ = std::fs::remove_file(path);
|
||||
let _ = std::fs::remove_file(path.with_extension("json.tmp"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_file_loads_defaults() {
|
||||
let path = temp_settings_path();
|
||||
cleanup(&path);
|
||||
|
||||
let settings = SettingsStore::load(&path);
|
||||
assert_eq!(settings, Settings::default());
|
||||
cleanup(&path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_and_load_roundtrip() {
|
||||
let path = temp_settings_path();
|
||||
cleanup(&path);
|
||||
|
||||
let mut expected = Settings::default();
|
||||
expected.create_repository.default_folder = Some(PathBuf::from("/tmp/repos"));
|
||||
|
||||
let store = SettingsStore {
|
||||
path: path.clone(),
|
||||
settings: expected.clone(),
|
||||
};
|
||||
store.save().unwrap();
|
||||
|
||||
assert_eq!(SettingsStore::load(&path), expected);
|
||||
cleanup(&path);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user