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