use crate::error::{Error, Result};
use crate::sandbox::docker::DockerConfig;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::PathBuf;
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct SandboxConfigFile {
pub default_sandbox: Option<String>,
pub sandboxes: HashMap<String, DockerConfig>,
}
impl SandboxConfigFile {
pub fn config_path() -> Result<PathBuf> {
let config_dir = dirs::config_dir()
.ok_or_else(|| Error::config("Could not determine config directory"))?;
let cert_x_gen_dir = config_dir.join("cert-x-gen");
if !cert_x_gen_dir.exists() {
std::fs::create_dir_all(&cert_x_gen_dir)
.map_err(|e| Error::config(format!("Failed to create config directory: {}", e)))?;
}
Ok(cert_x_gen_dir.join("sandbox-config.yaml"))
}
pub fn load() -> Result<Self> {
let path = Self::config_path()?;
if !path.exists() {
return Ok(Self::default());
}
let content = std::fs::read_to_string(&path)
.map_err(|e| Error::config(format!("Failed to read sandbox config: {}", e)))?;
serde_yaml::from_str(&content)
.map_err(|e| Error::config(format!("Failed to parse sandbox config: {}", e)))
}
pub fn save(&self) -> Result<()> {
let path = Self::config_path()?;
let content = serde_yaml::to_string(self)
.map_err(|e| Error::config(format!("Failed to serialize sandbox config: {}", e)))?;
std::fs::write(&path, content)
.map_err(|e| Error::config(format!("Failed to write sandbox config: {}", e)))?;
Ok(())
}
pub fn set_sandbox(&mut self, name: String, config: DockerConfig) {
self.sandboxes.insert(name, config);
}
pub fn remove_sandbox(&mut self, name: &str) -> Option<DockerConfig> {
if self.default_sandbox.as_deref() == Some(name) {
self.default_sandbox = None;
}
self.sandboxes.remove(name)
}
pub fn get_sandbox(&self, name: &str) -> Option<&DockerConfig> {
self.sandboxes.get(name)
}
pub fn set_default(&mut self, name: Option<String>) {
self.default_sandbox = name;
}
pub fn get_default_sandbox(&self) -> Option<(&String, &DockerConfig)> {
self.default_sandbox
.as_ref()
.and_then(|name| self.sandboxes.get(name).map(|config| (name, config)))
}
}