cc_switch/
claude_settings.rs1use anyhow::{Context, Result};
2use std::collections::BTreeMap;
3use std::fs;
4
5use crate::config::types::{ClaudeSettings, Configuration};
6use crate::utils::get_claude_settings_path;
7
8impl ClaudeSettings {
9 pub fn load(custom_dir: Option<&str>) -> Result<Self> {
21 let path = get_claude_settings_path(custom_dir)?;
22
23 if !path.exists() {
24 let default_settings = ClaudeSettings::default();
26 default_settings.save(custom_dir)?;
27 return Ok(default_settings);
28 }
29
30 let content = fs::read_to_string(&path)
31 .with_context(|| format!("Failed to read Claude settings from {}", path.display()))?;
32
33 let mut settings: ClaudeSettings = if content.trim().is_empty() {
35 ClaudeSettings::default()
36 } else {
37 serde_json::from_str(&content)
38 .with_context(|| "Failed to parse Claude settings JSON")?
39 };
40
41 if settings.env.is_empty() && !content.contains("\"env\"") {
43 settings.env = BTreeMap::new();
44 }
45
46 Ok(settings)
47 }
48
49 pub fn save(&self, custom_dir: Option<&str>) -> Result<()> {
61 let path = get_claude_settings_path(custom_dir)?;
62
63 if let Some(parent) = path.parent() {
65 fs::create_dir_all(parent)
66 .with_context(|| format!("Failed to create directory {}", parent.display()))?;
67 }
68
69 let settings_to_save = self;
71
72 let json = serde_json::to_string_pretty(&settings_to_save)
73 .with_context(|| "Failed to serialize Claude settings")?;
74
75 fs::write(&path, json).with_context(|| format!("Failed to write to {}", path.display()))?;
76
77 Ok(())
78 }
79
80 pub fn switch_to_config(&mut self, config: &Configuration) {
88 if self.env.is_empty() {
90 self.env = BTreeMap::new();
91 }
92
93 self.env.remove("ANTHROPIC_AUTH_TOKEN");
95 self.env.remove("ANTHROPIC_BASE_URL");
96 self.env.remove("ANTHROPIC_MODEL");
97 self.env.remove("ANTHROPIC_SMALL_FAST_MODEL");
98
99 self.env
101 .insert("ANTHROPIC_AUTH_TOKEN".to_string(), config.token.clone());
102 self.env
103 .insert("ANTHROPIC_BASE_URL".to_string(), config.url.clone());
104
105 if let Some(model) = &config.model
107 && !model.is_empty()
108 {
109 self.env
110 .insert("ANTHROPIC_MODEL".to_string(), model.clone());
111 }
112
113 if let Some(small_fast_model) = &config.small_fast_model
114 && !small_fast_model.is_empty()
115 {
116 self.env.insert(
117 "ANTHROPIC_SMALL_FAST_MODEL".to_string(),
118 small_fast_model.clone(),
119 );
120 }
121 }
122
123 pub fn remove_anthropic_env(&mut self) {
128 if self.env.is_empty() {
130 self.env = BTreeMap::new();
131 }
132
133 self.env.remove("ANTHROPIC_AUTH_TOKEN");
134 self.env.remove("ANTHROPIC_BASE_URL");
135 self.env.remove("ANTHROPIC_MODEL");
136 self.env.remove("ANTHROPIC_SMALL_FAST_MODEL");
137 }
138}