use crate::error::{Error, Result};
use crate::template::paths::PathResolver;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RepositoryConfig {
pub version: String,
pub default_branch: String,
pub repositories: Vec<Repository>,
#[serde(default)]
pub system_repositories: Vec<Repository>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Repository {
pub name: String,
pub url: String,
pub branch: String,
pub local_path: PathBuf,
pub enabled: bool,
pub trusted: bool,
pub last_updated: Option<DateTime<Utc>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
}
impl RepositoryConfig {
pub fn load(path: &Path) -> Result<Self> {
if !path.exists() {
return Err(Error::config(format!(
"Repository config file not found: {}",
path.display()
)));
}
let content = std::fs::read_to_string(path)
.map_err(|e| Error::config(format!("Failed to read config: {}", e)))?;
serde_yaml::from_str(&content)
.map_err(|e| Error::config(format!("Failed to parse config: {}", e)))
}
pub fn save(&self, path: &Path) -> Result<()> {
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)
.map_err(|e| Error::config(format!("Failed to create config directory: {}", e)))?;
}
let content = serde_yaml::to_string(self)
.map_err(|e| Error::config(format!("Failed to serialize config: {}", e)))?;
std::fs::write(path, content)
.map_err(|e| Error::config(format!("Failed to write config: {}", e)))?;
Ok(())
}
pub fn default_config() -> Self {
Self {
version: "1.0".to_string(),
default_branch: "main".to_string(),
repositories: vec![Repository {
name: "official".to_string(),
url: "https://github.com/Bugb-Technologies/cert-x-gen-templates.git".to_string(),
branch: "main".to_string(),
local_path: PathResolver::user_template_dir().join("official"),
enabled: true,
trusted: true,
last_updated: None,
description: Some("Official CERT-X-GEN templates".to_string()),
}],
system_repositories: Vec::new(),
}
}
pub fn enabled_repositories(&self) -> Vec<&Repository> {
self.repositories.iter().filter(|r| r.enabled).collect()
}
pub fn get_repository(&self, name: &str) -> Option<&Repository> {
self.repositories.iter().find(|r| r.name == name)
}
pub fn get_repository_mut(&mut self, name: &str) -> Option<&mut Repository> {
self.repositories.iter_mut().find(|r| r.name == name)
}
pub fn add_repository(&mut self, repo: Repository) -> Result<()> {
if self.repositories.iter().any(|r| r.name == repo.name) {
return Err(Error::config(format!(
"Repository '{}' already exists",
repo.name
)));
}
self.repositories.push(repo);
Ok(())
}
pub fn remove_repository(&mut self, name: &str) -> Result<()> {
let initial_len = self.repositories.len();
self.repositories.retain(|r| r.name != name);
if self.repositories.len() == initial_len {
return Err(Error::config(format!("Repository '{}' not found", name)));
}
Ok(())
}
}
impl Default for RepositoryConfig {
fn default() -> Self {
Self::default_config()
}
}
impl Repository {
pub fn new(name: String, url: String, branch: String, local_path: PathBuf) -> Self {
Self {
name,
url,
branch,
local_path,
enabled: true,
trusted: false,
last_updated: None,
description: None,
}
}
pub fn needs_update(&self, max_age_hours: i64) -> bool {
match self.last_updated {
None => true, Some(last) => {
let now = Utc::now();
let age = now.signed_duration_since(last);
age.num_hours() >= max_age_hours
}
}
}
pub fn mark_updated(&mut self) {
self.last_updated = Some(Utc::now());
}
}
#[cfg(test)]
mod tests {
use super::*;
use tempfile::TempDir;
#[test]
fn test_default_config() {
let config = RepositoryConfig::default_config();
assert_eq!(config.version, "1.0");
assert_eq!(config.default_branch, "main");
assert_eq!(config.repositories.len(), 1);
assert_eq!(config.repositories[0].name, "official");
}
#[test]
fn test_add_repository() {
let mut config = RepositoryConfig::default();
let repo = Repository::new(
"test".to_string(),
"https://github.com/test/repo.git".to_string(),
"main".to_string(),
PathBuf::from("/tmp/test"),
);
assert!(config.add_repository(repo).is_ok());
assert_eq!(config.repositories.len(), 2);
}
#[test]
fn test_duplicate_repository() {
let mut config = RepositoryConfig::default();
let repo = Repository::new(
"official".to_string(),
"https://github.com/test/repo.git".to_string(),
"main".to_string(),
PathBuf::from("/tmp/test"),
);
assert!(config.add_repository(repo).is_err());
}
#[test]
fn test_remove_repository() {
let mut config = RepositoryConfig::default();
assert!(config.remove_repository("official").is_ok());
assert_eq!(config.repositories.len(), 0);
}
#[test]
fn test_get_repository() {
let config = RepositoryConfig::default();
let repo = config.get_repository("official");
assert!(repo.is_some());
assert_eq!(repo.unwrap().name, "official");
}
#[test]
fn test_enabled_repositories() {
let mut config = RepositoryConfig::default();
config.repositories[0].enabled = false;
let enabled = config.enabled_repositories();
assert_eq!(enabled.len(), 0);
}
#[test]
fn test_save_and_load() {
let temp_dir = TempDir::new().unwrap();
let config_path = temp_dir.path().join("repositories.yaml");
let config = RepositoryConfig::default();
config.save(&config_path).unwrap();
let loaded = RepositoryConfig::load(&config_path).unwrap();
assert_eq!(loaded.version, config.version);
assert_eq!(loaded.repositories.len(), config.repositories.len());
}
#[test]
fn test_repository_needs_update() {
let mut repo = Repository::new(
"test".to_string(),
"https://example.com".to_string(),
"main".to_string(),
PathBuf::from("/tmp/test"),
);
assert!(repo.needs_update(24));
repo.mark_updated();
assert!(!repo.needs_update(24));
}
}