cc-switch-tui 0.2.1

All-in-One Assistant for Claude Code, Codex, Gemini, OpenCode, OpenClaw & Hermes
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
use clap::Subcommand;
use std::fs;
use std::path::{Path, PathBuf};

use crate::app_config::AppType;
use crate::cli::commands::config_common;
use crate::cli::commands::config_webdav;
use crate::cli::i18n::texts;
use crate::cli::ui::{error, highlight, info, success, to_json};
use crate::error::AppError;
use crate::services::ConfigService;
use crate::store::AppState;

#[derive(Subcommand)]
pub enum ConfigCommand {
    /// Show current configuration
    Show,
    /// Show configuration file path
    Path,
    /// Export configuration to file
    Export {
        /// Output file path
        file: PathBuf,
    },
    /// Import configuration from file
    Import {
        /// Input file path
        file: PathBuf,
    },
    /// Create a backup of current configuration
    Backup {
        /// Optional custom name for the backup
        #[arg(long)]
        name: Option<String>,
    },
    /// Restore from a backup
    Restore {
        /// Backup ID to restore (from list)
        #[arg(long, conflicts_with = "file")]
        backup: Option<String>,

        /// External file path to restore from
        #[arg(long, conflicts_with = "backup")]
        file: Option<PathBuf>,
    },
    /// Validate configuration file
    Validate,
    /// Reset to default configuration
    Reset,

    /// Manage common configuration snippet (per app)
    #[command(subcommand)]
    Common(config_common::CommonConfigCommand),

    /// Manage WebDAV sync settings and operations
    #[command(name = "webdav", subcommand)]
    WebDav(config_webdav::WebDavCommand),
}

pub fn execute(cmd: ConfigCommand, app: Option<AppType>) -> Result<(), AppError> {
    match cmd {
        ConfigCommand::Show => show_config(),
        ConfigCommand::Path => show_path(),
        ConfigCommand::Export { file } => export_config(&file),
        ConfigCommand::Import { file } => import_config(&file),
        ConfigCommand::Backup { name } => backup_config(name.as_deref()),
        ConfigCommand::Restore { backup, file } => {
            restore_config(backup.as_deref(), file.as_deref())
        }
        ConfigCommand::Validate => validate_config(),
        ConfigCommand::Reset => reset_config(),
        ConfigCommand::Common(cmd) => config_common::execute(cmd, app.unwrap_or(AppType::Claude)),
        ConfigCommand::WebDav(cmd) => config_webdav::execute(cmd),
    }
}

fn get_state() -> Result<AppState, AppError> {
    AppState::try_new()
}

fn show_config() -> Result<(), AppError> {
    let state = get_state()?;
    let config = state.config.read()?;

    println!("{}", highlight("Current Configuration"));
    println!("{}", "=".repeat(50));
    println!();

    // Display in pretty JSON format
    let json = to_json(&*config).map_err(|e| AppError::Message(e.to_string()))?;
    println!("{}", json);

    Ok(())
}

fn show_path() -> Result<(), AppError> {
    let config_dir = crate::config::get_app_config_dir();
    let db_path = config_dir.join("cc-switch.db");
    let legacy_config_path = config_dir.join("config.json");

    println!("{}", highlight("Configuration Paths"));
    println!("{}", "=".repeat(50));
    println!("DB file:      {}", db_path.display());
    println!("Legacy JSON:  {}", legacy_config_path.display());
    println!("Config dir:   {}", config_dir.display());

    // Check if DB file exists
    if db_path.exists() {
        println!("\n{} Database exists", success(""));

        // Show file size
        if let Ok(metadata) = fs::metadata(&db_path) {
            println!("File size:    {} bytes", metadata.len());
        }
    } else {
        println!("\n{} Database file does not exist", error(""));
        println!("{}", info("Run cc-switch once to create the database."));
    }

    // Show backup directory
    let backup_dir = config_dir.join("backups");
    if backup_dir.exists() {
        if let Ok(entries) = fs::read_dir(&backup_dir) {
            let count = entries.filter_map(|e| e.ok()).count();
            println!("\nBackups dir:  {}", backup_dir.display());
            println!("Backups:      {} backup(s) found", count);
        }
    }

    Ok(())
}

fn export_config(file: &PathBuf) -> Result<(), AppError> {
    println!(
        "{}",
        info(&format!("Exporting configuration to {}...", file.display()))
    );

    // Check if target file already exists
    if file.exists() {
        let confirm = inquire::Confirm::new(&format!(
            "File '{}' already exists. Overwrite?",
            file.display()
        ))
        .with_default(false)
        .prompt()
        .map_err(|e| AppError::Message(format!("Prompt failed: {}", e)))?;

        if !confirm {
            println!("{}", info("Cancelled."));
            return Ok(());
        }
    }

    // Ensure parent directory exists
    if let Some(parent) = file.parent() {
        fs::create_dir_all(parent).map_err(|e| AppError::io(parent, e))?;
    }

    // Export configuration
    ConfigService::export_config_to_path(file)?;

    println!(
        "{}",
        success(&format!("✓ Configuration exported to {}", file.display()))
    );

    Ok(())
}

