ggen-config 26.7.2

Configuration parser and validator for ggen.toml files
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
//! Configuration file parser
//!
//! This module provides functionality for loading and parsing ggen.toml files.

use crate::config_lib::{ConfigError, GgenConfig, Result};
use std::path::{Path, PathBuf};

/// Configuration loader and parser
pub struct ConfigLoader {
    path: PathBuf,
}

impl ConfigLoader {
    /// Create a new config loader from a file path
    ///
    /// # Arguments
    ///
    /// * `path` - Path to the ggen.toml file
    ///
    /// # Errors
    ///
    /// Returns an error if the file doesn't exist or path validation fails
    pub fn new<P: AsRef<Path>>(path: P) -> Result<Self> {
        let path = path.as_ref().to_path_buf();

        if !path.exists() {
            return Err(ConfigError::FileNotFound(path));
        }
        Ok(Self { path })
    }

    /// Load and parse configuration from a file
    ///
    /// # Arguments
    ///
    /// * `path` - Path to the ggen.toml file
    ///
    /// # Errors
    ///
    /// Returns an error if the file cannot be read or parsed
    ///
    /// # Example
    ///
    /// ```no_run
    /// use ggen_config::config_lib::ConfigLoader;
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let config = ConfigLoader::from_file("ggen.toml")?;
    /// println!("Loaded project: {}", config.project.name);
    /// # Ok(())
    /// # }
    /// ```
    pub fn from_file<P: AsRef<Path>>(path: P) -> Result<GgenConfig> {
        let loader = Self::new(path)?;
        loader.load()
    }

    /// Load and parse configuration from a string
    ///
    /// # Arguments
    ///
    /// * `content` - TOML content as a string
    ///
    /// # Errors
    ///
    /// Returns an error if the TOML cannot be parsed
    ///
    /// # Example
    ///
    /// ```
    /// use ggen_config::config_lib::ConfigLoader;
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let toml = r#"
    ///     [project]
    ///     name = "my-project"
    ///     version = "1.0.0"
    /// "#;
    ///
    /// let config = ConfigLoader::from_str(toml)?;
    /// assert_eq!(config.project.name, "my-project");
    /// # Ok(())
    /// # }
    /// ```
    pub fn from_str(content: &str) -> Result<GgenConfig> {
        let config: GgenConfig = star_toml::from_str::<GgenConfig>(content)?;
        Ok(config)
    }

    /// Load configuration from the stored file path
    ///
    /// # Errors
    ///
    /// Returns an error if the file cannot be read or parsed
    pub fn load(&self) -> Result<GgenConfig> {
        let config = star_toml::load_file::<GgenConfig>(&self.path)?;
        Ok(config)
    }

    /// Find and load ggen.toml from current or parent directories
    ///
    /// Searches upward through the directory tree until finding ggen.toml
    /// or reaching the filesystem root.
    ///
    /// # Errors
    ///
    /// Returns an error if no ggen.toml is found or if it cannot be parsed
    ///
    /// # Example
    ///
    /// ```no_run
    /// use ggen_config::config_lib::ConfigLoader;
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// // Searches current directory and parents for ggen.toml
    /// let config = ConfigLoader::find_and_load()?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn find_and_load() -> Result<GgenConfig> {
        let path = Self::find_config_file()?;
        Self::from_file(path)
    }

    /// Find ggen.toml by searching current and parent directories
    ///
    /// # Errors
    ///
    /// Returns an error if no configuration file is found
    pub fn find_config_file() -> Result<PathBuf> {
        let current = std::env::current_dir().map_err(|e| {
            ConfigError::Validation(format!("Failed to get current directory: {e}"))
        })?;

        star_toml::find_config_file("ggen.toml", current).ok_or_else(|| {
            ConfigError::FileNotFound(PathBuf::from("ggen.toml (searched all parent directories)"))
        })
    }

    /// Load configuration with environment-specific overrides
    ///
    /// # Arguments
    ///
    /// * `environment` - Environment name (e.g., "development", "production")
    ///
    /// # Errors
    ///
    /// Returns an error if the file cannot be read or parsed
    pub fn load_with_env(&self, environment: &str) -> Result<GgenConfig> {
        let mut config = self.load()?;

        // Apply environment-specific overrides if present
        if let Some(env_overrides) = config.env.clone() {
            if let Some(overrides) = env_overrides.get(environment) {
                apply_env_overrides(&mut config, overrides);
            }
        }

        Ok(config)
    }

    /// Load configuration with environment-specific overrides from a map
    ///
    /// # Arguments
    ///
    /// * `overrides` - Slice of (`environment_name`, overrides) tuples
    ///
    /// # Errors
    ///
    /// Returns an error if the config cannot be loaded
    ///
    /// # Example
    ///
    /// ```no_run
    /// use ggen_config::config_lib::ConfigLoader;
    /// use serde_json::json;
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let loader = ConfigLoader::new("ggen.toml")?;
    /// let config = loader.load_with_env_from_map(&[("zai", json!({"ai.provider": "zai"}))])?;
    /// assert_eq!(config.ai.map(|a| a.provider), Some("zai".to_string()));
    /// # Ok(())
    /// # }
    /// ```
    pub fn load_with_env_from_map(
        self, overrides: &[(&str, serde_json::Value)],
    ) -> Result<GgenConfig> {
        let mut config = self.load()?;

        for (_env_name, env_overrides) in overrides {
            if let Some(obj) = env_overrides.as_object() {
                for (key, value) in obj {
                    apply_single_override(&mut config, key, value);
                }
            }
        }

        Ok(config)
    }

    /// Get the config file path
    #[must_use]
    pub fn path(&self) -> &Path {
        self.path.as_path()
    }
}

