Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
128 changes: 128 additions & 0 deletions command-signatures/json/yc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
{
"name": "yc",
"description": "Command line interface for Yandex Cloud",
"args": {
"name": "command",
"description": "Yandex Cloud command or argument",
"isVariadic": true,
"isOptional": true,
"generatorName": "yc_builtin_completion",
"skipGeneratorValidation": true
},
"options": [
{
"name": "--profile",
"description": "Set the custom configuration file",
"isPersistent": true,
"args": {
"name": "PROFILE"
}
},
{
"name": "--debug",
"description": "Debug logging",
"isPersistent": true
},
{
"name": "--debug-grpc",
"description": "Debug gRPC logging. Very verbose, used for debugging connection problems",
"isPersistent": true
},
{
"name": "--no-user-output",
"description": "Disable printing user intended output to stderr",
"isPersistent": true
},
{
"name": "--retry",
"description": "Set the number of gRPC retry attempts (0 disables, negative means infinite)",
"isPersistent": true,
"args": {
"name": "ATTEMPTS"
}
},
{
"name": "--cloud-id",
"description": "Set the ID of the cloud to use",
"isPersistent": true,
"args": {
"name": "CLOUD_ID"
}
},
{
"name": "--folder-id",
"description": "Set the ID of the folder to use",
"isPersistent": true,
"args": {
"name": "FOLDER_ID"
}
},
{
"name": "--folder-name",
"description": "Set the name of the folder to use (will be resolved to id)",
"isPersistent": true,
"args": {
"name": "FOLDER_NAME"
}
},
{
"name": "--endpoint",
"description": "Set the Cloud API endpoint (host:port)",
"isPersistent": true,
"args": {
"name": "ENDPOINT"
}
},
{
"name": "--token",
"description": "Set the OAuth token to use",
"isPersistent": true,
"args": {
"name": "TOKEN"
}
},
{
"name": "--impersonate-service-account-id",
"description": "Set the ID of the service account to impersonate",
"isPersistent": true,
"args": {
"name": "SERVICE_ACCOUNT_ID"
}
},
{
"name": "--no-browser",
"description": "Disable opening browser for authentication",
"isPersistent": true
},
{
"name": "--format",
"description": "Set the output format",
"isPersistent": true,
"args": {
"name": "FORMAT",
"suggestions": [
"text",
"yaml",
"json",
"json-rest"
]
}
},
{
"name": "--jq",
"description": "Query to select values from the response using jq syntax",
"isPersistent": true,
"args": {
"name": "EXPRESSION"
}
},
{
"name": [
"-h",
"--help"
],
"description": "Display help for the command",
"isPersistent": true
}
]
}
2 changes: 2 additions & 0 deletions command-signatures/src/generators/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ mod tmux;
mod tmuxinator;
mod tsh;
mod uv;
mod yc;

/// Used for gcloud and gsutil completions.
mod gcloud;
Expand Down Expand Up @@ -160,6 +161,7 @@ pub fn dynamic_command_signature_data() -> HashMap<String, DynamicCompletionData
uv::generator(),
gcloud::gcloud_generators(),
gcloud::gsutil_generators(),
yc::generator(),
];

HashMap::from_iter(command_signature_generators.map(Into::into))
Expand Down
148 changes: 148 additions & 0 deletions command-signatures/src/generators/yc.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
//! `yc` is the Yandex Cloud CLI. Like `kubectl` and `oc`, it is Cobra-based, so its completions are
//! produced by shelling out to the CLI's own hidden completion command (`yc __complete`). Driving
//! completions from the installed CLI keeps them in sync with the user's `yc` version instead of
//! hand-maintaining the full command tree in a static spec.
use itertools::Itertools;
use warp_completion_metadata::{
CommandBuilder, CommandSignatureGenerators, Generator, GeneratorResults,
GeneratorResultsCollector, Suggestion,
};