fn import_config(file: &PathBuf) -> Result<(), AppError> {
    println!(
        "{}",
        info(&format!(
            "Importing configuration from {}...",
            file.display()
        ))
    );

    // Check if source file exists
    if !file.exists() {
        return Err(AppError::Message(format!(
            "File '{}' not found",
            file.display()
        )));
    }

    // Confirm import
    println!();
    println!("{}", highlight("Warning:"));
    println!("This will replace your current database with the imported SQL backup.");
    println!("A backup will be created automatically.");
    println!();

    let confirm = inquire::Confirm::new("Continue with import?")
        .with_default(false)
        .prompt()
        .map_err(|e| AppError::Message(format!("Prompt failed: {}", e)))?;

    if !confirm {
        println!("{}", info("Cancelled."));
        return Ok(());
    }

    // Perform import
    let state = get_state()?;
    let backup_id = ConfigService::import_config_from_path(file, &state)?;

    // 导入后同步 live 配置
    if let Err(e) = crate::services::provider::ProviderService::sync_current_to_live(&state) {
        log::warn!("配置导入后同步 live 配置失败: {e}");
    }

    println!(
        "{}",
        success(&format!("✓ Configuration imported from {}", file.display()))
    );
    if !backup_id.is_empty() {
        println!("{}", info(&format!("  Backup created: {}", backup_id)));
    }
    println!();
    println!(
        "{}",
        info("Note: Restart your CLI clients to apply the changes.")
    );

    Ok(())
}

fn backup_config(custom_name: Option<&str>) -> Result<(), AppError> {
    let config_path = crate::config::get_app_config_path();

    if let Some(name) = custom_name {
        println!(
            "{}",
            info(&format!("Creating backup with name '{}'...", name))
        );
    } else {
        println!("{}", info("Creating backup of current configuration..."));
    }

    let backup_id = ConfigService::create_backup(&config_path, custom_name.map(|s| s.to_string()))?;

    if backup_id.is_empty() {
        println!("{}", error("Failed to create backup."));
    } else {
        let backup_dir = config_path.parent().unwrap().join("backups");
        let backup_file = backup_dir.join(format!("{}.sql", backup_id));

        println!("{}", success(&format!("✓ Backup created: {}", backup_id)));
        println!("Location: {}", backup_file.display());
    }

    Ok(())
}

fn restore_config(backup_id: Option<&str>, file_path: Option<&Path>) -> Result<(), AppError> {
    let config_path = crate::config::get_app_config_path();

    // 情况1:指定了备份 ID
    if let Some(id) = backup_id {
        println!("{}", info(&format!("Restoring from backup '{}'...", id)));

        let confirm =
            inquire::Confirm::new("This will replace your current configuration. Continue?")
                .with_default(false)
                .prompt()
                .map_err(|e| AppError::Message(format!("Prompt failed: {}", e)))?;

        if !confirm {
            println!("{}", info("Cancelled."));
            return Ok(());
        }

        let state = get_state()?;
        let pre_restore_backup = ConfigService::restore_from_backup_id(id, &state)?;

        // 恢复后同步 live 配置
        if let Err(e) = crate::services::provider::ProviderService::sync_current_to_live(&state) {
            log::warn!("备份恢复后同步 live 配置失败: {e}");
        }

        println!(
            "{}",
            success(&format!("✓ Configuration restored from backup '{}'", id))
        );
        if !pre_restore_backup.is_empty() {
            println!(
                "{}",
                info(&format!("  Pre-restore backup: {}", pre_restore_backup))
            );
        }
        println!();
        println!(
            "{}",
            info("Note: Restart your CLI clients to apply the changes.")
        );

        return Ok(());
    }

    // 情况2:指定了文件路径
    if let Some(file) = file_path {
        println!(
            "{}",
            info(&format!(
                "Restoring configuration from {}...",
                file.display()
            ))
        );

        if !file.exists() {
            return Err(AppError::Message(format!(
                "File '{}' not found",
                file.display()
            )));
        }

        println!();
        println!("{}", highlight("Warning:"));
        println!("This will replace your current database with the SQL backup file.");
        println!("A backup of the current state will be created first.");
        println!();

        let confirm = inquire::Confirm::new(texts::config_restore_confirm_prompt())
            .with_default(false)
            .prompt()
            .map_err(|e| AppError::Message(format!("Prompt failed: {}", e)))?;

        if !confirm {
            println!("{}", info("Cancelled."));
            return Ok(());
        }

        let state = get_state()?;
        let pre_restore_backup = ConfigService::import_config_from_path(file, &state)?;

        // 恢复后同步 live 配置
        if let Err(e) = crate::services::provider::ProviderService::sync_current_to_live(&state) {
            log::warn!("配置恢复后同步 live 配置失败: {e}");
        }

        println!(
            "{}",
            success(&format!("✓ Configuration restored from {}", file.display()))
        );
        if !pre_restore_backup.is_empty() {
            println!(
                "{}",
                info(&format!("  Pre-restore backup: {}", pre_restore_backup))
            );
        }
        println!();
        println!(
            "{}",
            info("Note: Restart your CLI clients to apply the changes.")
        );

        return Ok(());
    }

    // 情况3:无参数,显示交互式列表
    println!("{}", highlight(texts::available_backups()));
    println!("{}", "=".repeat(50));

    let backups = ConfigService::list_backups(&config_path)?;

    if backups.is_empty() {
        println!();
        println!("{}", info(texts::no_backups_found()));
        println!("{}", info(texts::create_backup_first_hint()));
        return Ok(());
    }

    println!();
    println!("{}", texts::found_backups(backups.len()));
    println!();

    let choices: Vec<String> = backups
        .iter()
        .map(|b| format!("{} - {}", b.display_name, b.id))
        .collect();

    let selection = inquire::Select::new(texts::select_backup_to_restore(), choices)
        .prompt()
        .map_err(|_| AppError::Message(texts::selection_cancelled().to_string()))?;

    let selected_backup = backups
        .iter()
        .find(|b| selection.contains(&b.id))
        .ok_or_else(|| AppError::Message(texts::invalid_selection().to_string()))?;

    println!();
    println!("{}", highlight(texts::warning_title()));
    println!("{}", texts::config_restore_warning_replace());
    println!("{}", texts::config_restore_warning_pre_backup());
    println!();

    let confirm = inquire::Confirm::new(texts::config_restore_confirm_prompt())
        .with_default(false)
        .prompt()
        .map_err(|e| AppError::Message(format!("Prompt failed: {}", e)))?;

    if !confirm {
        println!("{}", info(texts::cancelled()));
        return Ok(());
    }

    let state = get_state()?;
    let pre_restore_backup = ConfigService::restore_from_backup_id(&selected_backup.id, &state)?;

    // 恢复后同步 live 配置
    if let Err(e) = crate::services::provider::ProviderService::sync_current_to_live(&state) {
        log::warn!("备份恢复后同步 live 配置失败: {e}");
    }

    println!(
        "{}",
        success(&format!(
            "✓ Configuration restored from: {}",
            selected_backup.display_name
        ))
    );
    if !pre_restore_backup.is_empty() {
        println!(
            "{}",
            info(&format!("  Pre-restore backup: {}", pre_restore_backup))
        );
    }
    println!();
    println!(
        "{}",
        info("Note: Restart your CLI clients to apply the changes.")
    );

    Ok(())
}

