From 89a42d81729a66bfc6dcb5649951c696316e5ef5 Mon Sep 17 00:00:00 2001 From: blockmandev <194144408+blockmandev@users.noreply.github.com> Date: Wed, 21 Oct 2026 18:38:35 -0600 Subject: [PATCH 1/2] completions: incode completions bash|zsh|fish|powershell (refs #26) #26 item 2. The parser is hand-written, so there is no argument library to generate completions from: src/completions.rs generates them from a table of the command line, COMPLETION, kept beside USAGE in main.rs. What is completed: every flag; the values of -p, --output-format and --spec-gate; the subcommands in first place (update, review, plugin, mcp, completions) and their verbs (mcp login, plugin add, ...); file names after a path flag; nothing after a free-text one. bash and zsh get a function each over their own word arrays, fish `complete` lines, PowerShell a native argument completer. Tests: - The table and USAGE (and review's USAGE) name the same flags, both ways; the subcommands match USAGE's lines. - The parser takes every flag and every fixed value offered (an error may only be about a combination, never "unknown"); review's flags parse; mcp's verbs are not "unknown"; plugin's are in its help. - The generated scripts run in the real shells on the same cases: bash calling the function, PowerShell through TabExpansion2, fish through `complete -C`, zsh with compadd/_files/compdef stood in for. Each skips, and says so, where its shell is missing; CI's Linux job now installs fish and zsh so every one runs somewhere. - A word that is not a plain token is refused rather than written into a script a shell runs. Controls: dropping --add-dir from the table fails the USAGE test; dropping fixed values from the generator fails bash and PowerShell. Found on the way: a PowerShell default branch written as a bare { } block was a script-block value, printed instead of run; a bare `--` is PowerShell's own token and reaches no completer, so the cases use prefixes. --- .github/workflows/ci.yml | 7 + README.md | 1 + src/completions.rs | 570 +++++++++++++++++++++++++++++++++++ src/lib.rs | 1 + src/main.rs | 624 +++++++++++++++++++++++++++++++++++++++ 5 files changed, 1203 insertions(+) create mode 100644 src/completions.rs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index abc24a6..3fd0a11 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -67,6 +67,13 @@ jobs: pkg-config clang libclang-dev libwayland-dev libpipewire-0.3-dev \ libxcb1-dev libxcb-randr0-dev libxcb-shm0-dev libdbus-1-dev \ libegl-dev libgbm-dev + # fish and zsh, for the completion scripts' tests (main.rs + # `fish_completes_from_the_table`, `zsh_completes_from_the_table`), + # which run them in the real shell and skip where it is missing. Test + # tools only: nothing links against them. + - name: shells the completion tests drive + if: runner.os == 'Linux' + run: sudo apt-get install -y --no-install-recommends fish zsh - uses: dtolnay/rust-toolchain@stable with: components: clippy diff --git a/README.md b/README.md index 460d536..6942cc5 100644 --- a/README.md +++ b/README.md @@ -307,6 +307,7 @@ agreeing what "done" means. | `incode --desktop-stop` | Halt the desktop driving this workspace. | | `incode --install-tools` | Download, check and unpack every [external tool](#external-tools) in `admin.json`, then exit (non-zero if any was not installed). | | `incode update [--check]` | Install the latest release over this program, checked against its `SHA256SUMS` (see [Install](#install)); `--check` only reports whether there is one. | +| `incode completions ` | Print a completion script for that shell: flags, the values of `-p`, `--output-format` and `--spec-gate`, the subcommands and their verbs (`mcp login`, `plugin add`, …), and file names after a path flag. Load it with `source <(incode completions bash)` (zsh: the same, after `compinit`), `incode completions fish \| source`, or in PowerShell `incode completions powershell \| Out-String \| Invoke-Expression` — in your shell's startup file to keep it. | | `incode --tool-server` | Internal. Started by the agent CLI that incode launched; offers incode's tools over MCP and runs nothing itself. | | `incode --desktop-mcp` | Internal. The desktop tools' executor, started by incode's toolbox. | | `incode --team-mcp --team-channel

` | Internal. The team channel as an MCP server, for `codex`. | diff --git a/src/completions.rs b/src/completions.rs new file mode 100644 index 0000000..4022941 --- /dev/null +++ b/src/completions.rs @@ -0,0 +1,570 @@ +//! `incode completions `: a completion script for bash, zsh, fish or +//! PowerShell, generated from a table of the command line. +//! +//! The parser is hand-written (`main.rs` `parse_args`), so there is no +//! argument library to generate completions from. The table — [`Command`] — +//! is kept beside `USAGE` in `main.rs`, whose tests hold the two to the same +//! flags and check that the parser accepts every one of them. +//! +//! Every script follows one logic: the word before the cursor decides what is +//! offered. After a flag with fixed values, those values; after a flag that +//! takes a path or free text, nothing, so the shell completes file names; else +//! the flags of the command in force — `incode` itself, or the subcommand in +//! first place — and, in the first position after it, its subcommands or +//! verbs. bash and zsh get a function each, over their own word arrays (bash +//! counts from 0, zsh from 1); fish gets `complete` lines and PowerShell a +//! native argument completer. + +/// What a flag takes after it. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Value { + /// Nothing: a switch. + None, + /// One of these words. + Choice(&'static [&'static str]), + /// A path: the shell completes file names. + Path, + /// Free text (a model, a task): nothing to offer. + Text, +} + +/// One flag, in its long and short spelling. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Flag { + pub long: &'static str, + pub short: Option<&'static str>, + pub value: Value, + /// One line, shown by fish beside the flag. + pub help: &'static str, +} + +/// `incode`, or one of its subcommands. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Command { + pub name: &'static str, + pub flags: &'static [Flag], + /// Words that may come first after the command (`mcp list`, `plugin add`). + pub verbs: &'static [&'static str], + /// Commands in first place after this one (only `incode` has them). + pub subcommands: &'static [Command], +} + +/// A flag with fixed values: its spellings, and the values. +type Choices = (Vec<&'static str>, &'static [&'static str]); + +/// The shells a script is written for. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Shell { + Bash, + Zsh, + Fish, + PowerShell, +} + +impl Shell { + /// Every shell, by the name `incode completions` takes. + pub const NAMES: [&'static str; 4] = ["bash", "zsh", "fish", "powershell"]; + + /// The shell `name` names (`pwsh` too), or `None`. + #[must_use] + pub fn parse(name: &str) -> Option { + match name { + "bash" => Some(Self::Bash), + "zsh" => Some(Self::Zsh), + "fish" => Some(Self::Fish), + "powershell" | "pwsh" => Some(Self::PowerShell), + _ => None, + } + } +} + +impl Command { + fn words(&self) -> Vec<&'static str> { + let mut words = Vec::new(); + for flag in self.flags { + words.push(flag.long); + words.extend(flag.short); + } + words + } + + /// The words offered first after this command: its verbs, or the names + /// of its subcommands. + fn first_words(&self) -> Vec<&'static str> { + let mut words: Vec<&'static str> = self.verbs.to_vec(); + words.extend(self.subcommands.iter().map(|c| c.name)); + words + } + + /// The flags that take something, grouped by what: choices with their + /// words, then every flag after which nothing is offered. + fn valued(&self) -> (Vec, Vec<&'static str>) { + let mut choices = Vec::new(); + let mut open = Vec::new(); + for flag in self.flags { + let spellings: Vec<&'static str> = + std::iter::once(flag.long).chain(flag.short).collect(); + match flag.value { + Value::Choice(words) => choices.push((spellings, words)), + Value::Path | Value::Text => open.extend(spellings), + Value::None => {} + } + } + (choices, open) + } +} + +/// Every word a script will contain, from `spec` down. Each must be a plain +/// token — letters, digits and `-` — so no shell reads one as syntax. +#[must_use] +pub fn all_words(spec: &Command) -> Vec<&'static str> { + let mut words = vec![spec.name]; + words.extend(spec.words()); + words.extend(spec.first_words()); + for flag in spec.flags { + if let Value::Choice(values) = flag.value { + words.extend(values); + } + } + for sub in spec.subcommands { + words.extend(all_words(sub)); + } + words +} + +fn is_plain(word: &str) -> bool { + !word.is_empty() && word.chars().all(|c| c.is_ascii_alphanumeric() || c == '-') +} + +/// The completion script for `shell`. +/// +/// # Errors +/// +/// A word in `spec` is not a plain token ([`all_words`]): it is refused +/// rather than written into a script the shell runs. +pub fn script(shell: Shell, spec: &Command) -> Result { + if let Some(bad) = all_words(spec).into_iter().find(|w| !is_plain(w)) { + return Err(format!( + "`{bad}` is not a plain word; it cannot go into a completion script" + )); + } + Ok(match shell { + Shell::Bash => format!( + "# {name} completion for bash. Load it with:\n\ + # source <({name} completions bash)\n{body}", + name = spec.name, + body = bash(spec) + ), + Shell::Zsh => format!( + "#compdef {name}\n\ + # {name} completion for zsh. Load it, after compinit, with:\n\ + # source <({name} completions zsh)\n{body}", + name = spec.name, + body = zsh(spec) + ), + Shell::Fish => fish(spec), + Shell::PowerShell => powershell(spec), + }) +} + +// --------------------------------------------------------------------------- +// bash (and zsh) +// --------------------------------------------------------------------------- + +fn bash(spec: &Command) -> String { + let function = format!("_{}", spec.name.replace('-', "_")); + let mut out = format!( + "{function}() {{\n\ + \x20 local cur=\"${{COMP_WORDS[COMP_CWORD]}}\" prev=\"${{COMP_WORDS[COMP_CWORD-1]}}\"\n\ + \x20 local sub=\"\" words=\"\"\n" + ); + if !spec.subcommands.is_empty() { + let names: Vec<&str> = spec.subcommands.iter().map(|c| c.name).collect(); + out.push_str(&format!( + " if [ \"$COMP_CWORD\" -gt 1 ]; then\n\ + \x20 case \"${{COMP_WORDS[1]}}\" in\n\ + \x20 {}) sub=\"${{COMP_WORDS[1]}}\" ;;\n\ + \x20 esac\n\ + \x20 fi\n", + names.join("|") + )); + } + out.push_str(" case \"$sub\" in\n"); + out.push_str(&format!( + " \"\")\n{} ;;\n", + bash_command(spec, 1) + )); + for sub in spec.subcommands { + out.push_str(&format!( + " {})\n{} ;;\n", + sub.name, + bash_command(sub, 2) + )); + } + out.push_str(&format!( + " esac\n\ + \x20 COMPREPLY=($(compgen -W \"$words\" -- \"$cur\"))\n\ + }}\n\ + complete -o default -F {function} {}\n", + spec.name + )); + out +} + +/// The `case "$prev"` for one command; `first` is the word position right +/// after it. +fn bash_command(command: &Command, first: usize) -> String { + let (choices, open) = command.valued(); + let mut out = String::from(" case \"$prev\" in\n"); + for (spellings, values) in &choices { + out.push_str(&format!( + " {}) words=\"{}\" ;;\n", + spellings.join("|"), + values.join(" ") + )); + } + if !open.is_empty() { + out.push_str(&format!( + " {}) return 0 ;;\n", + open.join("|") + )); + } + let first_words = command.first_words(); + out.push_str(&format!( + " *) words=\"{}\"", + command.words().join(" ") + )); + if !first_words.is_empty() { + out.push_str(&format!( + "\n [ \"$COMP_CWORD\" -eq {first} ] && words=\"$words {}\"", + first_words.join(" ") + )); + } + out.push_str(" ;;\n esac\n"); + out +} + +// --------------------------------------------------------------------------- +// zsh: the same logic over zsh's own `$words` (1-based) and `$CURRENT` +// --------------------------------------------------------------------------- + +fn zsh(spec: &Command) -> String { + let function = format!("_{}", spec.name.replace('-', "_")); + let mut out = format!( + "{function}() {{\n\ + \x20 local prev=\"${{words[CURRENT-1]}}\" sub=\"\"\n\ + \x20 local -a found\n" + ); + if !spec.subcommands.is_empty() { + let names: Vec<&str> = spec.subcommands.iter().map(|c| c.name).collect(); + out.push_str(&format!( + " if (( CURRENT > 2 )); then\n\ + \x20 case \"${{words[2]}}\" in\n\ + \x20 {}) sub=\"${{words[2]}}\" ;;\n\ + \x20 esac\n\ + \x20 fi\n", + names.join("|") + )); + } + out.push_str(" case \"$sub\" in\n"); + out.push_str(&format!( + " \"\")\n{} ;;\n", + zsh_command(spec, 2) + )); + for sub in spec.subcommands { + out.push_str(&format!( + " {})\n{} ;;\n", + sub.name, + zsh_command(sub, 3) + )); + } + out.push_str(&format!( + " esac\n\ + \x20 compadd -a found\n\ + }}\n\ + compdef {function} {}\n", + spec.name + )); + out +} + +/// The `case "$prev"` for one command; `first` is the `$CURRENT` right after +/// it. After a path flag `_files` completes; after free text, nothing. +fn zsh_command(command: &Command, first: usize) -> String { + let mut out = String::from(" case \"$prev\" in\n"); + let mut paths = Vec::new(); + let mut texts = Vec::new(); + for flag in command.flags { + let spellings: Vec<&str> = std::iter::once(flag.long).chain(flag.short).collect(); + match flag.value { + Value::Choice(values) => out.push_str(&format!( + " {}) found=({}) ;;\n", + spellings.join("|"), + values.join(" ") + )), + Value::Path => paths.extend(spellings), + Value::Text => texts.extend(spellings), + Value::None => {} + } + } + if !paths.is_empty() { + out.push_str(&format!( + " {}) _files; return ;;\n", + paths.join("|") + )); + } + if !texts.is_empty() { + out.push_str(&format!(" {}) return ;;\n", texts.join("|"))); + } + out.push_str(&format!( + " *) found=({})", + command.words().join(" ") + )); + let first_words = command.first_words(); + if !first_words.is_empty() { + out.push_str(&format!( + "\n (( CURRENT == {first} )) && found+=({})", + first_words.join(" ") + )); + } + out.push_str(" ;;\n esac\n"); + out +} + +// --------------------------------------------------------------------------- +// fish +// --------------------------------------------------------------------------- + +fn fish(spec: &Command) -> String { + let name = spec.name; + let mut out = format!( + "# {name} completion for fish. Load it with:\n\ + # {name} completions fish | source\n\ + complete -c {name} -f\n" + ); + let subs: Vec<&str> = spec.subcommands.iter().map(|c| c.name).collect(); + let top = if subs.is_empty() { + String::new() + } else { + format!("-n 'not __fish_seen_subcommand_from {}' ", subs.join(" ")) + }; + out.push_str(&fish_flags(name, spec, &top)); + // First place only, as the parser takes them: counted, because + // `__fish_use_subcommand` stays true after a flag (`incode --admin up`). + let first = spec.first_words(); + if !first.is_empty() { + out.push_str(&format!( + "complete -c {name} -n 'test (count (commandline -opc)) -eq 1' -a '{}'\n", + first.join(" ") + )); + } + for sub in spec.subcommands { + let inside = format!("-n '__fish_seen_subcommand_from {}' ", sub.name); + out.push_str(&fish_flags(name, sub, &inside)); + if !sub.verbs.is_empty() { + out.push_str(&format!( + "complete -c {name} -n 'test (count (commandline -opc)) -eq 2; and \ + __fish_seen_subcommand_from {}' -a '{}'\n", + sub.name, + sub.verbs.join(" ") + )); + } + } + out +} + +fn fish_flags(name: &str, command: &Command, condition: &str) -> String { + let mut out = String::new(); + for flag in command.flags { + let mut line = format!( + "complete -c {name} {condition}-l {}", + flag.long.trim_start_matches('-') + ); + if let Some(short) = flag.short { + line.push_str(&format!(" -s {}", short.trim_start_matches('-'))); + } + match flag.value { + Value::None => {} + Value::Choice(values) => line.push_str(&format!(" -x -a '{}'", values.join(" "))), + Value::Path => line.push_str(" -r -F"), + Value::Text => line.push_str(" -x"), + } + line.push_str(&format!(" -d '{}'", flag.help.replace('\'', "\\'"))); + out.push_str(&line); + out.push('\n'); + } + out +} + +// --------------------------------------------------------------------------- +// PowerShell +// --------------------------------------------------------------------------- + +fn powershell(spec: &Command) -> String { + let name = spec.name; + let list = |words: &[&str]| -> String { + words + .iter() + .map(|w| format!("'{w}'")) + .collect::>() + .join(",") + }; + let mut out = format!( + "# {name} completion for PowerShell. Load it with:\n\ + # {name} completions powershell | Out-String | Invoke-Expression\n\ + Register-ArgumentCompleter -Native -CommandName '{name}','{name}.exe' -ScriptBlock {{\n\ + \x20 param($wordToComplete, $commandAst, $cursorPosition)\n\ + \x20 $before = @($commandAst.CommandElements |\n\ + \x20 Where-Object {{ $_.Extent.EndOffset -lt $cursorPosition -or\n\ + \x20 ($wordToComplete -eq '' -and $_.Extent.EndOffset -le $cursorPosition) }} |\n\ + \x20 ForEach-Object {{ $_.Extent.Text }})\n\ + \x20 $count = $before.Count\n\ + \x20 $prev = $before[$count - 1]\n\ + \x20 $sub = ''\n" + ); + if !spec.subcommands.is_empty() { + let names: Vec<&str> = spec.subcommands.iter().map(|c| c.name).collect(); + out.push_str(&format!( + " if ($count -gt 1 -and @({}) -contains $before[1]) {{ $sub = $before[1] }}\n", + list(&names) + )); + } + out.push_str(" $words = @()\n"); + let mut branches = vec![(String::new(), powershell_command(spec, 1, &list))]; + for sub in spec.subcommands { + branches.push((sub.name.to_string(), powershell_command(sub, 2, &list))); + } + for (i, (sub, body)) in branches.iter().enumerate() { + let keyword = if i == 0 { "if" } else { "elseif" }; + out.push_str(&format!( + " {keyword} ($sub -eq '{sub}') {{\n{body} }}\n" + )); + } + out.push_str( + " $words | Where-Object { $_ -like \"$wordToComplete*\" } | ForEach-Object {\n\ + \x20 [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_)\n\ + \x20 }\n\ + }\n", + ); + out +} + +fn powershell_command(command: &Command, first: usize, list: &dyn Fn(&[&str]) -> String) -> String { + let (choices, open) = command.valued(); + let mut out = String::new(); + let mut keyword = "if"; + for (spellings, values) in &choices { + out.push_str(&format!( + " {keyword} (@({}) -contains $prev) {{ $words = @({}) }}\n", + list(spellings), + list(values) + )); + keyword = "elseif"; + } + if !open.is_empty() { + out.push_str(&format!( + " {keyword} (@({}) -contains $prev) {{ return }}\n", + list(&open) + )); + keyword = "elseif"; + } + // With no condition before it, the default is plain statements: a bare + // `{ … }` in PowerShell is a script-block VALUE, written to the output + // instead of run. + let guarded = keyword == "elseif"; + let indent = if guarded { " " } else { " " }; + if guarded { + out.push_str(" else {\n"); + } + out.push_str(&format!("{indent}$words = @({})\n", list(&command.words()))); + let first_words = command.first_words(); + if !first_words.is_empty() { + out.push_str(&format!( + "{indent}if ($count -eq {first}) {{ $words += @({}) }}\n", + list(&first_words) + )); + } + if guarded { + out.push_str(" }\n"); + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + const SUB: Command = Command { + name: "tool", + flags: &[Flag { + long: "--project", + short: None, + value: Value::None, + help: "in this project", + }], + verbs: &["list", "add"], + subcommands: &[], + }; + + const SPEC: Command = Command { + name: "demo", + flags: &[ + Flag { + long: "--mode", + short: Some("-p"), + value: Value::Choice(&["read-only", "write"]), + help: "the mode", + }, + Flag { + long: "--workspace", + short: Some("-w"), + value: Value::Path, + help: "a folder", + }, + ], + verbs: &[], + subcommands: &[SUB], + }; + + #[test] + fn every_shell_gets_a_script_naming_every_word() { + for name in Shell::NAMES { + let shell = Shell::parse(name).expect("a shell"); + let text = script(shell, &SPEC).expect("a script"); + // Flags without their dashes: fish spells them `-l mode`. + for word in [ + "mode", + "read-only", + "write", + "workspace", + "tool", + "list", + "project", + ] { + assert!(text.contains(word), "{name} lacks `{word}`:\n{text}"); + } + } + assert_eq!(Shell::parse("pwsh"), Some(Shell::PowerShell)); + assert_eq!(Shell::parse("cmd"), None); + } + + /// A word that is not a plain token would be shell syntax in the script. + #[test] + fn a_word_that_is_not_plain_is_refused() { + const BAD: Command = Command { + name: "demo", + flags: &[Flag { + long: "--x;rm", + short: None, + value: Value::None, + help: "", + }], + verbs: &[], + subcommands: &[], + }; + for name in Shell::NAMES { + let shell = Shell::parse(name).expect("a shell"); + assert!(script(shell, &BAD).is_err(), "{name}"); + } + } +} diff --git a/src/lib.rs b/src/lib.rs index 2f136cd..7d33c24 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -10,6 +10,7 @@ pub mod auditor; pub mod brief; pub mod budget; pub mod cli; +pub mod completions; pub mod config; pub mod contracts; pub mod custom_commands; diff --git a/src/main.rs b/src/main.rs index f1771b5..3f93ad8 100644 --- a/src/main.rs +++ b/src/main.rs @@ -9,6 +9,7 @@ use std::path::PathBuf; use anyhow::Context; +use incord_code::completions; use incord_code::{IncordCodeConfig, PermissionMode}; const USAGE: &str = "\ @@ -21,6 +22,8 @@ USAGE: incode review [--base ] [-p] Review the current change (see `incode review -h`) incode plugin list | add | update [name] | remove [--project] incode mcp ... (see `incode mcp help`) + incode completions Print a completion script + for that shell (the script says how to load it) OPTIONS: -m, --model Model to use (or set INCODE_MODEL) @@ -81,6 +84,192 @@ OPTIONS: -V, --version Print version "; +/// The command line as `incode completions` completes it. Kept beside +/// [`USAGE`]: the tests hold the two to the same flags, check that +/// [`parse_args`] accepts each one and that every fixed value is one the +/// parser takes, and drive the generated scripts in real shells. +const COMPLETION: completions::Command = { + use completions::{Command, Flag, Value}; + const fn flag( + long: &'static str, + short: Option<&'static str>, + value: Value, + help: &'static str, + ) -> Flag { + Flag { + long, + short, + value, + help, + } + } + const HELP: Flag = flag("--help", Some("-h"), Value::None, "Print help"); + Command { + name: "incode", + flags: &[ + flag("--model", Some("-m"), Value::Text, "Model to use"), + flag("--workspace", Some("-w"), Value::Path, "Workspace root"), + flag( + "--permission-mode", + Some("-p"), + Value::Choice(&[ + "read-only", + "workspace-write", + "danger-full-access", + "prompt", + "allow", + ]), + "What the agent may do", + ), + flag( + "--no-env-filter", + None, + Value::None, + "Pass the full environment", + ), + flag( + "--admin", + None, + Value::None, + "Print the operator's settings", + ), + flag( + "--serve", + None, + Value::None, + "Serve this workspace read-only", + ), + flag("--port", None, Value::Text, "Port for --serve"), + flag( + "--desktop-mcp", + None, + Value::None, + "Desktop MCP server on stdio", + ), + flag( + "--desktop-journal", + None, + Value::Path, + "File the desktop appends to", + ), + flag("--acp", None, Value::None, "Agent Client Protocol on stdio"), + flag("--team-mcp", None, Value::None, "Team MCP server on stdio"), + flag( + "--team-channel", + None, + Value::Path, + "Conversation --team-mcp joins", + ), + flag( + "--sandbox-exec", + None, + Value::None, + "Run under the OS sandbox", + ), + flag( + "--install-tools", + None, + Value::None, + "Install admin.json tools", + ), + flag( + "--tool-server", + None, + Value::None, + "Offer incode's tools over MCP", + ), + flag( + "--check-findings", + None, + Value::Path, + "Check a findings file", + ), + flag("--desktop-stop", None, Value::None, "Halt the desktop"), + flag("--task", Some("-t"), Value::Text, "Run one instruction"), + flag( + "--output-format", + None, + Value::Choice(&["text", "stream-json", "json"]), + "Output of a -t run", + ), + flag( + "--spec-gate", + None, + Value::Choice(&["on", "off"]), + "Spec gate for a -t run", + ), + flag("--resume", Some("-r"), Value::Text, "Continue a session"), + flag( + "--add-dir", + None, + Value::Path, + "Also work in this directory", + ), + HELP, + flag("--version", Some("-V"), Value::None, "Print version"), + ], + verbs: &[], + subcommands: &[ + Command { + name: "update", + flags: &[ + flag("--check", None, Value::None, "Only report a newer release"), + HELP, + ], + verbs: &[], + subcommands: &[], + }, + Command { + name: "review", + flags: &[ + flag("--base", None, Value::Text, "Compare with this ref"), + flag( + "--print", + Some("-p"), + Value::None, + "Print only the findings", + ), + flag("--model", Some("-m"), Value::Text, "Model to review with"), + flag( + "--workspace", + Some("-w"), + Value::Path, + "Repository to review", + ), + HELP, + ], + verbs: &[], + subcommands: &[], + }, + Command { + name: "plugin", + flags: &[flag( + "--project", + None, + Value::None, + "In this workspace's .incode/plugins", + )], + verbs: &["list", "add", "update", "remove", "help"], + subcommands: &[], + }, + Command { + name: "mcp", + flags: &[HELP], + verbs: &[ + "list", "get", "add", "remove", "approve", "login", "logout", "help", + ], + subcommands: &[], + }, + Command { + name: "completions", + flags: &[HELP], + verbs: &completions::Shell::NAMES, + subcommands: &[], + }, + ], + } +}; + fn main() -> anyhow::Result<()> { // The sbx engine's helper (`incode __sbx-enter ...`): confine this // process and exec the command, before any thread starts. Returns at once @@ -663,6 +852,27 @@ fn parse_args(args: impl Iterator) -> anyhow::Result { args.next(); return Ok(Parsed::Mcp(args.collect())); } + // A subcommand, in first place: one shell name, and the script for it is + // the whole answer. + if args.peek().map(String::as_str) == Some("completions") { + args.next(); + let shells = completions::Shell::NAMES.join(", "); + let words: Vec = args.collect(); + let name = match words.as_slice() { + [flag] if flag == "-h" || flag == "--help" => { + return Ok(Parsed::Exit(format!( + "usage: incode completions ({shells})" + ))) + } + [name] => name, + _ => anyhow::bail!("usage: incode completions ({shells})"), + }; + let shell = completions::Shell::parse(name) + .ok_or_else(|| anyhow::anyhow!("no completions for `{name}`. Shells: {shells}"))?; + return completions::script(shell, &COMPLETION) + .map(Parsed::Exit) + .map_err(|e| anyhow::anyhow!(e)); + } while let Some(arg) = args.next() { match arg.as_str() { @@ -1767,4 +1977,418 @@ mod tests { other => panic!("--version must not start a session, got {other:?}"), } } + + // --- completions ------------------------------------------------------- + + use std::collections::BTreeSet; + + /// The flags a help text names: words of `-` and a letter, or `--` and a + /// letter, with the punctuation around them cut off. + fn flags_named_in(text: &str) -> BTreeSet { + text.split(|c: char| c.is_whitespace() || c == ',' || c == '`') + .map(|w| w.trim_matches(|c: char| !(c.is_ascii_alphanumeric() || c == '-'))) + .filter(|w| { + let rest = w.trim_start_matches('-'); + (1..=2).contains(&(w.len() - rest.len())) + && rest.starts_with(|c: char| c.is_ascii_alphabetic()) + }) + .map(str::to_string) + .collect() + } + + fn table_flags(command: &completions::Command) -> BTreeSet { + command + .flags + .iter() + .flat_map(|f| std::iter::once(f.long).chain(f.short)) + .map(str::to_string) + .collect() + } + + fn sub(name: &str) -> &'static completions::Command { + COMPLETION + .subcommands + .iter() + .find(|c| c.name == name) + .unwrap_or_else(|| panic!("no `{name}` in the completion table")) + } + + fn options_of(usage: &str) -> &str { + usage.split_once("OPTIONS:").expect("an OPTIONS section").1 + } + + /// **THE TABLE AND THE HELP NAME THE SAME FLAGS**, both ways: a flag added + /// to `USAGE` and not to the table fails here, and so does the reverse. + #[test] + fn the_completion_table_names_the_flags_the_help_does() { + assert_eq!(table_flags(&COMPLETION), flags_named_in(options_of(USAGE))); + assert_eq!( + table_flags(sub("review")), + flags_named_in(options_of(incord_code::review::USAGE)) + ); + let subcommands: BTreeSet<&str> = USAGE + .lines() + .filter_map(|l| l.trim_start().strip_prefix("incode ")) + .filter_map(|rest| rest.split_whitespace().next()) + .filter(|w| w.starts_with(|c: char| c.is_ascii_lowercase())) + .collect(); + let table: BTreeSet<&str> = COMPLETION.subcommands.iter().map(|c| c.name).collect(); + assert_eq!(table, subcommands); + } + + /// The arguments that give `flag` a value the parser takes: one set per + /// fixed value, else one. + fn with_values(flag: &completions::Flag, spelling: &'static str) -> Vec> { + match flag.value { + completions::Value::None => vec![vec![spelling]], + completions::Value::Text => vec![vec![spelling, "1"]], + completions::Value::Path => vec![vec![spelling, "somewhere"]], + completions::Value::Choice(values) => { + values.iter().map(|v| vec![spelling, *v]).collect() + } + } + } + + /// **EVERY FLAG AND VALUE OFFERED IS ONE THE PROGRAM TAKES.** A flag may + /// still be refused for what it is combined with (`--team-mcp` without + /// `--team-channel`); never as unknown. + #[test] + fn every_completed_flag_and_value_is_accepted_by_its_parser() { + for flag in COMPLETION.flags { + for spelling in std::iter::once(flag.long).chain(flag.short) { + // Taken by `main` before `parse_args`, ahead of every thread. + if spelling == "--sandbox-exec" { + continue; + } + for args in with_values(flag, spelling) { + if let Err(e) = parse(&args) { + assert!(!e.to_string().contains("unknown"), "{args:?}: {e}"); + } + } + } + } + for flag in sub("update").flags { + for spelling in std::iter::once(flag.long).chain(flag.short) { + assert!(parse(&["update", spelling]).is_ok(), "update {spelling}"); + } + } + for flag in sub("review").flags { + for spelling in std::iter::once(flag.long).chain(flag.short) { + for args in with_values(flag, spelling) { + let args: Vec = args.iter().map(|s| (*s).to_string()).collect(); + incord_code::review::Args::parse(&args) + .unwrap_or_else(|e| panic!("review {args:?}: {e}")); + } + } + } + let ws = tempfile::tempdir().expect("ws"); + let data = tempfile::tempdir().expect("data"); + for verb in sub("mcp").verbs { + if let Err(e) = + incord_code::mcp_config::command(&[(*verb).to_string()], ws.path(), data.path()) + { + assert!(!e.starts_with("unknown"), "mcp {verb}: {e}"); + } + } + // `plugin update` fetches every installed plugin, and `plugin` answers + // a wrong verb and a missing argument alike, so its verbs are checked + // against its help — `help` itself by running it. + for verb in sub("plugin").verbs { + if *verb == "help" { + assert_eq!( + incord_code::plugins::cli(&["help".to_string()], ws.path()), + Ok(incord_code::plugins::USAGE.to_string()) + ); + } else { + assert!(incord_code::plugins::USAGE.contains(verb), "plugin {verb}"); + } + } + } + + #[test] + fn completions_prints_a_script_for_each_shell_and_refuses_others() { + for shell in completions::Shell::NAMES { + match parse(&["completions", shell]).expect("a shell") { + Parsed::Exit(script) => { + // fish spells it `-l permission-mode`. + assert!(script.contains("permission-mode"), "{shell}"); + assert!(script.contains("completions"), "{shell}"); + } + other => panic!("{shell}: {other:?}"), + } + } + assert!(matches!( + parse(&["completions", "--help"]), + Ok(Parsed::Exit(_)) + )); + assert!(parse(&["completions"]).is_err()); + assert!(parse(&["completions", "cmd"]).is_err()); + assert!(parse(&["completions", "bash", "zsh"]).is_err()); + } + + /// One completion request and what must come back: `words` ends with the + /// word being completed (`""` after a space). + struct Case { + words: &'static [&'static str], + exactly: Option<&'static [&'static str]>, + includes: &'static [&'static str], + excludes: &'static [&'static str], + } + + const fn case( + words: &'static [&'static str], + exactly: Option<&'static [&'static str]>, + includes: &'static [&'static str], + excludes: &'static [&'static str], + ) -> Case { + Case { + words, + exactly, + includes, + excludes, + } + } + + /// The same requests for every shell, run in an empty folder so a file + /// name never stands in for a completion. + const CASES: &[Case] = &[ + case( + &["incode", "--perm"], + Some(&["--permission-mode"]), + &[], + &[], + ), + case( + &["incode", "-p", ""], + Some(&[ + "read-only", + "workspace-write", + "danger-full-access", + "prompt", + "allow", + ]), + &[], + &[], + ), + case( + &["incode", ""], + None, + &["update", "review", "plugin", "mcp", "completions"], + &[], + ), + case(&["incode", "--mo"], None, &["--model"], &[]), + case( + &["incode", "mcp", ""], + None, + &["login", "logout"], + &["--model"], + ), + case(&["incode", "mcp", "list", ""], None, &[], &["login"]), + // Prefixes, not a bare `--`: PowerShell reads `--` as its own + // end-of-parameters token and asks no completer for it. + case(&["incode", "review", "--b"], Some(&["--base"]), &[], &[]), + case(&["incode", "review", "--ad"], Some(&[]), &[], &[]), + case(&["incode", "-w", ""], Some(&[]), &[], &[]), + case(&["incode", "--admin", "up"], None, &[], &["update"]), + case( + &["incode", "completions", ""], + None, + &["bash", "zsh", "fish", "powershell"], + &[], + ), + case( + &["incode", "--output-format", "s"], + Some(&["stream-json"]), + &[], + &[], + ), + ]; + + fn check(shell: &str, case: &Case, got: &[String]) { + let got: BTreeSet<&str> = got.iter().map(String::as_str).collect(); + if let Some(exactly) = case.exactly { + let want: BTreeSet<&str> = exactly.iter().copied().collect(); + assert_eq!(got, want, "{shell} {:?}", case.words); + } + for word in case.includes { + assert!( + got.contains(word), + "{shell} {:?} lacks {word}: {got:?}", + case.words + ); + } + for word in case.excludes { + assert!( + !got.contains(word), + "{shell} {:?} offers {word}: {got:?}", + case.words + ); + } + } + + /// Run `program args` in `dir` with `input` on stdin; its stdout lines. + fn run_lines( + program: &std::path::Path, + args: &[&str], + dir: &std::path::Path, + input: &str, + ) -> Vec { + use std::io::Write as _; + let mut child = std::process::Command::new(program) + .args(args) + .current_dir(dir) + .stdin(std::process::Stdio::piped()) + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .spawn() + .unwrap_or_else(|e| panic!("start {}: {e}", program.display())); + child + .stdin + .take() + .expect("stdin") + .write_all(input.as_bytes()) + .expect("write stdin"); + let out = child.wait_with_output().expect("wait"); + assert!( + out.status.success(), + "{} {args:?}: {}", + program.display(), + String::from_utf8_lossy(&out.stderr) + ); + String::from_utf8_lossy(&out.stdout) + .lines() + .map(|l| l.trim_end().to_string()) + .filter(|l| !l.is_empty()) + .collect() + } + + /// `name` where it can be run, or `None`. On Windows `bash` is Git for + /// Windows' (as `shell_choice` finds it): the `bash.exe` in the Windows + /// directory is the WSL launcher. + fn shell_program(name: &str) -> Option { + let path = std::env::var_os("PATH")?; + let exe = if cfg!(windows) { + format!("{name}.exe") + } else { + name.to_string() + }; + if cfg!(windows) && name == "bash" { + return std::env::split_paths(&path) + .filter(|dir| dir.join("git.exe").is_file()) + .flat_map(|dir| [dir.join("../bin/bash.exe"), dir.join("../../bin/bash.exe")]) + .find(|candidate| candidate.is_file()); + } + std::env::split_paths(&path) + .map(|dir| dir.join(&exe)) + .find(|candidate| candidate.is_file()) + } + + fn script_for(shell: completions::Shell) -> String { + completions::script(shell, &COMPLETION).expect("a script") + } + + /// **BASH COMPLETES WHAT THE TABLE SAYS**, run by bash itself. + #[test] + fn bash_completes_from_the_table() { + let Some(bash) = shell_program("bash") else { + eprintln!("bash_completes_from_the_table: SKIPPED (no bash)"); + return; + }; + let dir = tempfile::tempdir().expect("empty dir"); + let input = format!( + "{}\nCOMP_WORDS=(\"$@\"); COMP_CWORD=$(( ${{#COMP_WORDS[@]}} - 1 )); _incode\n\ + printf '%s\\n' \"${{COMPREPLY[@]}}\"\n", + script_for(completions::Shell::Bash) + ); + for case in CASES { + let mut args = vec!["-s", "--"]; + args.extend(case.words); + check("bash", case, &run_lines(&bash, &args, dir.path(), &input)); + } + } + + /// PowerShell's own completion engine (`TabExpansion2`) asks the + /// registered completer, as at a prompt. + #[test] + fn powershell_completes_from_the_table() { + let Some(program) = shell_program("pwsh").or_else(|| shell_program("powershell")) else { + eprintln!("powershell_completes_from_the_table: SKIPPED (no PowerShell)"); + return; + }; + let dir = tempfile::tempdir().expect("empty dir"); + let file = tempfile::tempdir().expect("script dir"); + for case in CASES { + let line = case.words.join(" "); + let script = format!( + "{}\n$line = '{line}'\n\ + (TabExpansion2 -inputScript $line -cursorColumn $line.Length).CompletionMatches |\n\ + \x20 ForEach-Object {{ $_.CompletionText }}\n", + script_for(completions::Shell::PowerShell) + ); + let path = file.path().join("case.ps1"); + std::fs::write(&path, script).expect("write script"); + let path = path.to_string_lossy().into_owned(); + let got = run_lines( + &program, + &[ + "-NoProfile", + "-NonInteractive", + "-ExecutionPolicy", + "Bypass", + "-File", + &path, + ], + dir.path(), + "", + ); + check("powershell", case, &got); + } + } + + /// fish's own engine (`complete -C`), where fish is installed. + #[test] + fn fish_completes_from_the_table() { + let Some(fish) = shell_program("fish") else { + eprintln!("fish_completes_from_the_table: SKIPPED (no fish)"); + return; + }; + let dir = tempfile::tempdir().expect("empty dir"); + for case in CASES { + let line = case.words.join(" "); + let input = format!( + "{}\ncomplete -C '{line}'\n", + script_for(completions::Shell::Fish) + ); + let got: Vec = run_lines(&fish, &[], dir.path(), &input) + .into_iter() + .map(|l| l.split('\t').next().unwrap_or("").to_string()) + .collect(); + check("fish", case, &got); + } + } + + /// The zsh function, where zsh is installed, with zsh's `compadd`, + /// `_files` and `compdef` stood in for: they belong to the completion + /// system, which needs a terminal. `compadd` keeps what matches the word, + /// as the real one does. + #[test] + fn zsh_completes_from_the_table() { + let Some(zsh) = shell_program("zsh") else { + eprintln!("zsh_completes_from_the_table: SKIPPED (no zsh)"); + return; + }; + let dir = tempfile::tempdir().expect("empty dir"); + let input = format!( + "compdef() {{ : }}\n_files() {{ : }}\n\ + compadd() {{ local w; for w in \"${{(@P)2}}\"; do\n\ + \x20 [[ $w == \"${{words[CURRENT]}}\"* ]] && print -r -- \"$w\"; done }}\n\ + {}\nwords=(\"$@\"); CURRENT=$#; _incode; true\n", + script_for(completions::Shell::Zsh) + ); + for case in CASES { + let mut args = vec!["-s", "--"]; + args.extend(case.words); + check("zsh", case, &run_lines(&zsh, &args, dir.path(), &input)); + } + } } From 3d8a8aa9371eed5c93c99bdae93c9ee0173d4482 Mon Sep 17 00:00:00 2001 From: blockmandev <194144408+blockmandev@users.noreply.github.com> Date: Wed, 21 Oct 2026 18:46:21 -0600 Subject: [PATCH 2/2] completions tests: a shell CI has may not be skipped The shell tests skip where their shell is missing, so a green run did not show the fish or zsh script had run at all. INCODE_TEST_SHELLS names the shells a runner must have; one listed and not found fails the test. CI sets it per runner: Linux bash,fish,zsh,powershell; macOS bash,zsh,powershell; Windows bash,powershell. Control: requiring fish here, where it is not installed, fails fish_completes_from_the_table. --- .github/workflows/ci.yml | 4 ++++ src/main.rs | 20 ++++++++++++++++---- 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3fd0a11..055b648 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -84,7 +84,11 @@ jobs: git config --global user.name "ci" - run: cargo clippy --all-targets - run: cargo test --lib + # The completion tests skip a shell that is missing; here every shell + # the runner has is required, so a skip cannot pass for a run. - run: cargo test --bins + env: + INCODE_TEST_SHELLS: ${{ runner.os == 'Linux' && 'bash,fish,zsh,powershell' || runner.os == 'macOS' && 'bash,zsh,powershell' || 'bash,powershell' }} # incode's commands under `sandbox_engine = "sbx"`, for real (Linux; # it says it skipped elsewhere). - run: cargo test --test sbx_engine diff --git a/src/main.rs b/src/main.rs index 3f93ad8..45c92b3 100644 --- a/src/main.rs +++ b/src/main.rs @@ -2283,6 +2283,18 @@ mod tests { .find(|candidate| candidate.is_file()) } + /// A shell test with no shell to run: skipped, and said — unless + /// `INCODE_TEST_SHELLS` (CI sets it per runner) lists that shell, when a + /// skip would hide that the script was never run, so it fails. + fn skip(test: &str, shell: &str) { + let required = std::env::var("INCODE_TEST_SHELLS").unwrap_or_default(); + assert!( + !required.split(',').any(|s| s.trim() == shell), + "{test}: {shell} is required here (INCODE_TEST_SHELLS={required}) and was not found" + ); + eprintln!("{test}: SKIPPED (no {shell})"); + } + fn script_for(shell: completions::Shell) -> String { completions::script(shell, &COMPLETION).expect("a script") } @@ -2291,7 +2303,7 @@ mod tests { #[test] fn bash_completes_from_the_table() { let Some(bash) = shell_program("bash") else { - eprintln!("bash_completes_from_the_table: SKIPPED (no bash)"); + skip("bash_completes_from_the_table", "bash"); return; }; let dir = tempfile::tempdir().expect("empty dir"); @@ -2312,7 +2324,7 @@ mod tests { #[test] fn powershell_completes_from_the_table() { let Some(program) = shell_program("pwsh").or_else(|| shell_program("powershell")) else { - eprintln!("powershell_completes_from_the_table: SKIPPED (no PowerShell)"); + skip("powershell_completes_from_the_table", "powershell"); return; }; let dir = tempfile::tempdir().expect("empty dir"); @@ -2349,7 +2361,7 @@ mod tests { #[test] fn fish_completes_from_the_table() { let Some(fish) = shell_program("fish") else { - eprintln!("fish_completes_from_the_table: SKIPPED (no fish)"); + skip("fish_completes_from_the_table", "fish"); return; }; let dir = tempfile::tempdir().expect("empty dir"); @@ -2374,7 +2386,7 @@ mod tests { #[test] fn zsh_completes_from_the_table() { let Some(zsh) = shell_program("zsh") else { - eprintln!("zsh_completes_from_the_table: SKIPPED (no zsh)"); + skip("zsh_completes_from_the_table", "zsh"); return; }; let dir = tempfile::tempdir().expect("empty dir");