gitai/
config.rs

1use crate::core::llm::{
2    get_available_provider_names, get_default_model_for_provider, provider_requires_api_key,
3};
4use crate::git::GitRepo;
5
6use anyhow::{Context, Result, anyhow};
7use git2::Config as GitConfig;
8use log::debug;
9use serde::{Deserialize, Serialize};
10use std::collections::HashMap;
11
12/// Get a configuration value with layered priority: env var > local git config > global git config
13fn get_layered_value(
14    key: &str,
15    env_var: Option<&str>,
16    local_config: Option<&GitConfig>,
17    global_config: Option<&GitConfig>,
18) -> Option<String> {
19    // First, check environment variable
20    if let Some(env) = env_var
21        && let Ok(val) = std::env::var(env)
22    {
23        return Some(val);
24    }
25
26    // Then, check local git config
27    if let Some(local) = local_config
28        && let Ok(val) = local.get_string(key)
29    {
30        return Some(val.clone());
31    }
32
33    // Finally, check global git config
34    if let Some(global) = global_config
35        && let Ok(val) = global.get_string(key)
36    {
37        return Some(val.clone());
38    }
39
40    None
41}
42
43/// Configuration structure
44#[derive(Deserialize, Serialize, Clone, Debug)]
45pub struct Config {
46    /// Default LLM provider
47    pub default_provider: String,
48    /// Provider-specific configurations
49    pub providers: HashMap<String, ProviderConfig>,
50    /// Instructions for commit messages
51    #[serde(default)]
52    pub instructions: String,
53    #[serde(skip)]
54    pub temp_instructions: Option<String>,
55    /// Flag indicating if this config is local
56    #[serde(skip)]
57    pub is_local: bool,
58}
59
60/// Provider-specific configuration structure
61#[derive(Deserialize, Serialize, Clone, Debug, Default)]
62pub struct ProviderConfig {
63    /// API key for the provider
64    pub api_key: String,
65    /// Model to be used with the provider
66    pub model_name: String,
67    /// Additional parameters for the provider
68    #[serde(default)]
69    pub additional_params: HashMap<String, String>,
70    /// Token limit, if set by the user
71    pub token_limit: Option<usize>,
72}
73
74impl Config {
75    /// Load the configuration with layered priority: env > local git > global git
76    pub fn load() -> Result<Self> {
77        // Open git configs
78        let global_config = GitConfig::open_default().ok();
79        let local_config = git2::Repository::discover(".")
80            .ok()
81            .and_then(|repo| repo.config().ok());
82
83        let default_provider = get_layered_value(
84            "gitai.defaultprovider",
85            Some("GITAI_DEFAULT_PROVIDER"),
86            local_config.as_ref(),
87            global_config.as_ref(),
88        )
89        .unwrap_or_else(|| "openai".to_string()); // fallback to openai if not set
90
91        let instructions = get_layered_value(
92            "gitai.instructions",
93            Some("GITAI_INSTRUCTIONS"),
94            local_config.as_ref(),
95            global_config.as_ref(),
96        )
97        .unwrap_or_default();
98
99        let mut providers = HashMap::new();
100        for provider in get_available_provider_names() {
101            let api_key_env = match provider.as_str() {
102                "openai" => Some("OPENAI_API_KEY"),
103                "anthropic" => Some("ANTHROPIC_API_KEY"),
104                "google" => Some("GOOGLE_API_KEY"),
105                _ => None,
106            };
107
108            if let Some(api_key) = get_layered_value(
109                &format!("gitai.{provider}-apikey"),
110                api_key_env,
111                local_config.as_ref(),
112                global_config.as_ref(),
113            ) {
114                let default_model = get_default_model_for_provider(&provider).to_string();
115                let model = get_layered_value(
116                    &format!("gitai.{provider}-model"),
117                    None, // no env for model yet
118                    local_config.as_ref(),
119                    global_config.as_ref(),
120                )
121                .unwrap_or(default_model);
122
123                let token_limit = get_layered_value(
124                    &format!("gitai.{provider}-tokenlimit"),
125                    None,
126                    local_config.as_ref(),
127                    global_config.as_ref(),
128                )
129                .and_then(|s| s.parse::<i64>().ok())
130                .and_then(|v| usize::try_from(v).ok());
131
132                let additional_params = HashMap::new(); // TODO: handle additional params if needed
133
134                providers.insert(
135                    #[allow(clippy::implicit_clone)]
136                    provider.to_owned(),
137                    ProviderConfig {
138                        api_key,
139                        model_name: model,
140                        additional_params,
141                        token_limit,
142                    },
143                );
144            }
145        }
146
147        let config = Self {
148            default_provider,
149            providers,
150            instructions,
151            temp_instructions: None,
152            is_local: false,
153        };
154
155        debug!("Configuration loaded: {config:?}");
156        Ok(config)
157    }
158
159    /// Merge this config with project-specific config, with project config taking precedence
160    /// But never allow API keys from project config
161    pub fn merge_with_project_config(&mut self, project_config: Self) {
162        debug!("Merging with project configuration");
163
164        // Override default provider if set in project config
165        if project_config.default_provider != Self::default().default_provider {
166            self.default_provider
167                .clone_from(&project_config.default_provider);
168        }
169
170        // Merge provider configs, but never allow API keys from project config
171        for (provider, proj_provider_config) in project_config.providers {
172            let entry = self.providers.entry(provider).or_default();
173
174            // Don't override API keys from project config (security)
175            if !proj_provider_config.model_name.is_empty() {
176                entry
177                    .model_name
178                    .clone_from(&proj_provider_config.model_name);
179            }
180
181            // Merge additional params
182            entry
183                .additional_params
184                .extend(proj_provider_config.additional_params);
185
186            // Override token limit if set in project config
187            if proj_provider_config.token_limit.is_some() {
188                entry.token_limit = proj_provider_config.token_limit;
189            }
190        }
191
192        // Always override instructions field if set in project config
193        self.instructions.clone_from(&project_config.instructions);
194    }
195
196    /// Save the configuration to git config
197    pub fn save(&self) -> Result<()> {
198        // Don't save project configs to personal config file
199        if self.is_local {
200            return Ok(());
201        }
202
203        let mut config = GitConfig::open_default()?;
204        self.save_to_config(&mut config, "gitai")?;
205        debug!("Configuration saved to global git config: {self:?}");
206        Ok(())
207    }
208
209    /// Save the configuration to a git config
210    fn save_to_config(&self, config: &mut GitConfig, prefix: &str) -> Result<()> {
211        // Set default provider
212        config.set_str(&format!("{prefix}.defaultprovider"), &self.default_provider)?;
213
214        // Set instructions
215        config.set_str(&format!("{prefix}.instructions"), &self.instructions)?;
216
217        for (provider, provider_config) in &self.providers {
218            // Set api key only if not empty
219            if !provider_config.api_key.is_empty() {
220                config.set_str(
221                    &format!("{prefix}.{provider}-apikey"),
222                    &provider_config.api_key,
223                )?;
224            }
225
226            // Set model
227            config.set_str(
228                &format!("{prefix}.{provider}-model"),
229                &provider_config.model_name,
230            )?;
231
232            if let Some(token_limit) = provider_config.token_limit {
233                config.set_i64(
234                    &format!("{prefix}.{provider}-tokenlimit"),
235                    i64::try_from(token_limit).context("Token limit exceeds i64 range")?,
236                )?;
237            }
238
239            for (key, value) in &provider_config.additional_params {
240                config.set_str(&format!("{prefix}.{provider}-additional{key}"), value)?;
241            }
242        }
243
244        Ok(())
245    }
246
247    /// Save the configuration as a project-specific configuration
248    pub fn save_as_project_config(&self) -> Result<()> {
249        let repo = git2::Repository::discover(".")?;
250
251        // Before saving, create a copy that excludes API keys
252        let mut project_config = self.clone();
253
254        // Remove API keys from all providers
255        for provider_config in project_config.providers.values_mut() {
256            provider_config.api_key.clear();
257        }
258
259        // Mark as project config
260        project_config.is_local = true;
261
262        // Save to local git config
263        let mut config = repo.config()?;
264        project_config.save_to_config(&mut config, "gitai")?;
265        debug!("Project configuration saved to local git config: {project_config:?}");
266        Ok(())
267    }
268
269    /// Check the environment for necessary prerequisites
270    pub fn check_environment(&self) -> Result<()> {
271        // Check if we're in a git repository
272        if !GitRepo::is_inside_work_tree()? {
273            return Err(anyhow!(
274                "Not in a Git repository. Please run this command from within a Git repository."
275            ));
276        }
277
278        Ok(())
279    }
280
281    #[inline]
282    pub fn set_temp_instructions(&mut self, instructions: Option<String>) {
283        self.temp_instructions = instructions;
284    }
285
286    #[must_use]
287    pub fn get_effective_instructions(&self) -> String {
288        self.temp_instructions
289            .as_ref()
290            .unwrap_or(&self.instructions)
291            .trim()
292            .to_string()
293    }
294
295    /// Update the configuration with new values
296    #[allow(clippy::too_many_arguments)]
297    pub fn update(
298        &mut self,
299        provider: Option<String>,
300        api_key: Option<String>,
301        model: Option<String>,
302        additional_params: Option<HashMap<String, String>>,
303        instructions: Option<String>,
304        token_limit: Option<usize>,
305    ) -> Result<()> {
306        if let Some(provider) = provider {
307            self.default_provider.clone_from(&provider);
308            if !self.providers.contains_key(&provider) {
309                // Only insert a new provider if it requires configuration
310                if provider_requires_api_key(&provider.to_lowercase()) {
311                    self.providers.insert(
312                        provider.clone(),
313                        ProviderConfig::default_for(&provider.to_lowercase()),
314                    );
315                }
316            }
317        }
318
319        let provider_config = self
320            .providers
321            .get_mut(&self.default_provider)
322            .context("Could not get default provider")?;
323
324        if let Some(key) = api_key {
325            provider_config.api_key = key;
326        }
327        if let Some(model) = model {
328            provider_config.model_name = model;
329        }
330        if let Some(params) = additional_params {
331            provider_config.additional_params.extend(params);
332        }
333
334        if let Some(instr) = instructions {
335            self.instructions = instr;
336        }
337        if let Some(limit) = token_limit {
338            provider_config.token_limit = Some(limit);
339        }
340
341        debug!("Configuration updated: {self:?}");
342        Ok(())
343    }
344
345    /// Get the configuration for a specific provider
346    #[must_use]
347    pub fn get_provider_config(&self, provider: &str) -> Option<&ProviderConfig> {
348        // Special case: redirect "claude" to "anthropic"
349        let provider_to_lookup = if provider.eq_ignore_ascii_case("claude") {
350            "anthropic"
351        } else {
352            provider
353        };
354
355        // First try direct lookup
356        self.providers.get(provider_to_lookup).or_else(|| {
357            // If not found, try lowercased version
358            let lowercase_provider = provider_to_lookup.to_lowercase();
359
360            self.providers.get(&lowercase_provider).or_else(|| {
361                // If the provider is not in the config, check if it's a valid provider
362                if get_available_provider_names().contains(&lowercase_provider) {
363                    // Return None for valid providers not in the config
364                    // This allows the code to use default values for providers like Ollama
365                    None
366                } else {
367                    // Return None for invalid providers
368                    None
369                }
370            })
371        })
372    }
373
374    /// Set whether this config is a project config
375    #[inline]
376    pub fn set_project_config(&mut self, is_project: bool) {
377        self.is_local = is_project;
378    }
379
380    /// Check if this is a project config
381    #[inline]
382    #[must_use]
383    pub const fn is_project_config(&self) -> bool {
384        self.is_local
385    }
386}
387
388impl Default for Config {
389    fn default() -> Self {
390        let providers: HashMap<String, ProviderConfig> = get_available_provider_names()
391            .into_iter()
392            .map(|provider| (provider.clone(), ProviderConfig::default_for(&provider)))
393            .collect();
394
395        // Default to OpenAI if available, otherwise use the first available provider
396        let default_provider = if providers.contains_key("openai") {
397            "openai".to_string()
398        } else {
399            providers
400                .keys()
401                .next()
402                .map_or_else(|| "openai".to_string(), std::string::ToString::to_string)
403        };
404
405        Self {
406            default_provider,
407            providers,
408            instructions: String::new(),
409            temp_instructions: None,
410            is_local: false,
411        }
412    }
413}
414
415impl ProviderConfig {
416    /// Create a default provider configuration for a given provider
417    #[must_use]
418    pub fn default_for(provider: &str) -> Self {
419        Self {
420            api_key: String::new(),
421            model_name: get_default_model_for_provider(provider).to_string(),
422            additional_params: HashMap::new(),
423            token_limit: None, // Will use the default from get_default_token_limit_for_provider
424        }
425    }
426
427    /// Get the token limit for this provider configuration
428    #[inline]
429    #[must_use]
430    pub const fn get_token_limit(&self) -> Option<usize> {
431        self.token_limit
432    }
433}