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
12fn 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 if let Some(env) = env_var
21 && let Ok(val) = std::env::var(env)
22 {
23 return Some(val);
24 }
25
26 if let Some(local) = local_config
28 && let Ok(val) = local.get_string(key)
29 {
30 return Some(val.clone());
31 }
32
33 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#[derive(Deserialize, Serialize, Clone, Debug)]
45pub struct Config {
46 pub default_provider: String,
48 pub providers: HashMap<String, ProviderConfig>,
50 #[serde(default)]
52 pub instructions: String,
53 #[serde(skip)]
54 pub temp_instructions: Option<String>,
55 #[serde(skip)]
57 pub is_local: bool,
58}
59
60#[derive(Deserialize, Serialize, Clone, Debug, Default)]
62pub struct ProviderConfig {
63 pub api_key: String,
65 pub model_name: String,
67 #[serde(default)]
69 pub additional_params: HashMap<String, String>,
70 pub token_limit: Option<usize>,
72}
73
74impl Config {
75 pub fn load() -> Result<Self> {
77 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()); 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, 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(); 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 pub fn merge_with_project_config(&mut self, project_config: Self) {
162 debug!("Merging with project configuration");
163
164 if project_config.default_provider != Self::default().default_provider {
166 self.default_provider
167 .clone_from(&project_config.default_provider);
168 }
169
170 for (provider, proj_provider_config) in project_config.providers {
172 let entry = self.providers.entry(provider).or_default();
173
174 if !proj_provider_config.model_name.is_empty() {
176 entry
177 .model_name
178 .clone_from(&proj_provider_config.model_name);
179 }
180
181 entry
183 .additional_params
184 .extend(proj_provider_config.additional_params);
185
186 if proj_provider_config.token_limit.is_some() {
188 entry.token_limit = proj_provider_config.token_limit;
189 }
190 }
191
192 self.instructions.clone_from(&project_config.instructions);
194 }
195
196 pub fn save(&self) -> Result<()> {
198 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 fn save_to_config(&self, config: &mut GitConfig, prefix: &str) -> Result<()> {
211 config.set_str(&format!("{prefix}.defaultprovider"), &self.default_provider)?;
213
214 config.set_str(&format!("{prefix}.instructions"), &self.instructions)?;
216
217 for (provider, provider_config) in &self.providers {
218 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 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 pub fn save_as_project_config(&self) -> Result<()> {
249 let repo = git2::Repository::discover(".")?;
250
251 let mut project_config = self.clone();
253
254 for provider_config in project_config.providers.values_mut() {
256 provider_config.api_key.clear();
257 }
258
259 project_config.is_local = true;
261
262 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 pub fn check_environment(&self) -> Result<()> {
271 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 #[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 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 #[must_use]
347 pub fn get_provider_config(&self, provider: &str) -> Option<&ProviderConfig> {
348 let provider_to_lookup = if provider.eq_ignore_ascii_case("claude") {
350 "anthropic"
351 } else {
352 provider
353 };
354
355 self.providers.get(provider_to_lookup).or_else(|| {
357 let lowercase_provider = provider_to_lookup.to_lowercase();
359
360 self.providers.get(&lowercase_provider).or_else(|| {
361 if get_available_provider_names().contains(&lowercase_provider) {
363 None
366 } else {
367 None
369 }
370 })
371 })
372 }
373
374 #[inline]
376 pub fn set_project_config(&mut self, is_project: bool) {
377 self.is_local = is_project;
378 }
379
380 #[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 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 #[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, }
425 }
426
427 #[inline]
429 #[must_use]
430 pub const fn get_token_limit(&self) -> Option<usize> {
431 self.token_limit
432 }
433}