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
use anyhow::{Context, Result};
use std::fs;
use crate::config::config::get_config_storage_path;
use crate::config::types::{ConfigStorage, Configuration};
impl ConfigStorage {
/// Load configurations from disk
///
/// Reads the JSON file from `~/.claude/cc_auto_switch_setting.json`
/// Auto-migrates from old location `~/.cc-switch/configurations.json` if it exists
/// Returns default empty storage if file doesn't exist
///
/// # Errors
/// Returns error if file exists but cannot be read or parsed
pub fn load() -> Result<Self> {
let new_path = get_config_storage_path()?;
// Check if the new file already exists
if new_path.exists() {
let content = fs::read_to_string(&new_path).with_context(|| {
format!(
"Failed to read configuration storage from {}",
new_path.display()
)
})?;
let storage: ConfigStorage = serde_json::from_str(&content)
.with_context(|| "Failed to parse configuration storage JSON")?;
return Ok(storage);
}
// No configuration file exists at new path, return default empty storage
Ok(ConfigStorage::default())
}
/// Save configurations to disk
///
/// Writes the current state to `~/.claude/cc_auto_switch_setting.json`
/// Creates the directory structure if it doesn't exist
///
/// # Errors
/// Returns error if directory cannot be created or file cannot be written
pub fn save(&self) -> Result<()> {
let path = get_config_storage_path()?;
// Create directory if it doesn't exist
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)
.with_context(|| format!("Failed to create directory {}", parent.display()))?;
}
let json = serde_json::to_string_pretty(self)
.with_context(|| "Failed to serialize configuration storage")?;
fs::write(&path, json).with_context(|| format!("Failed to write to {}", path.display()))?;
Ok(())
}
/// Migrate configurations from old path to new path
///
/// Old path: `~/.cc_auto_switch/configurations.json`
/// New path: `~/.claude/cc_auto_switch_setting.json`
///
/// Safe to run multiple times. If old path does not exist, returns Ok(()) and prints a note.
pub fn migrate_from_old_path() -> Result<()> {
let new_path = get_config_storage_path()?;
let old_path = dirs::home_dir()
.map(|home| home.join(".cc_auto_switch").join("configurations.json"))
.ok_or_else(|| anyhow::anyhow!("Could not find home directory"))?;
if !old_path.exists() {
println!("âšī¸ No old configuration found at {}", old_path.display());
return Ok(());
}
println!("đ Migrating configuration from old location...");
let content = fs::read_to_string(&old_path).with_context(|| {
format!(
"Failed to read old configuration from {}",
old_path.display()
)
})?;
let storage: ConfigStorage = serde_json::from_str(&content)
.with_context(|| "Failed to parse old configuration storage JSON")?;
// Save to new location
storage
.save()
.with_context(|| "Failed to save migrated configuration to new location")?;
// Remove old directory
if let Some(parent) = old_path.parent() {
fs::remove_dir_all(parent).with_context(|| {
format!(
"Failed to remove old configuration directory {}",
parent.display()
)
})?;
}
println!(
"â
Configuration migrated successfully to {}",
new_path.display()
);
Ok(())
}
/// Add a new configuration to storage
///
/// # Arguments
/// * `config` - Configuration object to add
///
/// Overwrites existing configuration with same alias
pub fn add_configuration(&mut self, config: Configuration) {
self.configurations
.insert(config.alias_name.clone(), config);
}
/// Remove a configuration by alias name
///
/// # Arguments
/// * `alias_name` - Name of configuration to remove
///
/// # Returns
/// `true` if configuration was found and removed, `false` if not found
pub fn remove_configuration(&mut self, alias_name: &str) -> bool {
self.configurations.remove(alias_name).is_some()
}
/// Get a configuration by alias name
///
/// # Arguments
/// * `alias_name` - Name of configuration to retrieve
///
/// # Returns
/// `Some(&Configuration)` if found, `None` if not found
pub fn get_configuration(&self, alias_name: &str) -> Option<&Configuration> {
self.configurations.get(alias_name)
}
/// Set the default directory for Claude settings
///
/// # Arguments
/// * `directory` - Directory path for Claude settings
#[allow(dead_code)]
pub fn set_claude_settings_dir(&mut self, directory: String) {
self.claude_settings_dir = Some(directory);
}
/// Get the current Claude settings directory
///
/// # Returns
/// `Some(&String)` if custom directory is set, `None` if using default
#[allow(dead_code)]
pub fn get_claude_settings_dir(&self) -> Option<&String> {
self.claude_settings_dir.as_ref()
}
/// Update an existing configuration
///
/// This method handles updating a configuration, including potential alias renaming.
/// If the new configuration has a different alias name than the old one, it removes
/// the old entry and creates a new one.
///
/// # Arguments
/// * `old_alias` - Current alias name of the configuration to update
/// * `new_config` - Updated configuration object
///
/// # Returns
/// `Ok(())` if update succeeds, `Err` if the old configuration doesn't exist
///
/// # Errors
/// Returns error if the configuration with `old_alias` doesn't exist
pub fn update_configuration(
&mut self,
old_alias: &str,
new_config: Configuration,
) -> Result<()> {
// Check if the old configuration exists
if !self.configurations.contains_key(old_alias) {
return Err(anyhow::anyhow!("Configuration '{}' not found", old_alias));
}
// If alias changed, remove the old entry
if old_alias != new_config.alias_name {
self.configurations.remove(old_alias);
}
// Insert the updated configuration (this will overwrite if alias hasn't changed)
self.configurations
.insert(new_config.alias_name.clone(), new_config);
Ok(())
}
}