/// Apply environment-specific overrides to configuration
///
/// Uses JSON pointer notation to update nested fields
fn apply_env_overrides(config: &mut GgenConfig, overrides: &serde_json::Value) {
    if let Some(obj) = overrides.as_object() {
        for (key, value) in obj {
            // Simple key-based override (supports one level of nesting)
            apply_single_override(config, key, value);
        }
    }
}

/// Apply a single configuration override
fn apply_single_override(config: &mut GgenConfig, key: &str, value: &serde_json::Value) {
    // Parse dotted key notation (e.g., "ai.temperature", "mcp.enabled")
    let parts: Vec<&str> = key.split('.').collect();

    match parts.as_slice() {
        ["ai", field] => {
            if let Some(ai_config) = config.ai.as_mut() {
                update_ai_field(ai_config, field, value);
            }
        }
        ["logging", "level"] => {
            if let Some(logging) = config.logging.as_mut() {
                if let Some(s) = value.as_str() {
                    logging.level = s.to_string();
                }
            }
        }
        ["logging", field] => {
            if let Some(logging) = config.logging.as_mut() {
                update_logging_field(logging, field, value);
            }
        }
        ["security", field] => {
            if let Some(security) = config.security.as_mut() {
                update_security_field(security, field, value);
            }
        }
        ["performance", field] => {
            if let Some(performance) = config.performance.as_mut() {
                update_performance_field(performance, field, value);
            }
        }
        ["mcp", field] => {
            if config.mcp.is_none() {
                config.mcp = Some(crate::config_lib::schema::McpConfig {
                    name: None,
                    version: None,
                    tool_timeout_ms: default_mcp_tool_timeout(),
                    max_concurrent_requests: default_mcp_max_concurrent(),
                    transport: None,
                    tools: None,
                    zai: None,
                    enabled: default_mcp_enabled(),
                    discovery: None,
                });
            }
            if let Some(mcp) = config.mcp.as_mut() {
                update_mcp_field(mcp, field, value);
            }
        }
        ["a2a", field] => {
            if config.a2a.is_none() {
                config.a2a = Some(crate::config_lib::schema::A2AConfig {
                    agent_id: None,
                    agent_name: None,
                    agent_type: None,
                    transport: None,
                    messaging: None,
                    orchestration: None,
                    capabilities: None,
                    enabled: default_a2a_enabled(),
                });
            }
            if let Some(a2a) = config.a2a.as_mut() {
                update_a2a_field(a2a, field, value);
            }
        }
        _ => {
            // Unsupported override path - log or ignore
        }
    }
}

/// Update AI configuration field
fn update_ai_field(
    ai: &mut crate::config_lib::schema::AiConfig, field: &str, value: &serde_json::Value,
) {
    match field {
        "model" => {
            if let Some(s) = value.as_str() {
                ai.model = s.to_string();
            }
        }
        "temperature" => {
            if let Some(f) = value.as_f64() {
                ai.temperature = f as f32;
            }
        }
        "max_tokens" => {
            if let Some(n) = value.as_u64() {
                ai.max_tokens = n as u32;
            }
        }
        _ => {}
    }
}

/// Update security configuration field
fn update_security_field(
    security: &mut crate::config_lib::schema::SecurityConfig, field: &str,
    value: &serde_json::Value,
) {
    match field {
        "require_confirmation" => {
            if let Some(b) = value.as_bool() {
                security.require_confirmation = b;
            }
        }
        "audit_operations" => {
            if let Some(b) = value.as_bool() {
                security.audit_operations = b;
            }
        }
        _ => {}
    }
}

