|
| 1 | +namespace ClawSharp.Infrastructure.Config; |
| 2 | + |
| 3 | +using ClawSharp.Core.Config; |
| 4 | +using Tomlyn; |
| 5 | +using Tomlyn.Model; |
| 6 | + |
| 7 | +/// <summary>Loads ClawSharp configuration from TOML files with environment variable overrides.</summary> |
| 8 | +public static class TomlConfigLoader |
| 9 | +{ |
| 10 | + /// <summary> |
| 11 | + /// Loads configuration from the specified path, CLAWSHARP_CONFIG_PATH env var, or the default location. |
| 12 | + /// Missing files return default config. Environment variables always take precedence. |
| 13 | + /// </summary> |
| 14 | + public static ClawSharpConfig Load(string? configPath = null) |
| 15 | + { |
| 16 | + configPath ??= Environment.GetEnvironmentVariable("CLAWSHARP_CONFIG_PATH") |
| 17 | + ?? Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".clawsharp", "config.toml"); |
| 18 | + |
| 19 | + ClawSharpConfig config; |
| 20 | + |
| 21 | + if (!File.Exists(configPath)) |
| 22 | + { |
| 23 | + config = new ClawSharpConfig(); |
| 24 | + } |
| 25 | + else |
| 26 | + { |
| 27 | + var toml = File.ReadAllText(configPath); |
| 28 | + try |
| 29 | + { |
| 30 | + config = Toml.ToModel<ClawSharpConfig>(toml, |
| 31 | + options: new TomlModelOptions |
| 32 | + { |
| 33 | + ConvertPropertyName = name => ToSnakeCase(name), |
| 34 | + }); |
| 35 | + } |
| 36 | + catch (TomlException ex) |
| 37 | + { |
| 38 | + throw new InvalidOperationException( |
| 39 | + $"Failed to parse config file '{configPath}': {ex.Message}", ex); |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + return ApplyEnvironmentOverrides(config); |
| 44 | + } |
| 45 | + |
| 46 | + private static ClawSharpConfig ApplyEnvironmentOverrides(ClawSharpConfig config) |
| 47 | + { |
| 48 | + if (Environment.GetEnvironmentVariable("CLAWSHARP_DEFAULT_PROVIDER") is { } provider) |
| 49 | + config.DefaultProvider = provider; |
| 50 | + if (Environment.GetEnvironmentVariable("CLAWSHARP_DEFAULT_MODEL") is { } model) |
| 51 | + config.DefaultModel = model; |
| 52 | + if (Environment.GetEnvironmentVariable("OPENAI_API_KEY") is { } oaiKey) |
| 53 | + (config.Providers.Openai ??= new ProviderEntry()).ApiKey = oaiKey; |
| 54 | + if (Environment.GetEnvironmentVariable("ANTHROPIC_API_KEY") is { } antKey) |
| 55 | + (config.Providers.Anthropic ??= new ProviderEntry()).ApiKey = antKey; |
| 56 | + |
| 57 | + return config; |
| 58 | + } |
| 59 | + |
| 60 | + private static string ToSnakeCase(string name) |
| 61 | + { |
| 62 | + var result = new System.Text.StringBuilder(); |
| 63 | + for (var i = 0; i < name.Length; i++) |
| 64 | + { |
| 65 | + var c = name[i]; |
| 66 | + if (char.IsUpper(c)) |
| 67 | + { |
| 68 | + if (i > 0) result.Append('_'); |
| 69 | + result.Append(char.ToLowerInvariant(c)); |
| 70 | + } |
| 71 | + else |
| 72 | + { |
| 73 | + result.Append(c); |
| 74 | + } |
| 75 | + } |
| 76 | + return result.ToString(); |
| 77 | + } |
| 78 | +} |
0 commit comments