fix: preserve authoritative settings through profile switches and refreshes

This commit is contained in:
objz committed 2026-10-01 23:23:26 +02:00
1 parent dc351df546
commit 00ba2faffe
23 files changed
+3768 -527

No files matched your search

+7
View File
@@ -251,6 +251,13 @@ pub static SETTINGS: LazyLock<ConfigStore> = LazyLock::new(|| {
fn write_config_document(path: &std::path::Path, config: &Config) -> io::Result<()> {
write_merged_toml_document(path, config, |document| {
if let Some(environment) = document
.get_mut("defaults")
.and_then(|defaults| defaults.get_mut("environment"))
.and_then(toml_edit::Item::as_table_mut)
{
environment.retain(|key, _| config.defaults.environment.contains_key(key));
}
if config.paths.java_path.is_none()
&& let Some(paths) = document
.get_mut("paths")
+69 -3
View File
@@ -248,7 +248,7 @@ impl Default for Paths {
}
pub fn resolve_path(raw: &str) -> PathBuf {
if let Some(stripped) = raw.strip_prefix("~/") {
if let Some(stripped) = raw.strip_prefix("~/").or_else(|| raw.strip_prefix("~\\")) {
if let Some(home) = dirs::home_dir() {
return home.join(stripped);
}
@@ -315,9 +315,75 @@ impl Default for Defaults {
}
}
pub(crate) fn parse_tag_values(input: &str) -> Result<Vec<String>, String> {
#[derive(Clone, Copy, PartialEq, Eq)]
enum Quote {
None,
Single,
Double,
}
let mut values = Vec::new();
let mut current = String::new();
let mut quote = Quote::None;
let mut started = false;
let mut characters = input.chars().peekable();
while let Some(character) = characters.next() {
match (quote, character) {
(Quote::None, character) if character.is_whitespace() => {
if started {
values.push(std::mem::take(&mut current));
started = false;
}
}
(Quote::None, '\'') => {
quote = Quote::Single;
started = true;
}
(Quote::None, '"') => {
quote = Quote::Double;
started = true;
}
(Quote::Single, '\'') => quote = Quote::None,
(Quote::Double, '"') => quote = Quote::None,
(Quote::Double, '\\') if matches!(characters.peek(), Some('"' | '\\')) => {
current.push(characters.next().unwrap_or_default());
started = true;
}
(_, character) => {
current.push(character);
started = true;
}
}
}
if quote != Quote::None {
return Err("Quoted value is missing its closing quote.".to_owned());
}
if started {
values.push(current);
}
Ok(values)
}
pub(crate) fn format_tag_values(values: &[String]) -> String {
values
.iter()
.map(|value| {
if !value.is_empty()
&& !value
.chars()
.any(|character| character.is_whitespace() || matches!(character, '\'' | '"'))
{
value.clone()
} else {
format!("\"{}\"", value.replace('\\', "\\\\").replace('"', "\\\""))
}
})
.collect::<Vec<_>>()
.join(" ")
}
#[derive(Debug, Clone, Serialize, Deserialize)]
// timing knobs for the error toast animation: show for 5s, start sliding at 3.5s,
// fly off screen over 300ms. tweak these if the toasts feel too fast or slow.
pub struct Ui {
#[serde(default)]
pub image_protocol: ImageProtocol,
+22
View File
@@ -3,6 +3,28 @@
use super::*;
#[test]
fn saving_settings_removes_deleted_environment_keys_and_keeps_retained_comments() {
let temp = tempfile::tempdir().unwrap();
let path = temp.path().join("config.toml");
std::fs::write(
&path,
"[defaults.environment]\nKEEP = 'old' # retained\nREMOVE = 'gone'\n[unknown]\nvalue = 1\n",
)
.unwrap();
let mut config = Config::default();
config
.defaults
.environment
.insert("KEEP".to_owned(), "new".to_owned());
write_config_document(&path, &config).unwrap();
let source = std::fs::read_to_string(&path).unwrap();
assert!(!source.contains("REMOVE"));
assert!(source.contains("# retained"));
assert!(source.contains("[unknown]"));
assert_eq!(load_config(&path).unwrap().defaults.environment.len(), 1);
}
#[test]
fn load_config_from_valid_toml() {
let tmp = tempfile::tempdir().unwrap();
+8 -5
View File
@@ -80,15 +80,18 @@ fn resolve_path_absolute() {
#[test]
fn resolve_path_tilde_prefix() {
let resolved = resolve_path("~/games/rmcl");
assert!(!resolved.to_string_lossy().starts_with('~'));
assert!(resolved.to_string_lossy().ends_with("games/rmcl"));
let home = dirs::home_dir().expect("test environment has a home directory");
for path in ["~/games/rmcl", r"~\games/rmcl"] {
assert_eq!(resolve_path(path), home.join("games/rmcl"));
}
}
#[test]
fn resolve_path_bare_tilde() {
let resolved = resolve_path("~");
assert!(!resolved.to_string_lossy().starts_with('~'));
assert_eq!(
resolve_path("~"),
dirs::home_dir().expect("test environment has a home directory")
);
}
#[test]
+32 -5
View File
@@ -3,8 +3,6 @@
use super::*;
// cover every BorderStyle variant. a mutation that swaps two arms of the
// match (e.g. Rounded -> Plain) would slip past testing just one variant.
#[rstest::rstest]
#[case::plain(BorderStyle::Plain, BorderType::Plain)]
#[case::rounded(BorderStyle::Rounded, BorderType::Rounded)]
@@ -51,13 +49,43 @@ fn resolve_with_overrides_keeps_base() {
}),
..ThemeConfig::default()
};
let theme = resolve_app_theme(&config);
assert_eq!(theme.accent(), Color::Red);
let theme = resolve_app_theme(&config).unwrap();
assert_eq!(
theme.accent(),
if ratatui_themekit::no_color_active() {
resolve_theme("dracula").accent()
} else {
Color::Red
}
);
let base = resolve_theme("dracula");
assert_eq!(theme.text(), base.text());
assert_eq!(theme.error(), base.error());
}
#[test]
fn missing_and_invalid_custom_themes_are_errors() {
let temp = tempfile::tempdir().unwrap();
let path = temp.path().join("theme.toml");
let config = ThemeConfig {
theme: path.to_string_lossy().into_owned(),
..Default::default()
};
assert!(resolve_app_theme(&config).is_err());
std::fs::write(&path, "bad theme").unwrap();
assert!(resolve_app_theme(&config).is_err());
std::fs::write(&path, include_str!("../../../assets/example-theme.toml")).unwrap();
let theme = resolve_app_theme(&config).unwrap();
assert_eq!(
theme.id(),
if ratatui_themekit::no_color_active() {
"no-color"
} else {
"my-theme"
}
);
}
#[test]
fn resolve_builtin_theme() {
let theme = resolve_theme("dracula");
@@ -83,7 +111,6 @@ fn custom_theme_file_parses() {
toml::from_str::<CustomTheme>("name = \"X\"\nid = \"x\"\naccent = \"#f97316\"\n").unwrap();
assert_eq!(minimal.accent, Color::Rgb(249, 115, 22));
// the two failure modes users hit: nesting under [theme], or omitting name/id
assert!(
toml::from_str::<CustomTheme>("[theme]\nname = \"X\"\nid = \"x\"\naccent = \"Red\"\n")
.is_err()
+38 -53
View File
@@ -97,14 +97,17 @@ fn ensure_theme_exists(path: &Path) {
let _ = std::fs::write(path, include_str!("../../assets/theme.toml"));
}
fn resolve_app_theme(config: &ThemeConfig) -> Box<dyn Theme> {
let base = load_base_theme(&config.theme);
fn resolve_app_theme(config: &ThemeConfig) -> std::io::Result<Box<dyn Theme>> {
let base = load_base_theme(&config.theme)?;
if ratatui_themekit::no_color_active() {
return Ok(resolve_theme("catppuccin"));
}
let Some(overrides) = &config.custom else {
return base;
return Ok(base);
};
Box::new(CustomTheme {
Ok(Box::new(CustomTheme {
name: format!("{} (customized)", base.name()),
id: base.id().to_owned(),
accent: overrides.accent.unwrap_or_else(|| base.accent()),
@@ -126,10 +129,10 @@ fn resolve_app_theme(config: &ThemeConfig) -> Box<dyn Theme> {
border: overrides.border.unwrap_or_else(|| base.border()),
surface: overrides.surface.unwrap_or_else(|| base.surface()),
background: overrides.background.unwrap_or_else(|| base.background()),
})
}))
}
fn load_base_theme(name: &str) -> Box<dyn Theme> {
fn load_base_theme(name: &str) -> std::io::Result<Box<dyn Theme>> {
let path = if Path::new(name).is_absolute() {
Some(std::path::PathBuf::from(name))
} else {
@@ -147,20 +150,27 @@ fn load_base_theme(name: &str) -> Box<dyn Theme> {
}
};
if let Some(path) = path
&& let Ok(content) = std::fs::read_to_string(&path)
{
match toml::from_str::<CustomTheme>(&content) {
Ok(custom) => return Box::new(custom),
Err(e) => tracing::warn!(
"Failed to parse theme file {}: {e}. Theme files need top-level \
name, id and accent keys (not nested under [theme]).",
path.display()
),
}
if path.is_none() && ratatui_themekit::available_theme_ids().contains(&name) {
return Ok(resolve_theme(name));
}
resolve_theme(name)
let path = path.unwrap_or_else(|| {
super::get_config_path()
.join("theme")
.join(format!("{name}.toml"))
});
let content = std::fs::read_to_string(&path).map_err(|error| {
std::io::Error::new(
error.kind(),
format!("failed to load theme {}: {error}", path.display()),
)
})?;
let custom = toml::from_str::<CustomTheme>(&content).map_err(|error| {
std::io::Error::new(
std::io::ErrorKind::InvalidData,
format!("invalid theme {}: {error}", path.display()),
)
})?;
Ok(Box::new(custom))
}
pub struct ThemeStore(RwLock<Arc<dyn Theme>>);
@@ -215,7 +225,11 @@ pub static THEME: LazyLock<ThemeStore> = LazyLock::new(|| {
let config = THEME_CONFIG
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner);
ThemeStore(RwLock::new(Arc::from(resolve_app_theme(&config))))
let theme = resolve_app_theme(&config).unwrap_or_else(|error| {
tracing::error!("Could not load theme: {error}");
resolve_theme("catppuccin")
});
ThemeStore(RwLock::new(Arc::from(theme)))
});
pub static BORDER_STYLE: LazyLock<BorderStyleStore> = LazyLock::new(|| {
@@ -233,10 +247,10 @@ pub fn current_theme_config() -> ThemeConfig {
}
pub fn apply_theme(theme: String, border_style: BorderStyle) -> std::io::Result<()> {
validate_theme_name(&theme)?;
let mut config = current_theme_config();
config.theme = theme;
config.border_style = border_style.clone();
let resolved = resolve_app_theme(&config)?;
super::write_merged_toml_document(
&super::get_config_path().join("theme.toml"),
&config,
@@ -246,7 +260,7 @@ pub fn apply_theme(theme: String, border_style: BorderStyle) -> std::io::Result<
}
},
)?;
THEME.set(resolve_app_theme(&config));
THEME.set(resolved);
BORDER_STYLE.set(border_style);
*THEME_CONFIG
.write()
@@ -255,42 +269,13 @@ pub fn apply_theme(theme: String, border_style: BorderStyle) -> std::io::Result<
Ok(())
}
fn validate_theme_name(name: &str) -> std::io::Result<()> {
if ratatui_themekit::available_theme_ids().contains(&name) {
return Ok(());
}
let path = if Path::new(name).is_absolute() {
std::path::PathBuf::from(name)
} else {
let directory = super::get_config_path().join("theme");
let direct = directory.join(name);
if direct.exists() {
direct
} else {
directory.join(format!("{name}.toml"))
}
};
let content = std::fs::read_to_string(&path).map_err(|error| {
std::io::Error::new(
error.kind(),
format!("failed to load theme {}: {error}", path.display()),
)
})?;
toml::from_str::<CustomTheme>(&content).map_err(|error| {
std::io::Error::new(
std::io::ErrorKind::InvalidData,
format!("invalid theme {}: {error}", path.display()),
)
})?;
Ok(())
}
pub fn reload_theme() -> std::io::Result<()> {
let path = super::get_config_path().join("theme.toml");
let content = std::fs::read_to_string(path)?;
let config: ThemeConfig = toml::from_str(&content)
.map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error))?;
THEME.set(resolve_app_theme(&config));
let resolved = resolve_app_theme(&config)?;
THEME.set(resolved);
BORDER_STYLE.set(config.border_style.clone());
*THEME_CONFIG
.write()