/// Update logging configuration field
fn update_logging_field(
    logging: &mut crate::config_lib::schema::LoggingConfig, field: &str, value: &serde_json::Value,
) {
    match field {
        "format" => {
            if let Some(s) = value.as_str() {
                logging.format = s.to_string();
            }
        }
        "file" => {
            if let Some(s) = value.as_str() {
                logging.file = Some(s.to_string());
            }
        }
        "rotation" => {
            if let Some(s) = value.as_str() {
                logging.rotation = Some(s.to_string());
            }
        }
        _ => {}
    }
}

/// Update performance configuration field
fn update_performance_field(
    performance: &mut crate::config_lib::schema::PerformanceConfig, field: &str,
    value: &serde_json::Value,
) {
    match field {
        "max_workers" => {
            if let Some(n) = value.as_u64() {
                performance.max_workers = n as u32;
            }
        }
        "cache_size" => {
            if let Some(s) = value.as_str() {
                performance.cache_size = Some(s.to_string());
            }
        }
        "memory_limit_mb" => {
            if let Some(n) = value.as_u64() {
                performance.memory_limit_mb = Some(n as u32);
            }
        }
        "parallel_execution" => {
            if let Some(b) = value.as_bool() {
                performance.parallel_execution = b;
            }
        }
        _ => {}
    }
}

/// Update MCP configuration field
fn update_mcp_field(
    mcp: &mut crate::config_lib::schema::McpConfig, field: &str, value: &serde_json::Value,
) {
    match field {
        "enabled" => {
            if let Some(b) = value.as_bool() {
                mcp.enabled = b;
            }
        }
        "name" => {
            if let Some(s) = value.as_str() {
                mcp.name = Some(s.to_string());
            }
        }
        "version" => {
            if let Some(s) = value.as_str() {
                mcp.version = Some(s.to_string());
            }
        }
        "tool_timeout_ms" => {
            if let Some(n) = value.as_u64() {
                mcp.tool_timeout_ms = n;
            }
        }
        "max_concurrent_requests" => {
            if let Some(n) = value.as_u64() {
                mcp.max_concurrent_requests = n as usize;
            }
        }
        _ => {}
    }
}

/// Update A2A configuration field
fn update_a2a_field(
    a2a: &mut crate::config_lib::schema::A2AConfig, field: &str, value: &serde_json::Value,
) {
    match field {
        "enabled" => {
            if let Some(b) = value.as_bool() {
                a2a.enabled = b;
            }
        }
        "agent_id" => {
            if let Some(s) = value.as_str() {
                a2a.agent_id = Some(s.to_string());
            }
        }
        "agent_name" => {
            if let Some(s) = value.as_str() {
                a2a.agent_name = Some(s.to_string());
            }
        }
        "agent_type" => {
            if let Some(s) = value.as_str() {
                a2a.agent_type = Some(s.to_string());
            }
        }
        _ => {}
    }
}

// Default value functions (re-export from schema for parser use)
const fn default_mcp_tool_timeout() -> u64 {
    30000
}

const fn default_mcp_max_concurrent() -> usize {
    100
}

fn default_mcp_enabled() -> bool {
    false
}

fn default_a2a_enabled() -> bool {
    false
}

#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_minimal_config() {
        let toml = r#"
            [project]
            name = "test-project"
            version = "1.0.0"
        "#;

        let config = ConfigLoader::from_str(toml).unwrap();
        assert_eq!(config.project.name, "test-project");
        assert_eq!(config.project.version, "1.0.0");
        assert!(config.ai.is_none());
    }

    #[test]
    fn test_parse_full_config() {
        let toml = r#"
            [project]
            name = "full-project"
            version = "2.0.0"
            description = "A test project"

            [ai]
            provider = "openai"
            model = "gpt-4"
            temperature = 0.8
            max_tokens = 3000

            [templates]
            directory = "templates"
            backup_enabled = true
        "#;

        let config = ConfigLoader::from_str(toml).unwrap();
        assert_eq!(config.project.name, "full-project");

        let ai = config.ai.as_ref().unwrap();
        assert_eq!(ai.provider, "openai");
        assert_eq!(ai.model, "gpt-4");
        assert!((ai.temperature - 0.8).abs() < f32::EPSILON);

        let templates = config.templates.as_ref().unwrap();
        assert_eq!(templates.directory.as_ref().unwrap(), "templates");
        assert!(templates.backup_enabled);
    }

    #[test]
    fn test_default_values() {
        let toml = r#"
            [project]
            name = "defaults"
            version = "1.0.0"

            [ai]
            provider = "ollama"
            model = "llama2"
        "#;

        let config = ConfigLoader::from_str(toml).unwrap();
        let ai = config.ai.as_ref().unwrap();

        // Check default values
        assert!((ai.temperature - 0.7).abs() < f32::EPSILON);
        assert_eq!(ai.max_tokens, 2000);
        assert_eq!(ai.timeout, 30);
    }
}