/// Builds the `yc __complete ...` command that asks the installed CLI for completions of the command
/// being typed. The final line of Cobra's completion output is a `:<directive>` metadata line, so it
/// is stripped with `sed '$d'`; `CommandBuilder::pipe` also discards the first command's stderr,
/// which is where Cobra writes its "Completion ended with directive" trailer.
fn yc_completion_command(
tokens: &[&str],
has_trailing_whitespace: bool,
env_vars: &[String],
) -> CommandBuilder {
let env_vars_str = env_vars.iter().join(" ");
let mut generation_command = vec![&env_vars_str, "yc", "__complete"]
.into_iter()
.chain(
// Skip the first token, which is just "yc".
tokens.iter().skip(1).cloned(),
)
.collect_vec();
// Cobra needs an explicit empty argument to complete a fresh token.
if has_trailing_whitespace {
generation_command.push("\"\"");
}
CommandBuilder::pipe(
CommandBuilder::single_command(generation_command.join(" ")),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ [IMPORTANT] [SECURITY] This joins unescaped user-supplied tokens into the shell command Warp runs for completions, so a token like $(touch /tmp/yc-pwn) or foo;... can execute during Tab completion; shell-escape each token/env assignment or build the subprocess without shell interpolation before joining.

CommandBuilder::single_command("sed '$d'"),
)
}

/// Parses `yc __complete` output into suggestions. Cobra emits one completion per line as
/// `value<TAB>description` (the description is omitted when empty), so each line is split on the
/// first tab to carry the description through. Blank lines, the `:<directive>` metadata line, and
/// the "Completion ended" trailer are dropped, and any error output yields no suggestions. The
/// ordering from the CLI is preserved.
fn yc_completion_post_process(output: &str) -> GeneratorResults {
if output.contains("ERROR:") || output.contains("error:") {
return GeneratorResults::default();
}
output
.lines()
.filter(|line| {
let trimmed = line.trim();
!trimmed.is_empty()
&& !trimmed.starts_with(':')
&& !trimmed.starts_with("Completion ended")
})
.map(|line| match line.split_once('\t') {
Some((value, description)) if !description.trim().is_empty() => {
Suggestion::with_description(value.trim(), description.trim())
}
Some((value, _)) => Suggestion::new(value.trim()),
None => Suggestion::new(line.trim()),
})
.collect_ordered_results()
}

pub fn generator() -> CommandSignatureGenerators {
CommandSignatureGenerators::new("yc").add_generator(
"yc_builtin_completion",
Generator::command_from_tokens(yc_completion_command, yc_completion_post_process),
)
}

#[cfg(test)]
mod tests {
use super::*;
use warp_completion_metadata::Shell;

#[test]
fn test_completion_command_completes_fresh_token() {
let cmd = yc_completion_command(&["yc"], true, &[]);
assert_eq!(
cmd.build(Shell::Posix),
r#" yc __complete "" 2>/dev/null | sed '$d'"#
);
}

#[test]
fn test_completion_command_completes_nested_subcommand() {
let cmd = yc_completion_command(&["yc", "compute", "instance"], true, &[]);
assert_eq!(
cmd.build(Shell::Posix),
r#" yc __complete compute instance "" 2>/dev/null | sed '$d'"#
);
}

#[test]
fn test_completion_command_completes_partial_token() {
// No trailing whitespace: the last token is a prefix Cobra should match, not a new token.
let cmd = yc_completion_command(&["yc", "comp"], false, &[]);
assert_eq!(
cmd.build(Shell::Posix),
r#" yc __complete comp 2>/dev/null | sed '$d'"#
);
}

#[test]
fn test_post_process_parses_descriptions_and_filters_metadata() {
let results = yc_completion_post_process(
"compute\tManage Compute Cloud resources\nconfig\tManage CLI config\n:4\nCompletion ended with directive: ShellCompDirectiveNoFileComp\n",
);
assert!(results.is_ordered);
assert_eq!(
results
.suggestions
.into_iter()
.map(|suggestion| (suggestion.exact_string, suggestion.description))
.collect::<Vec<_>>(),
vec![
(
"compute".to_owned(),
Some("Manage Compute Cloud resources".to_owned())
),
("config".to_owned(), Some("Manage CLI config".to_owned())),
]
);
}

#[test]
fn test_post_process_handles_missing_description() {
// A line with no tab, and a line with a tab but an empty description, both yield a
// description-less suggestion.
let results = yc_completion_post_process("vpc\ndns\t\n");
assert_eq!(
results
.suggestions
.into_iter()
.map(|suggestion| (suggestion.exact_string, suggestion.description))
.collect::<Vec<_>>(),
vec![("vpc".to_owned(), None), ("dns".to_owned(), None)]
);
}

#[test]
fn test_post_process_returns_nothing_on_error() {
let results =
yc_completion_post_process("ERROR: failed to resolve endpoint: connection refused");
assert!(results.suggestions.is_empty());
}
}
Loading