Skip to main content

cc_switch/cli/
completion.rs

1use crate::config::ConfigStorage;
2use anyhow::Result;
3use clap::CommandFactory;
4use std::fs;
5use std::io::Write;
6use std::path::PathBuf;
7
8/// Generate shell aliases for eval
9///
10/// # Arguments
11/// * `shell` - Shell type (fish, zsh, bash)
12///
13/// # Errors
14/// Returns error if shell is not supported
15pub fn generate_aliases(shell: &str) -> Result<()> {
16    match shell {
17        "fish" | "zsh" | "bash" => {
18            println!("alias cs='cc-switch'");
19            println!("alias cx='cc-switch codex'");
20            println!("alias co='cc-switch omp'");
21            println!("alias cg='cc-switch grok'");
22        }
23        _ => {
24            anyhow::bail!(
25                "Unsupported shell: {}. Supported shells: fish, zsh, bash",
26                shell
27            );
28        }
29    }
30
31    Ok(())
32}
33
34/// Return the install path for a shell's completion file, if it has a standard location.
35fn completion_install_path(shell: &str) -> Option<PathBuf> {
36    let home = dirs::home_dir()?;
37    match shell {
38        "fish" => Some(home.join(".config/fish/completions/cc-switch.fish")),
39        "zsh" => Some(home.join(".zsh/completions/_cc-switch")),
40        "bash" => Some(home.join(".bash_completion.d/cc-switch")),
41        _ => None,
42    }
43}
44
45/// Generate shell completion script and install it to the standard path.
46///
47/// For fish/zsh/bash the output is written directly to the shell's
48/// completion directory. For other shells the script is printed to stdout.
49///
50/// # Errors
51/// Returns error if shell is not supported or generation fails
52pub fn generate_completion(shell: &str) -> Result<()> {
53    use crate::cli::Cli;
54
55    let mut app = Cli::command();
56    let mut buf: Vec<u8> = Vec::new();
57
58    match shell {
59        "fish" => {
60            generate_fish_completion(&mut app, &mut buf);
61        }
62        "zsh" => {
63            clap_complete::generate(clap_complete::shells::Zsh, &mut app, "cc-switch", &mut buf);
64        }
65        "bash" => {
66            clap_complete::generate(clap_complete::shells::Bash, &mut app, "cc-switch", &mut buf);
67        }
68        "elvish" => {
69            clap_complete::generate(
70                clap_complete::shells::Elvish,
71                &mut app,
72                "cc-switch",
73                &mut std::io::stdout(),
74            );
75            return Ok(());
76        }
77        "powershell" => {
78            clap_complete::generate(
79                clap_complete::shells::PowerShell,
80                &mut app,
81                "cc-switch",
82                &mut std::io::stdout(),
83            );
84            return Ok(());
85        }
86        _ => {
87            anyhow::bail!(
88                "Unsupported shell: {}. Supported shells: fish, zsh, bash, elvish, powershell",
89                shell
90            );
91        }
92    }
93
94    if let Some(path) = completion_install_path(shell) {
95        if let Some(parent) = path.parent() {
96            fs::create_dir_all(parent)?;
97        }
98        fs::write(&path, &buf)?;
99        eprintln!("Installed {shell} completion to {}", path.display());
100    } else {
101        std::io::stdout().write_all(&buf)?;
102    }
103
104    Ok(())
105}
106
107/// List available configuration aliases for shell completion
108///
109/// Outputs all stored configuration aliases, one per line
110/// Also includes 'cc' and 'official' as special aliases for resetting to default Claude
111/// For contexts where user types 'cc-switch use c' or similar, 'current' is prioritized first
112///
113/// # Errors
114/// Returns error if loading configurations fails
115pub fn list_aliases_for_completion() -> Result<()> {
116    let storage = ConfigStorage::load()?;
117
118    // Always include 'cc' and 'official' for reset functionality
119    println!("cc");
120    println!("official");
121
122    // Prioritize 'current' first if it exists - this ensures when user types 'cc-switch use c'
123    // or 'cs use c', the 'current' configuration appears first in completion
124    if storage.configurations.contains_key("current") {
125        println!("current");
126    }
127
128    // Output all other stored aliases in alphabetical order
129    let mut aliases: Vec<String> = storage.configurations.keys().cloned().collect();
130    aliases.sort();
131
132    for alias_name in aliases {
133        if alias_name != "current" {
134            println!("{alias_name}");
135        }
136    }
137
138    Ok(())
139}
140
141/// List available Codex configuration aliases for shell completion
142///
143/// Outputs all stored Codex configuration aliases, one per line
144///
145/// # Errors
146/// Returns error if loading configurations fails
147pub fn list_codex_aliases_for_completion() -> Result<()> {
148    let storage = ConfigStorage::load()?;
149
150    // Output all stored Codex aliases in alphabetical order
151    if let Some(ref configs) = storage.codex_configurations {
152        let mut aliases: Vec<String> = configs.keys().cloned().collect();
153        aliases.sort();
154
155        for alias_name in aliases {
156            println!("{alias_name}");
157        }
158    }
159
160    Ok(())
161}
162/// List available OMP configuration aliases for shell completion
163///
164/// Outputs all stored OMP configuration aliases, one per line
165///
166/// # Errors
167/// Returns error if loading configurations fails
168pub fn list_omp_aliases_for_completion() -> Result<()> {
169    let storage = ConfigStorage::load()?;
170
171    // Output all stored OMP aliases in alphabetical order
172    if let Some(configs) = &storage.omp_configurations {
173        let mut aliases: Vec<String> = configs.keys().cloned().collect();
174        aliases.sort();
175
176        for alias_name in aliases {
177            println!("{alias_name}");
178        }
179    }
180
181    Ok(())
182}
183
184/// List available grok configuration aliases for shell completion
185///
186/// Outputs all stored grok configuration aliases, one per line
187///
188/// # Errors
189/// Returns error if loading configurations fails
190pub fn list_grok_aliases_for_completion() -> Result<()> {
191    let storage = ConfigStorage::load()?;
192
193    if let Some(configs) = &storage.grok_configurations {
194        let mut aliases: Vec<String> = configs.keys().cloned().collect();
195        aliases.sort();
196
197        for alias_name in aliases {
198            println!("{alias_name}");
199        }
200    }
201
202    Ok(())
203}
204
205/// Generate custom fish completion with dynamic alias completion, writing to `out`.
206fn generate_fish_completion(app: &mut clap::Command, out: &mut Vec<u8>) {
207    clap_complete::generate(clap_complete::shells::Fish, app, "cc-switch", out);
208
209    let extra = r#"
210# Custom completion for use subcommand with dynamic aliases
211complete -c cc-switch -n '__fish_cc_switch_using_subcommand use' -f -a '(cc-switch --list-aliases)' -d 'Configuration alias name'
212# Custom completion for switch subcommand (alias for use)
213complete -c cc-switch -n '__fish_cc_switch_using_subcommand switch' -f -a '(cc-switch --list-aliases)' -d 'Configuration alias name'
214# Custom completion for remove subcommand with dynamic aliases
215complete -c cc-switch -n '__fish_cc_switch_using_subcommand remove' -f -a '(cc-switch --list-aliases)' -d 'Configuration alias name'
216
217# Completion for 'completion' subcommand with shell types
218complete -c cc-switch -n '__fish_cc_switch_using_subcommand completion' -f -a 'fish zsh bash elvish powershell' -d 'Shell type'
219
220# Completion for 'cc-switch omp' subcommand dynamic aliases
221complete -c cc-switch -n '__fish_seen_subcommand_from omp' -n '__fish_seen_subcommand_from use' -f -a '(cc-switch --list-omp-aliases)' -d 'OMP configuration alias name'
222complete -c cc-switch -n '__fish_seen_subcommand_from omp' -n '__fish_seen_subcommand_from remove' -f -a '(cc-switch --list-omp-aliases)' -d 'OMP configuration alias name'
223
224# Completion for 'cc-switch grok' subcommand dynamic aliases
225complete -c cc-switch -n '__fish_seen_subcommand_from grok' -n '__fish_seen_subcommand_from use' -f -a '(cc-switch --list-grok-aliases)' -d 'grok configuration alias name'
226complete -c cc-switch -n '__fish_seen_subcommand_from grok' -n '__fish_seen_subcommand_from remove' -f -a '(cc-switch --list-grok-aliases)' -d 'grok configuration alias name'
227"#;
228    out.extend_from_slice(extra.as_bytes());
229
230    generate_cs_completion_file();
231    generate_cx_completion_file();
232    generate_co_completion_file();
233    generate_cg_completion_file();
234}
235
236/// Generate separate completion file for cs fish alias.
237///
238/// Fish only auto-loads completions from files named after the command,
239/// so `cs` needs its own `cs.fish`.
240fn generate_cs_completion_file() {
241    let home = dirs::home_dir().unwrap_or_else(|| std::path::PathBuf::from("~"));
242    let completions_dir = home.join(".config").join("fish").join("completions");
243
244    if !completions_dir.exists()
245        && let Err(e) = fs::create_dir_all(&completions_dir)
246    {
247        eprintln!("Warning: Could not create completions directory: {e}");
248        return;
249    }
250
251    let cs_content = r#"# Completion for 'cs' alias (cc-switch)
252complete -c cs -w cc-switch
253"#;
254
255    let cs_path = completions_dir.join("cs.fish");
256
257    if let Err(e) = fs::write(&cs_path, cs_content) {
258        eprintln!("Warning: Could not write cs.fish: {e}");
259    }
260
261    eprintln!("Created completion file: {}", cs_path.display());
262}
263
264/// Generate separate completion file for cx fish function
265///
266/// Fish doesn't automatically load completion files for functions, only for commands.
267/// This creates ~/.config/fish/completions/cx.fish
268fn generate_cx_completion_file() {
269    // Fish uses ~/.config/fish/completions on all platforms (including macOS)
270    let home = dirs::home_dir().unwrap_or_else(|| std::path::PathBuf::from("~"));
271    let completions_dir = home.join(".config").join("fish").join("completions");
272
273    if !completions_dir.exists()
274        && let Err(e) = fs::create_dir_all(&completions_dir)
275    {
276        eprintln!("Warning: Could not create completions directory: {e}");
277        return;
278    }
279
280    let cx_content = r#"# Completion for 'cx' alias (cc-switch codex)
281# Define cx as a fish function
282function cx
283    cc-switch codex $argv
284end
285
286# Disable file completion by default
287complete -c cx -f
288complete -c cx -n '__fish_use_subcommand' -f -a 'add use remove list' -d 'Codex subcommand'
289complete -c cx -n '__fish_seen_subcommand_from use' -f -a '(cc-switch --list-codex-aliases)' -d 'Codex configuration alias name'
290complete -c cx -n '__fish_seen_subcommand_from remove' -f -a '(cc-switch --list-codex-aliases)' -d 'Codex configuration alias name'
291complete -c cx -n '__fish_seen_subcommand_from list' -f -l plain -s p -d 'Plain text output'
292complete -c cx -n '__fish_seen_subcommand_from list' -f -l name -s n -d 'Show only name and auth mode'
293complete -c cx -n '__fish_seen_subcommand_from add' -f -l interactive -s i -d 'Interactive mode'
294complete -c cx -n '__fish_seen_subcommand_from add' -f -l from-file -d 'Import from auth.json (defaults to ~/.codex/auth.json if no path)' -r
295"#;
296
297    let cx_path = completions_dir.join("cx.fish");
298
299    if let Err(e) = fs::write(&cx_path, cx_content) {
300        eprintln!("Warning: Could not write cx.fish: {e}");
301    }
302
303    eprintln!("\nCreated completion file: {}", cx_path.display());
304}
305/// Generate separate completion file for co fish function
306///
307/// Fish doesn't automatically load completion files for functions, only for commands.
308/// This creates ~/.config/fish/completions/co.fish
309fn generate_co_completion_file() {
310    let home = dirs::home_dir().unwrap_or_else(|| std::path::PathBuf::from("~"));
311    let completions_dir = home.join(".config").join("fish").join("completions");
312
313    if !completions_dir.exists()
314        && let Err(e) = fs::create_dir_all(&completions_dir)
315    {
316        eprintln!("Warning: Could not create completions directory: {e}");
317        return;
318    }
319
320    let co_content = r#"# Completion for 'co' alias (cc-switch omp)
321# Define co as a fish function
322function co
323    cc-switch omp $argv
324end
325
326# Disable file completion by default
327complete -c co -f
328complete -c co -n '__fish_use_subcommand' -f -a 'add use remove list' -d 'OMP subcommand'
329complete -c co -n '__fish_seen_subcommand_from use' -f -a '(cc-switch --list-omp-aliases)' -d 'OMP configuration alias name'
330complete -c co -n '__fish_seen_subcommand_from remove' -f -a '(cc-switch --list-omp-aliases)' -d 'OMP configuration alias name'
331complete -c co -n '__fish_seen_subcommand_from list' -f -l plain -s p -d 'Plain text output'
332complete -c co -n '__fish_seen_subcommand_from list' -f -l name -s n -d 'Show only name and auth mode'
333complete -c co -n '__fish_seen_subcommand_from add' -f -l interactive -s i -d 'Interactive mode'
334complete -c co -n '__fish_seen_subcommand_from add' -f -l from-file -d 'Import from .env file (defaults to ~/.omp/agent/.env if no path)' -r
335"#;
336
337    let co_path = completions_dir.join("co.fish");
338
339    if let Err(e) = fs::write(&co_path, co_content) {
340        eprintln!("Warning: Could not write co.fish: {e}");
341    }
342
343    eprintln!("\nCreated completion file: {}", co_path.display());
344}
345/// Generate separate completion file for cg fish function
346///
347/// Fish doesn't automatically load completion files for functions, only for commands.
348/// This creates ~/.config/fish/completions/cg.fish
349fn generate_cg_completion_file() {
350    let home = dirs::home_dir().unwrap_or_else(|| std::path::PathBuf::from("~"));
351    let completions_dir = home.join(".config").join("fish").join("completions");
352
353    if !completions_dir.exists()
354        && let Err(e) = fs::create_dir_all(&completions_dir)
355    {
356        eprintln!("Warning: Could not create completions directory: {e}");
357        return;
358    }
359
360    let cg_content = r#"# Completion for 'cg' alias (cc-switch grok)
361# Define cg as a fish function
362function cg
363    cc-switch grok $argv
364end
365
366# Disable file completion by default
367complete -c cg -f
368complete -c cg -n '__fish_use_subcommand' -f -a 'add use remove list' -d 'grok subcommand'
369complete -c cg -n '__fish_seen_subcommand_from use' -f -a '(cc-switch --list-grok-aliases)' -d 'grok configuration alias name'
370complete -c cg -n '__fish_seen_subcommand_from remove' -f -a '(cc-switch --list-grok-aliases)' -d 'grok configuration alias name'
371complete -c cg -n '__fish_seen_subcommand_from list' -f -l plain -s p -d 'Plain text output'
372complete -c cg -n '__fish_seen_subcommand_from list' -f -l name -s n -d 'Show only alias name and model'
373complete -c cg -n '__fish_seen_subcommand_from add' -f -l interactive -s i -d 'Interactive mode'
374complete -c cg -n '__fish_seen_subcommand_from add' -f -l from-file -d 'Import from config.toml (defaults to ~/.grok/config.toml if no path)' -r
375"#;
376
377    let cg_path = completions_dir.join("cg.fish");
378
379    if let Err(e) = fs::write(&cg_path, cg_content) {
380        eprintln!("Warning: Could not write cg.fish: {e}");
381    }
382
383    eprintln!("\nCreated completion file: {}", cg_path.display());
384}