use std::collections::HashMap;
use std::fs;
use std::path::PathBuf;
#[derive(Debug, Clone)]
pub struct Config {
pub aliases: HashMap<String, Vec<String>>,
pub main_branch: String,
pub verbose: bool,
}
impl Default for Config {
fn default() -> Self {
Self {
aliases: HashMap::new(),
main_branch: "main".to_string(),
verbose: false,
}
}
}
pub fn load_config() -> Config {
let config_path = get_config_path();
if !config_path.exists() {
return Config::default();
}
let content = match fs::read_to_string(&config_path) {
Ok(c) => c,
Err(_) => return Config::default(),
};
let config: toml::Value = match content.parse() {
Ok(c) => c,
Err(_) => return Config::default(),
};
let mut result = Config::default();
if let Some(aliases) = config.get("aliases") {
if let Some(table) = aliases.as_table() {
for (key, value) in table {
if let Some(arr) = value.as_array() {
let cmd: Vec<String> = arr.iter()
.filter_map(|v| v.as_str().map(|s| s.to_string()))
.collect();
if !cmd.is_empty() {
result.aliases.insert(key.clone(), cmd);
}
}
}
}
}
if let Some(settings) = config.get("settings") {
if let Some(branch) = settings.get("main_branch") {
if let Some(s) = branch.as_str() {
result.main_branch = s.to_string();
}
}
if let Some(verbose) = settings.get("verbose") {
if let Some(v) = verbose.as_bool() {
result.verbose = v;
}
}
}
result
}
fn get_config_path() -> PathBuf {
let mut path = dirs::home_dir().unwrap_or_else(|| PathBuf::from("."));
path.push(".git-alias.toml");
path
}
pub fn create_default_config() -> Result<(), String> {
let config_path = get_config_path();
if config_path.exists() {
return Err("Config file already exists".to_string());
}
let default_config = r#"# Git-Short Configuration File
[aliases]
# Add your custom aliases here
# Example:
# my = ["status", "-s", "-b"]
# pushf = ["push", "--force-with-lease"]
[settings]
# Default branch name
main_branch = "main"
# Verbose mode (show executed command)
verbose = false
"#;
fs::write(&config_path, default_config)
.map_err(|e| format!("Failed to create config file: {}", e))?;
println!("Created config file at: {}", config_path.display());
Ok(())
}