Skip to content

Commit 1c50512

Browse files
committed
feat(cli): add dynamic shell completion support (!59)
> **🏗️ build-from-issue-agent** Closes #71 ## Summary Add dynamic shell completion support using `clap_complete`'s `CompleteEnv`, plus a `navigator completions <shell>` subcommand (rustup-style) that outputs completion scripts to stdout with detailed per-shell setup instructions in `--help`. Completions are dynamic — the shell calls back into the `navigator` binary on each tab-press, so they are always in sync with the installed version. This also lays the groundwork for future runtime completers (e.g., listing sandbox names on tab, tracked in #83). ## Changes Made - `Cargo.toml`: Added `clap_complete = { version = "4.5", features = ["unstable-dynamic"] }` to workspace dependencies - `crates/navigator-cli/Cargo.toml`: Added `clap_complete` dependency - `crates/navigator-cli/src/main.rs`: - Added `CompleteEnv::with_factory(Cli::command).complete()` at the top of `main()` (before TLS/argument parsing) - Added `Completions { shell }` subcommand that re-invokes the binary with `COMPLETE=<shell>` and pipes the output - Added `CompletionShell` enum (bash, fish, zsh, powershell) - Added `COMPLETIONS_HELP` with per-shell setup instructions (similar to `rustup completions --help`) - Added 3 unit tests - `CONTRIBUTING.md`: Added shell completions section documenting `nav` wrapper setup ## Usage ```bash # Generate completions navigator completions fish > ~/.config/fish/completions/navigator.fish navigator completions bash > ~/.local/share/bash-completion/completions/navigator navigator completions zsh > ~/.zfunc/_navigator navigator completions powershell >> $PROFILE # See full per-shell instructions navigator completions --help # For the nav wrapper (rewrite registration target) navigator completions fish | sed 's/--command navigator/--command nav/' > ~/.config/fish/completions/nav.fish ``` ## Design Decision: Why stdout-only (no auto-install) We researched how 12 popular CLI tools handle completion installation: | Tool | Command | Writes files? | Modifies RC? | |------|---------|---------------|-------------| | gh, glab, kubectl, docker, rustup, mise, starship | `completion <shell>` | stdout only | No | | atuin | `gen-completions --shell <shell>` | stdout (`--out-dir` option) | No | | gcloud | `install.sh` | Yes | **Yes** | | Amazon Q | `q integrations install` | Yes | **Yes** | **10 of 12 tools** follow the same pattern: output to stdout, never modify RC files, explicit shell selection, clear `--help` instructions. Only gcloud and Amazon Q modify RC files (and both have been criticized for it). Our approach matches the industry consensus. ## Deviations from Plan - The original issue proposed a static `completions <shell>` subcommand using `clap_complete::generate()`. After discussion, we switched to dynamic `CompleteEnv` which is always up-to-date and enables future runtime completers. - Added a `navigator completions <shell>` subcommand (not in original plan) for discoverability — it wraps the `COMPLETE` env var mechanism with a familiar CLI UX. ## Tests Added - **Unit:** `cli_debug_assert` — validates CLI structure; `completions_engine_returns_candidates` — smoke test confirming the completion engine returns subcommand candidates; `completions_subcommand_appears_in_candidates` — verifies `completions` appears in tab-completion results - **Integration:** N/A - **E2E:** N/A ## Verification - [x] All tests passing - [x] Pre-commit checks passing (clippy warnings are pre-existing, not from this change) - [x] CONTRIBUTING.md updated with nav wrapper completion setup
1 parent 5fd4885 commit 1c50512

5 files changed

Lines changed: 180 additions & 1 deletion

File tree

