refactor: upgrade crates and restructure project

This commit is contained in:
objz committed 2026-04-18 16:59:27 +02:00
1 parent ea093c044f
commit 47dad69321
80 files changed
+6094 -6125

No files matched your search

+33 -89
View File
@@ -1,99 +1,49 @@
use config::{Config as ConfigLoader, ConfigError, File};
use dirs_next::config_dir;
use once_cell::sync::Lazy;
use std::fs;
use std::path::PathBuf;
use types::Config;
use std::sync::LazyLock;
pub mod types;
pub mod settings;
pub mod theme;
pub use settings::Config;
#[must_use]
pub fn get_config_path() -> PathBuf {
match config_dir() {
Some(base_dir) => base_dir.join("mcl/"),
None => {
tracing::error!("Could not determine config directory, falling back to ./config/");
PathBuf::from("./config/")
}
}
dirs_next::config_dir()
.unwrap_or_else(|| PathBuf::from("."))
.join("mcl")
}
fn ensure_config_exists(default_path: &str) -> PathBuf {
fn ensure_config_exists() -> PathBuf {
let config_path = get_config_path().join("config.toml");
if !config_path.exists() {
if let Some(parent_dir) = config_path.parent() {
match fs::create_dir_all(parent_dir) {
Ok(_) => {}
Err(e) => {
tracing::error!("Failed to create configuration directory: {}", e);
}
}
}
match fs::copy(default_path, &config_path) {
Ok(_) => {
tracing::debug!(
"Default configuration copied to '{}'",
config_path.display()
);
}
Err(e) => {
tracing::error!(
"Failed to copy default config from '{}' to '{}': {}",
default_path,
config_path.display(),
e
);
}
if let Some(parent) = config_path.parent() {
let _ = fs::create_dir_all(parent);
}
let _ = fs::write(&config_path, include_str!("../../assets/config.toml"));
}
config_path
}
pub fn load_config(config_path: &std::path::Path) -> Result<Config, ConfigError> {
let built = match ConfigLoader::builder()
ConfigLoader::builder()
.add_source(File::from(config_path).required(false))
.build()
{
Ok(c) => c,
Err(e) => {
tracing::error!(
"Failed to build config from '{}': {}",
config_path.display(),
e
);
return Err(e);
}
};
match built.try_deserialize() {
Ok(config) => Ok(config),
Err(e) => {
tracing::error!(
"Failed to deserialize config from '{}': {}",
config_path.display(),
e
);
Err(e)
}
}
.build()?
.try_deserialize()
}
pub static SETTINGS: Lazy<Config> = Lazy::new(|| {
let path: PathBuf = ensure_config_exists("assets/config.toml");
match load_config(&path) {
Ok(config) => config,
Err(e) => {
tracing::error!("Config load failed, using defaults: {}", e);
Config {
general: types::General::default(),
paths: types::Paths::default(),
defaults: types::Defaults::default(),
ui: types::Ui::default(),
}
pub static SETTINGS: LazyLock<Config> = LazyLock::new(|| {
let path = ensure_config_exists();
load_config(&path).unwrap_or_else(|e| {
tracing::error!("Config load failed, using defaults: {}", e);
Config {
general: settings::General::default(),
paths: settings::Paths::default(),
defaults: settings::Defaults::default(),
ui: settings::Ui::default(),
}
}
})
});
#[cfg(test)]
@@ -107,16 +57,12 @@ mod tests {
std::fs::write(
&path,
r#"
[general]
debug = true
[defaults]
memory_max = "4G"
"#,
[defaults]
memory_max = "4G"
"#,
)
.unwrap();
let config = load_config(&path).unwrap();
assert!(config.general.debug);
assert_eq!(config.defaults.memory_max, "4G");
assert_eq!(config.defaults.memory_min, "512M");
}
@@ -127,7 +73,6 @@ memory_max = "4G"
let path = tmp.path().join("config.toml");
std::fs::write(&path, "").unwrap();
let config = load_config(&path).unwrap();
assert!(!config.general.debug);
assert_eq!(config.defaults.memory_max, "2G");
}
@@ -135,8 +80,7 @@ memory_max = "4G"
fn load_config_missing_file_uses_defaults() {
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("nonexistent.toml");
let config = load_config(&path).unwrap();
assert!(!config.general.debug);
load_config(&path).unwrap();
}
#[test]
@@ -146,9 +90,9 @@ memory_max = "4G"
std::fs::write(
&path,
r#"
[paths]
instances_dir = "/custom/path"
"#,
[paths]
instances_dir = "/custom/path"
"#,
)
.unwrap();
let config = load_config(&path).unwrap();
+51 -79
View File
@@ -1,11 +1,9 @@
use dirs_next;
use std::path::PathBuf;
use serde::Deserialize;
#[derive(Debug, Deserialize, Default)]
pub struct General {
#[serde(default)]
pub debug: bool,
}
pub struct General {}
#[derive(Debug, Deserialize)]
pub struct Paths {
@@ -18,16 +16,26 @@ pub struct Paths {
}
fn default_instances_dir() -> String {
"~/.local/share/mcl/instances".to_string()
dirs_next::data_dir()
.unwrap_or_else(|| PathBuf::from("."))
.join("mcl")
.join("instances")
.to_string_lossy()
.into_owned()
}
fn default_meta_dir() -> String {
"~/.local/share/mcl/meta".to_string()
dirs_next::data_dir()
.unwrap_or_else(|| PathBuf::from("."))
.join("mcl")
.join("meta")
.to_string_lossy()
.into_owned()
}
impl Default for Paths {
fn default() -> Self {
Paths {
Self {
instances_dir: default_instances_dir(),
meta_dir: default_meta_dir(),
java_path: None,
@@ -35,43 +43,30 @@ impl Default for Paths {
}
}
pub fn resolve_path(raw: &str) -> PathBuf {
if let Some(stripped) = raw.strip_prefix("~/") {
if let Some(home) = dirs_next::home_dir() {
return home.join(stripped);
}
} else if raw == "~" {
if let Some(home) = dirs_next::home_dir() {
return home;
}
}
PathBuf::from(raw)
}
impl Paths {
pub fn effective_java_path(&self) -> Option<&str> {
self.java_path.as_deref().filter(|s| !s.is_empty())
}
pub fn resolve_instances_dir(&self) -> std::path::PathBuf {
let raw = &self.instances_dir;
if let Some(stripped) = raw.strip_prefix("~/") {
return match dirs_next::home_dir() {
Some(home) => home.join(stripped),
None => std::path::PathBuf::from(raw),
};
}
if raw == "~" {
return match dirs_next::home_dir() {
Some(home) => home,
None => std::path::PathBuf::from(raw),
};
}
std::path::PathBuf::from(raw)
pub fn resolve_instances_dir(&self) -> PathBuf {
resolve_path(&self.instances_dir)
}
pub fn resolve_meta_dir(&self) -> std::path::PathBuf {
let raw = &self.meta_dir;
if let Some(stripped) = raw.strip_prefix("~/") {
return match dirs_next::home_dir() {
Some(home) => home.join(stripped),
None => std::path::PathBuf::from(raw),
};
}
if raw == "~" {
return match dirs_next::home_dir() {
Some(home) => home,
None => std::path::PathBuf::from(raw),
};
}
std::path::PathBuf::from(raw)
pub fn resolve_meta_dir(&self) -> PathBuf {
resolve_path(&self.meta_dir)
}
}
@@ -84,16 +79,15 @@ pub struct Defaults {
}
fn default_memory_min() -> String {
"512M".to_string()
"512M".to_owned()
}
fn default_memory_max() -> String {
"2G".to_string()
"2G".to_owned()
}
impl Default for Defaults {
fn default() -> Self {
Defaults {
Self {
memory_min: default_memory_min(),
memory_max: default_memory_max(),
}
@@ -115,22 +109,19 @@ pub struct Ui {
fn default_error_auto_dismiss_ms() -> u64 {
5000
}
fn default_error_slide_start_ms() -> u64 {
3500
}
fn default_error_fly_out_ms() -> u64 {
300
}
fn default_max_error_events() -> usize {
50
}
impl Default for Ui {
fn default() -> Self {
Ui {
Self {
error_auto_dismiss_ms: default_error_auto_dismiss_ms(),
error_slide_start_ms: default_error_slide_start_ms(),
error_fly_out_ms: default_error_fly_out_ms(),
@@ -176,66 +167,49 @@ mod tests {
#[test]
fn effective_java_path_some_when_set() {
let paths = Paths {
java_path: Some("/usr/bin/java".to_string()),
java_path: Some("/usr/bin/java".to_owned()),
..Paths::default()
};
assert_eq!(paths.effective_java_path(), Some("/usr/bin/java"));
}
#[test]
fn resolve_instances_dir_absolute_path() {
let paths = Paths {
instances_dir: "/opt/mcl/instances".to_string(),
..Paths::default()
};
assert_eq!(
paths.resolve_instances_dir(),
std::path::PathBuf::from("/opt/mcl/instances")
);
fn resolve_path_absolute() {
assert_eq!(resolve_path("/opt/mcl"), PathBuf::from("/opt/mcl"));
}
#[test]
fn resolve_instances_dir_tilde_prefix() {
let paths = Paths {
instances_dir: "~/games/mcl".to_string(),
..Paths::default()
};
let resolved = paths.resolve_instances_dir();
fn resolve_path_tilde_prefix() {
let resolved = resolve_path("~/games/mcl");
assert!(!resolved.to_string_lossy().starts_with('~'));
assert!(resolved.to_string_lossy().ends_with("games/mcl"));
}
#[test]
fn resolve_instances_dir_bare_tilde() {
let paths = Paths {
instances_dir: "~".to_string(),
..Paths::default()
};
let resolved = paths.resolve_instances_dir();
fn resolve_path_bare_tilde() {
let resolved = resolve_path("~");
assert!(!resolved.to_string_lossy().starts_with('~'));
}
#[test]
fn resolve_meta_dir_absolute_path() {
fn resolve_instances_dir_absolute() {
let paths = Paths {
meta_dir: "/opt/mcl/meta".to_string(),
instances_dir: "/opt/mcl/instances".to_owned(),
..Paths::default()
};
assert_eq!(
paths.resolve_meta_dir(),
std::path::PathBuf::from("/opt/mcl/meta")
paths.resolve_instances_dir(),
PathBuf::from("/opt/mcl/instances")
);
}
#[test]
fn resolve_meta_dir_tilde_prefix() {
fn resolve_meta_dir_absolute() {
let paths = Paths {
meta_dir: "~/mcl/meta".to_string(),
meta_dir: "/opt/mcl/meta".to_owned(),
..Paths::default()
};
let resolved = paths.resolve_meta_dir();
assert!(!resolved.to_string_lossy().starts_with('~'));
assert!(resolved.to_string_lossy().ends_with("mcl/meta"));
assert_eq!(paths.resolve_meta_dir(), PathBuf::from("/opt/mcl/meta"));
}
#[test]
@@ -257,7 +231,6 @@ mod tests {
#[test]
fn config_deserializes_from_empty_toml() {
let config: Config = toml::from_str("").unwrap();
assert!(!config.general.debug);
assert_eq!(config.defaults.memory_max, "2G");
}
@@ -271,7 +244,6 @@ debug = true
memory_max = "8G"
"#;
let config: Config = toml::from_str(toml_str).unwrap();
assert!(config.general.debug);
assert_eq!(config.defaults.memory_max, "8G");
assert_eq!(config.defaults.memory_min, "512M");
}
+244
View File
@@ -0,0 +1,244 @@
use std::path::Path;
use std::sync::LazyLock;
use ratatui::style::Color;
use ratatui::widgets::BorderType;
use ratatui_themekit::{CustomTheme, Theme, resolve_theme};
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum BorderStyle {
#[default]
Rounded,
Plain,
Double,
Thick,
}
impl BorderStyle {
pub fn to_border_type(&self) -> BorderType {
match self {
Self::Rounded => BorderType::Rounded,
Self::Plain => BorderType::Plain,
Self::Double => BorderType::Double,
Self::Thick => BorderType::Thick,
}
}
}
#[derive(Debug, Deserialize, Default)]
pub struct ThemeOverrides {
pub accent: Option<Color>,
pub accent_dim: Option<Color>,
pub text: Option<Color>,
pub text_dim: Option<Color>,
pub text_bright: Option<Color>,
pub success: Option<Color>,
pub error: Option<Color>,
pub warning: Option<Color>,
pub info: Option<Color>,
pub diff_added: Option<Color>,
pub diff_removed: Option<Color>,
pub diff_context: Option<Color>,
pub border: Option<Color>,
pub surface: Option<Color>,
pub background: Option<Color>,
}
#[derive(Debug, Deserialize)]
pub struct ThemeConfig {
#[serde(default)]
pub border_style: BorderStyle,
#[serde(default = "default_theme_name")]
pub theme: String,
#[serde(default)]
pub custom: Option<ThemeOverrides>,
}
fn default_theme_name() -> String {
"catppuccin".to_owned()
}
impl Default for ThemeConfig {
fn default() -> Self {
Self {
border_style: BorderStyle::default(),
theme: default_theme_name(),
custom: None,
}
}
}
fn load_theme_config() -> ThemeConfig {
let path = super::get_config_path().join("theme.toml");
ensure_theme_exists(&path);
match std::fs::read_to_string(&path) {
Ok(content) => toml::from_str(&content).unwrap_or_else(|e| {
tracing::warn!("Failed to parse theme.toml: {}. Using defaults.", e);
ThemeConfig::default()
}),
Err(_) => ThemeConfig::default(),
}
}
fn ensure_theme_exists(path: &Path) {
if path.exists() {
return;
}
if let Some(parent) = path.parent() {
let _ = std::fs::create_dir_all(parent);
}
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);
let Some(overrides) = &config.custom else {
return base;
};
Box::new(CustomTheme {
name: format!("{} (customized)", base.name()),
id: base.id().to_owned(),
accent: overrides.accent.unwrap_or_else(|| base.accent()),
accent_dim: overrides.accent_dim.unwrap_or_else(|| base.accent_dim()),
text: overrides.text.unwrap_or_else(|| base.text()),
text_dim: overrides.text_dim.unwrap_or_else(|| base.text_dim()),
text_bright: overrides.text_bright.unwrap_or_else(|| base.text_bright()),
success: overrides.success.unwrap_or_else(|| base.success()),
error: overrides.error.unwrap_or_else(|| base.error()),
warning: overrides.warning.unwrap_or_else(|| base.warning()),
info: overrides.info.unwrap_or_else(|| base.info()),
diff_added: overrides.diff_added.unwrap_or_else(|| base.diff_added()),
diff_removed: overrides.diff_removed.unwrap_or_else(|| base.diff_removed()),
diff_context: overrides.diff_context.unwrap_or_else(|| base.diff_context()),
border: overrides.border.unwrap_or_else(|| base.border()),
surface: overrides.surface.unwrap_or_else(|| base.surface()),
background: overrides.background.unwrap_or_else(|| base.background()),
})
}
/// Load a base theme by built-in name or file path.
fn load_base_theme(name: &str) -> Box<dyn Theme> {
// Try as a file path first (absolute or relative to config dir)
let path = if Path::new(name).is_absolute() {
Some(std::path::PathBuf::from(name))
} else {
// Check in the mcl config theme directory
let theme_dir = super::get_config_path().join("theme");
let candidate = theme_dir.join(name);
if candidate.exists() {
Some(candidate)
} else {
let with_ext = theme_dir.join(format!("{name}.toml"));
if with_ext.exists() {
Some(with_ext)
} else {
None
}
}
};
if let Some(path) = path {
if let Ok(content) = std::fs::read_to_string(&path) {
if let Ok(custom) = toml::from_str::<CustomTheme>(&content) {
return Box::new(custom);
} else {
tracing::warn!("Failed to parse theme file: {}", path.display());
}
}
}
// Fall back to built-in theme by name
resolve_theme(name)
}
static THEME_CONFIG: LazyLock<ThemeConfig> = LazyLock::new(load_theme_config);
pub static THEME: LazyLock<Box<dyn Theme>> = LazyLock::new(|| resolve_app_theme(&THEME_CONFIG));
pub static BORDER_STYLE: LazyLock<BorderStyle> =
LazyLock::new(|| THEME_CONFIG.border_style.clone());
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn default_theme_config() {
let config = ThemeConfig::default();
assert_eq!(config.theme, "catppuccin");
assert_eq!(config.border_style, BorderStyle::Rounded);
assert!(config.custom.is_none());
}
#[test]
fn border_style_roundtrip() {
let style = BorderStyle::Double;
assert_eq!(style.to_border_type(), BorderType::Double);
}
#[test]
fn theme_config_deserialize_builtin() {
let toml_str = r#"
theme = "dracula"
border_style = "plain"
"#;
let config: ThemeConfig = toml::from_str(toml_str).unwrap();
assert_eq!(config.theme, "dracula");
assert_eq!(config.border_style, BorderStyle::Plain);
assert!(config.custom.is_none());
}
#[test]
fn theme_config_with_partial_overrides() {
let toml_str = r#"
theme = "dracula"
[custom]
accent = "Red"
"#;
let config: ThemeConfig = toml::from_str(toml_str).unwrap();
assert_eq!(config.theme, "dracula");
let overrides = config.custom.unwrap();
assert_eq!(overrides.accent, Some(Color::Red));
assert!(overrides.text.is_none());
}
#[test]
fn resolve_with_overrides_keeps_base() {
let config = ThemeConfig {
theme: "dracula".to_owned(),
custom: Some(ThemeOverrides {
accent: Some(Color::Red),
..ThemeOverrides::default()
}),
..ThemeConfig::default()
};
let theme = resolve_app_theme(&config);
assert_eq!(theme.accent(), Color::Red);
// Other colors should come from dracula base
let base = resolve_theme("dracula");
assert_eq!(theme.text(), base.text());
assert_eq!(theme.error(), base.error());
}
#[test]
fn resolve_builtin_theme() {
let config = ThemeConfig {
theme: "dracula".to_owned(),
..ThemeConfig::default()
};
let theme = resolve_app_theme(&config);
assert_eq!(theme.id(), "dracula");
}
#[test]
fn theme_config_empty_toml_uses_defaults() {
let config: ThemeConfig = toml::from_str("").unwrap();
assert_eq!(config.theme, "catppuccin");
assert_eq!(config.border_style, BorderStyle::Rounded);
}
}