fn validate_config() -> Result<(), AppError> {
    let config_dir = crate::config::get_app_config_dir();
    let db_path = config_dir.join("cc-switch.db");

    println!("{}", info("Validating database..."));
    println!();

    if !db_path.exists() {
        println!("{}", error("✗ Database file does not exist"));
        println!("Path: {}", db_path.display());
        return Ok(());
    }

    println!("{} Database file exists", success(""));
    println!("Path: {}", db_path.display());

    let db = crate::Database::init()?;
    println!("{} Database schema is readable", success(""));

    // Show some stats
    let claude_count = db.get_all_providers("claude")?.len();
    let codex_count = db.get_all_providers("codex")?.len();
    let gemini_count = db.get_all_providers("gemini")?.len();
    let mcp_count = db.get_all_mcp_servers()?.len();
    let skills_count = db.get_all_installed_skills()?.len();

    println!();
    println!("{}", highlight("Database Summary:"));
    println!("Claude providers:  {}", claude_count);
    println!("Codex providers:   {}", codex_count);
    println!("Gemini providers:  {}", gemini_count);
    println!("MCP servers:       {}", mcp_count);
    println!("Skills installed:  {}", skills_count);

    println!();
    println!("{}", success("✓ Database validation passed"));

    Ok(())
}

fn reset_config() -> Result<(), AppError> {
    println!("{}", highlight("Reset Configuration"));
    println!("{}", "=".repeat(50));
    println!();
    println!("{}", highlight("Warning:"));
    println!("This will delete your current configuration and create a fresh default one.");
    println!("All your providers, MCP servers, and settings will be lost.");
    println!();
    println!("{}", info("Consider creating a backup first:"));
    println!("  cc-switch config backup");
    println!();

    let confirm = inquire::Confirm::new("Are you sure you want to reset to default configuration?")
        .with_default(false)
        .prompt()
        .map_err(|e| AppError::Message(format!("Prompt failed: {}", e)))?;

    if !confirm {
        println!("{}", info("Cancelled."));
        return Ok(());
    }

    // Create a backup before reset (SQL)
    let config_path = crate::config::get_app_config_path();
    let backup_id = ConfigService::create_backup(&config_path, None)?;

    // Delete the database file
    let db_path = crate::config::get_app_config_dir().join("cc-switch.db");
    if db_path.exists() {
        fs::remove_file(&db_path).map_err(|e| AppError::io(&db_path, e))?;
    }

    // Recreate empty DB
    let _ = crate::Database::init()?;

    println!("{}", success("✓ Configuration reset to defaults"));
    if !backup_id.is_empty() {
        println!("{}", info(&format!("  Backup created: {}", backup_id)));
        println!(
            "{}",
            info("  You can restore it later using: cc-switch config restore")
        );
    }

    Ok(())
}