‎CONTRIBUTING.md‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,30 @@ mise test # Run all project tests
5454
mise run sandbox # Run sandbox container interactively
5555
```
5656

57+
## Shell Completions
58+
59+
The CLI supports dynamic shell completions. Run `navigator completions --help` for full per-shell setup instructions.
60+
61+
For the `nav` wrapper, generate completions from the real binary and rewrite the registration to target `nav`:
62+
63+
**Fish:**
64+
65+
```bash
66+
navigator completions fish | sed 's/--command navigator/--command nav/' > ~/.config/fish/completions/nav.fish
67+
```
68+
69+
**Bash:**
70+
71+
```bash
72+
navigator completions bash | sed 's/_clap_complete_navigator/_clap_complete_nav/g; s/ navigator$/ nav/' > ~/.local/share/bash-completion/completions/nav
73+
```
74+
75+
**Zsh:**
76+
77+
```bash
78+
navigator completions zsh | sed 's/_clap_dynamic_completer_navigator/_clap_dynamic_completer_nav/g; s/ navigator$/ nav/' > ~/.zfunc/_nav
79+
```
80+
5781
## Sandbox SSH access
5882

5983
To connect to a running sandbox with SSH, use:

‎Cargo.lock‎

Lines changed: 29 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎Cargo.toml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ webpki-roots = "1"
3838

3939
# CLI
4040
clap = { version = "4.5", features = ["derive", "env"] }
41+
clap_complete = { version = "4.5", features = ["unstable-dynamic"] }
4142
indicatif = "0.17"
4243
owo-colors = "4"
4344
ratatui = "0.26"

‎crates/navigator-cli/Cargo.toml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ tonic = { workspace = true, features = ["tls"] }
2828

2929
# CLI
3030
clap = { workspace = true }
31+
clap_complete = { workspace = true }
3132
crossterm = { workspace = true }
3233
dialoguer = "0.11"
3334
indicatif = { workspace = true }

‎crates/navigator-cli/src/main.rs‎

Lines changed: 125 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
//! Navigator CLI - command-line interface for Navigator.
22
33
use clap::{CommandFactory, Parser, Subcommand, ValueEnum};
4+
use clap_complete::env::CompleteEnv;
45
use miette::Result;
56
use owo_colors::OwoColorize;
7+
use std::io::Write;
68
use std::path::PathBuf;
79

810
use navigator_bootstrap::{load_active_cluster, load_cluster_metadata};
@@ -127,6 +129,13 @@ enum Commands {
127129
command: ProviderCommands,
128130
},
129131

132+
/// Generate shell completions.
133+
#[command(after_long_help = COMPLETIONS_HELP)]
134+
Completions {
135+
/// Shell to generate completions for.
136+
shell: CompletionShell,
137+
},
138+
130139
/// SSH proxy (used by `ProxyCommand`).
131140
///
132141
/// Two mutually exclusive modes:
@@ -164,6 +173,70 @@ enum Commands {
164173
},
165174
}
166175

176+
#[derive(Clone, Debug, ValueEnum)]
177+
enum CompletionShell {
178+
Bash,
179+
Fish,
180+
Zsh,
181+
Powershell,
182+
}
183+
184+
impl std::fmt::Display for CompletionShell {
185+
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
186+
match self {
187+
Self::Bash => write!(f, "bash"),
188+
Self::Fish => write!(f, "fish"),
189+
Self::Zsh => write!(f, "zsh"),
190+
Self::Powershell => write!(f, "powershell"),
191+
}
192+
}
193+
}
194+
195+
const COMPLETIONS_HELP: &str = "\
196+
Enable tab completion for Bash, Fish, Zsh, or PowerShell.
197+
198+
The script is output on stdout, allowing you to redirect the output
199+
to the file of your choosing. Where you place the file will depend
200+
on which shell and operating system you are using.
201+
202+
BASH:
203+
204+
$ mkdir -p ~/.local/share/bash-completion/completions
205+
$ navigator completions bash > ~/.local/share/bash-completion/completions/navigator
206+
207+
On macOS with Homebrew (install bash-completion first):
208+
209+
$ mkdir -p $(brew --prefix)/etc/bash_completion.d
210+
$ navigator completions bash > $(brew --prefix)/etc/bash_completion.d/navigator.bash-completion
211+
212+
FISH:
213+
214+
$ mkdir -p ~/.config/fish/completions
215+
$ navigator completions fish > ~/.config/fish/completions/navigator.fish
216+
217+
ZSH:
218+
219+
$ mkdir -p ~/.zfunc
220+
$ navigator completions zsh > ~/.zfunc/_navigator
221+
222+
Then add the following to your .zshrc before compinit:
223+
224+
fpath+=~/.zfunc
225+
226+
And reload with:
227+
228+
$ exec zsh
229+
230+
POWERSHELL:
231+
232+
> navigator completions powershell >> $PROFILE
233+
234+
If no profile exists yet, create one first:
235+
236+
> New-Item -Path $PROFILE -Type File -Force
237+
238+
You may need to log out and back in for changes to take effect.";
239+
167240
#[derive(Clone, Debug, ValueEnum)]
168241
enum CliProviderType {
169242
Claude,
@@ -702,6 +775,8 @@ enum InferenceCommands {
702775

703776
#[tokio::main]
704777
async fn main() -> Result<()> {
778+
CompleteEnv::with_factory(Cli::command).complete();
779+
705780
rustls::crypto::aws_lc_rs::default_provider()
706781
.install_default()
707782
.map_err(|e| miette::miette!("failed to install rustls crypto provider: {e:?}"))?;
@@ -1158,6 +1233,17 @@ async fn main() -> Result<()> {
11581233
}
11591234
}
11601235
}
1236+
Some(Commands::Completions { shell }) => {
1237+
let exe = std::env::current_exe()
1238+
.map_err(|e| miette::miette!("failed to find current executable: {e}"))?;
1239+
let output = std::process::Command::new(exe)
1240+
.env("COMPLETE", shell.to_string())
1241+
.output()
1242+
.map_err(|e| miette::miette!("failed to generate completions: {e}"))?;
1243+
std::io::stdout()
1244+
.write_all(&output.stdout)
1245+
.map_err(|e| miette::miette!("failed to write completions: {e}"))?;
1246+
}
11611247
Some(Commands::SshProxy {
11621248
gateway,
11631249
sandbox_id,
@@ -1206,3 +1292,42 @@ async fn main() -> Result<()> {
12061292

12071293
Ok(())
12081294
}
1295+
1296+
#[cfg(test)]
1297+
mod tests {
1298+
use super::*;
1299+
use std::ffi::OsString;
1300+
1301+
#[test]
1302+
fn cli_debug_assert() {
1303+
Cli::command().debug_assert();
1304+
}
1305+
1306+
#[test]
1307+
fn completions_engine_returns_candidates() {
1308+
let mut cmd = Cli::command();
1309+
let args: Vec<OsString> = vec!["navigator".into(), "".into()];
1310+
let candidates = clap_complete::engine::complete(&mut cmd, args, 1, None)
1311+
.expect("completion engine failed");
1312+
assert!(
1313+
!candidates.is_empty(),
1314+
"expected subcommand completions for empty input"
1315+
);
1316+
}
1317+
1318+
#[test]
1319+
fn completions_subcommand_appears_in_candidates() {
1320+
let mut cmd = Cli::command();
1321+
let args: Vec<OsString> = vec!["navigator".into(), "comp".into()];
1322+
let candidates = clap_complete::engine::complete(&mut cmd, args, 1, None)
1323+
.expect("completion engine failed");
1324+
let names: Vec<String> = candidates
1325+
.iter()
1326+
.map(|c| c.get_value().to_string_lossy().into_owned())
1327+
.collect();
1328+
assert!(
1329+
names.contains(&"completions".to_string()),
1330+
"expected 'completions' in candidates, got: {names:?}"
1331+
);
1332+
}
1333+
}

0 commit comments

Comments
 (0)