use crate::error::{Context, Result};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use tokio::fs;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Config {
pub git: GitConfig,
#[serde(default)]
pub templates: HashMap<String, TemplateConfig>,
#[serde(default)]
pub validation: ValidationConfig,
#[serde(default)]
pub hooks: HooksConfig,
#[serde(default)]
pub auto: AutoConfig,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TemplateConfig {
#[serde(default)]
pub branch_prefix: Option<String>,
#[serde(default = "default_commit_format")]
pub commit_message_format: String,
}
fn default_commit_format() -> String {
"Save changes to {description}".to_string()
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GitConfig {
pub branch_prefix: String,
pub base_branch: String,
pub auto_push: bool,
pub remote_name: String,
#[serde(default)]
pub max_file_size: u64,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ValidationConfig {
#[serde(default = "default_validation_mode")]
pub mode: String,
#[serde(default)]
pub command: Option<String>,
}
fn default_validation_mode() -> String {
"off".to_string()
}
impl Default for ValidationConfig {
fn default() -> Self {
Self {
mode: default_validation_mode(),
command: None,
}
}
}
impl ValidationConfig {
pub fn is_required(&self) -> bool {
self.mode == "required"
}
pub fn is_off(&self) -> bool {
self.mode == "off"
}
}
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct HooksConfig {
#[serde(default)]
pub pre_save: Vec<String>,
#[serde(default)]
pub post_save: Vec<String>,
#[serde(default)]
pub pre_finish: Vec<String>,
#[serde(default)]
pub post_finish: Vec<String>,
}
impl HooksConfig {
pub fn get(&self, stage: &str) -> &[String] {
match stage {
"pre_save" => &self.pre_save,
"post_save" => &self.post_save,
"pre_finish" => &self.pre_finish,
"post_finish" => &self.post_finish,
_ => &[],
}
}
pub fn has_hooks(&self) -> bool {
!self.pre_save.is_empty()
|| !self.post_save.is_empty()
|| !self.pre_finish.is_empty()
|| !self.post_finish.is_empty()
}
}
impl Default for TemplateConfig {
fn default() -> Self {
Self {
branch_prefix: None,
commit_message_format: default_commit_format(),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct AutoConfig {
#[serde(default)]
pub save_on_switch: bool,
}
impl Default for Config {
fn default() -> Self {
let mut templates = HashMap::new();
templates.insert("refactor".to_string(), TemplateConfig {
branch_prefix: Some("refactor".to_string()),
commit_message_format: "Refactor: {description}".to_string(),
});
templates.insert("bugfix".to_string(), TemplateConfig {
branch_prefix: Some("fix".to_string()),
commit_message_format: "Fix: {description}".to_string(),
});
templates.insert("feature".to_string(), TemplateConfig {
branch_prefix: Some("feat".to_string()),
commit_message_format: "Feat: {description}".to_string(),
});
Self {
git: GitConfig {
branch_prefix: "codetree".to_string(),
base_branch: "main".to_string(),
auto_push: false,
remote_name: "origin".to_string(),
max_file_size: 0,
},
templates,
validation: ValidationConfig::default(),
hooks: HooksConfig::default(),
auto: AutoConfig::default(),
}
}
}
impl Config {
pub fn get_config_path(config_path: Option<&Path>) -> Result<PathBuf> {
match config_path {
Some(path) => Ok(path.to_path_buf()),
None => Self::default_config_path(),
}
}
pub async fn load(config_path: &Path) -> Result<Self> {
let config_file = config_path.to_path_buf();
if config_file.exists() {
let content = fs::read_to_string(&config_file)
.await
.with_context(|| format!("Failed to read config file: {:?}", config_file))?;
let config: Config = toml::from_str(&content)
.with_context(|| format!("Failed to parse config file: {:?}", config_file))?;
Ok(config)
} else {
let config = Self::default();
config.save(&config_file).await?;
Ok(config)
}
}
pub async fn save(&self, path: &Path) -> Result<()> {
if let Some(parent) = path.parent() {
fs::create_dir_all(parent).await
.with_context(|| format!("Failed to create config directory: {:?}", parent))?;
}
let content = toml::to_string_pretty(self)
.context("Failed to serialize configuration")?;
crate::atomic::write_atomic(path, content.as_bytes())
.with_context(|| format!("Failed to write config file: {:?}", path))?;
Ok(())
}
pub fn default_config_path() -> Result<PathBuf> {
let current_dir = std::env::current_dir()
.context("Failed to get current directory")?;
let local_config = current_dir.join(".codetree.toml");
if local_config.exists() {
return Ok(local_config);
}
if let Ok(home) = std::env::var("HOME") {
let global_config = PathBuf::from(home)
.join(".config")
.join("codetree")
.join("config.toml");
return Ok(global_config);
}
Ok(local_config)
}
pub fn validate(&self) -> Result<()> {
if self.git.branch_prefix.is_empty() {
bail!("branch_prefix cannot be empty");
}
if self.git.base_branch.is_empty() {
bail!("base_branch cannot be empty");
}
Ok(())
}
pub fn get_template(&self, name: &str) -> Option<&TemplateConfig> {
self.templates.get(name)
}
pub fn get_data_dir() -> Result<PathBuf> {
let current_dir = std::env::current_dir()
.context("Failed to get current directory")?;
Ok(current_dir.join(".codetree"))
}
pub async fn is_initialized() -> Result<bool> {
let data_dir = Self::get_data_dir()?;
Ok(data_dir.exists())
}
}
#[cfg(test)]
mod tests {
use super::*;
use tempfile::TempDir;
#[tokio::test]
async fn test_config_default_values() {
let config = Config::default();
assert_eq!(config.git.branch_prefix, "codetree");
assert_eq!(config.git.base_branch, "main");
}
#[tokio::test]
async fn test_config_save_and_load() -> Result<()> {
let temp_dir = TempDir::new().unwrap();
let config_path = temp_dir.path().join("test_config.toml");
let mut config = Config::default();
config.git.branch_prefix = "agent".to_string();
config.git.base_branch = "main".to_string();
config.save(&config_path).await?;
let loaded_config = Config::load(&config_path).await?;
assert_eq!(loaded_config.git.branch_prefix, "agent");
assert_eq!(loaded_config.git.base_branch, "main");
Ok(())
}
#[tokio::test]
async fn test_config_load_nonexistent_creates_default() -> Result<()> {
let temp_dir = TempDir::new().unwrap();
let config_path = temp_dir.path().join("nonexistent_config.toml");
let config = Config::load(&config_path).await?;
assert_eq!(config.git.branch_prefix, "codetree");
assert!(config_path.exists());
Ok(())
}
#[tokio::test]
async fn test_config_validation() {
let mut config = Config::default();
assert!(config.validate().is_ok());
config.git.branch_prefix = "".to_string();
assert!(config.validate().is_err());
config.git.branch_prefix = "codetree".to_string();
config.git.base_branch = "".to_string();
assert!(config.validate().is_err());
}
#[test]
fn test_get_config_path() {
let custom_path = Path::new("/custom/config.toml");
let result = Config::get_config_path(Some(custom_path)).unwrap();
assert_eq!(result, custom_path);
let default_result = Config::get_config_path(None);
assert!(default_result.is_ok());
}
#[test]
fn test_get_data_dir() {
let data_dir = Config::get_data_dir().unwrap();
assert!(data_dir.ends_with(".codetree"));
}
#[tokio::test]
async fn test_is_initialized() {
let _temp_dir = TempDir::new().unwrap();
let result = Config::is_initialized().await;
assert!(result.is_ok());
}
#[tokio::test]
async fn test_config_default_fields() {
let config = Config::default();
assert!(!config.git.auto_push);
assert_eq!(config.git.remote_name, "origin");
}
#[tokio::test]
async fn test_config_validation_edge_cases() {
let mut config = Config::default();
config.git.branch_prefix = "".to_string();
config.git.base_branch = "".to_string();
assert!(config.validate().is_err());
config.git.branch_prefix = "codetree".to_string();
config.git.base_branch = "".to_string();
assert!(config.validate().is_err());
config.git.branch_prefix = "".to_string();
config.git.base_branch = "main".to_string();
assert!(config.validate().is_err());
}
#[tokio::test]
async fn test_config_save_overwrites_existing() -> Result<()> {
let temp_dir = TempDir::new().unwrap();
let config_path = temp_dir.path().join("overwrite_config.toml");
let mut config = Config::default();
config.git.branch_prefix = "first".to_string();
config.save(&config_path).await?;
let mut config2 = Config::default();
config2.git.branch_prefix = "second".to_string();
config2.save(&config_path).await?;
let loaded = Config::load(&config_path).await?;
assert_eq!(loaded.git.branch_prefix, "second");
Ok(())
}
#[tokio::test]
async fn test_config_default_templates() {
let config = Config::default();
assert!(config.get_template("refactor").is_some());
assert!(config.get_template("bugfix").is_some());
assert!(config.get_template("feature").is_some());
assert!(config.get_template("unknown").is_none());
let refactor = config.get_template("refactor").unwrap();
assert_eq!(refactor.branch_prefix.as_deref(), Some("refactor"));
assert_eq!(refactor.commit_message_format, "Refactor: {description}");
let bugfix = config.get_template("bugfix").unwrap();
assert_eq!(bugfix.branch_prefix.as_deref(), Some("fix"));
assert_eq!(bugfix.commit_message_format, "Fix: {description}");
}
#[tokio::test]
async fn test_config_template_save_and_load() -> Result<()> {
let temp_dir = TempDir::new().unwrap();
let config_path = temp_dir.path().join("template_config.toml");
let mut config = Config::default();
config.templates.insert("custom".to_string(), TemplateConfig {
branch_prefix: Some("custom".to_string()),
commit_message_format: "Custom: {description}".to_string(),
});
config.save(&config_path).await?;
let loaded = Config::load(&config_path).await?;
let custom = loaded.get_template("custom").unwrap();
assert_eq!(custom.branch_prefix.as_deref(), Some("custom"));
assert_eq!(custom.commit_message_format, "Custom: {description}");
Ok(())
}
#[tokio::test]
async fn test_validation_config_default() {
let config = Config::default();
assert!(config.validation.is_off());
assert!(!config.validation.is_required());
assert!(config.validation.command.is_none());
}
#[tokio::test]
async fn test_validation_config_save_and_load() -> Result<()> {
let temp_dir = TempDir::new().unwrap();
let config_path = temp_dir.path().join("validation_config.toml");
let mut config = Config::default();
config.validation.mode = "required".to_string();
config.validation.command = Some("cargo test".to_string());
config.save(&config_path).await?;
let loaded = Config::load(&config_path).await?;
assert!(loaded.validation.is_required());
assert_eq!(loaded.validation.command.as_deref(), Some("cargo test"));
Ok(())
}
}