Skip to content
Open
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
654 changes: 654 additions & 0 deletions command-signatures/src/lib.rs

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion completion-metadata/src/fig_types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -528,7 +528,7 @@ impl From<ParserDirectives> for crate::ParserDirectives {
}

/// Unescape HTML entities that Fig allows in `name` or `description` fields.
fn html_unescape(input: String) -> String {
pub(crate) fn html_unescape(input: String) -> String {
match html_escape::decode_html_entities(&input) {
// If the input is returned as-is, it contains no HTML entities so we can reuse the owned String.
Cow::Borrowed(_) => input,
Expand Down
1 change: 1 addition & 0 deletions completion-metadata/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
mod command_builder;
pub mod fig_types;
mod signature;
pub mod validation;

use serde::{Deserialize, Serialize};
pub use signature::*;
Expand Down
2 changes: 1 addition & 1 deletion completion-metadata/src/signature.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ impl Signature {
/// * A single dash followed by a single character (`-h`, `-v`, etc.) is short-hand, unless the second character is also a dash.
/// * A single dash followed by multiple characters (`-version`) is long-hand
/// * Two dashes followed by 0 or more characters is long-hand
fn is_short_hand_flag(name: &str) -> bool {
pub(crate) fn is_short_hand_flag(name: &str) -> bool {
name.len() == 2 && name.starts_with('-') && name != "--"
}

Expand Down
176 changes: 176 additions & 0 deletions completion-metadata/src/validation.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,176 @@
//! Shared metadata validation for handwritten command specs.
//!
//! These checks operate on [`fig_types::Command`] before it is converted into [`crate::Signature`],
//! because conversion loses the source option boundaries (and, for persistent options, copies
//! options into descendant nodes) that precise diagnostics depend on.
//!
//! The recursive command/option traversal here is intentionally reusable: additional rules over
//! the same authored command tree (such as duplicate full option names) can be added alongside
//! [`find_short_flag_conflicts`] without re-implementing traversal.

use crate::fig_types::{html_unescape, Command, CommandOption};
use crate::signature::is_short_hand_flag;
use std::collections::{BTreeMap, HashSet};

/// A single option entry that claims a short flag involved in a [`ShortFlagConflict`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ShortFlagClaimant {
/// The option's zero-based position within its command node's authored `options` array.
pub index: usize,
/// The complete, raw `name` array exactly as authored in the JSON (before HTML-entity
/// unescaping).
pub names: Vec<String>,
}

/// A short flag claimed by two or more distinct option entries directly authored on the same
/// command or subcommand node.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ShortFlagConflict {
/// The canonical command path, using the first declared name at each command level.
pub command_path: Vec<String>,
/// The normalized short flag (e.g. `-h`), after HTML-entity unescaping.
pub flag: String,
/// Every distinct conflicting option, in source order.
pub claimants: Vec<ShortFlagClaimant>,
}

impl ShortFlagConflict {
/// Formats a deterministic, human-readable diagnostic for this conflict.
///
/// `file` is the (repository-relative) path of the JSON file the conflict was found in; it is
/// supplied by the caller because `fig_types::Command` does not know its own source file.
pub fn describe(&self, file: &str) -> String {
let path = self.command_path.join(" ");
let options = self
.claimants
.iter()
.map(|claimant| {
format!(
"#{} {}",
claimant.index + 1,
format_name_array(&claimant.names)
)
})
.collect::<Vec<_>>();
format!(
"{file}: command \"{path}\": duplicate short flag \"{flag}\" is used by options {options}",
file = file,
path = path,
flag = self.flag,
options = join_with_and(&options),
)
}
}

fn format_name_array(names: &[String]) -> String {
let entries = names
.iter()
.map(|name| format!("{name:?}"))
.collect::<Vec<_>>()
.join(", ");
format!("[{entries}]")
}

/// Joins strings such that `["a"]` -> `"a"`, `["a", "b"]` -> `"a and b"`, and
/// `["a", "b", "c"]` -> `"a, b, and c"`.
fn join_with_and(parts: &[String]) -> String {
match parts {
[] => String::new(),
[only] => only.clone(),
[first, second] => format!("{first} and {second}"),
_ => {
let (last, rest) = parts.split_last().expect("parts has more than 2 elements");
format!("{}, and {}", rest.join(", "), last)
}
}
}

/// Recursively finds every duplicate-short-flag conflict directly authored on `command` and its
/// subcommands.
///
/// Each command or subcommand node is treated as an independent option namespace: sibling
/// subcommands, and a parent and its children, may reuse the same short flag without conflict.
/// Only options directly declared on a node are considered; persistent options are not yet copied
/// into descendants at this stage, so they are not double-counted as new authored definitions.
pub fn find_short_flag_conflicts(command: &Command) -> Vec<ShortFlagConflict> {
let mut conflicts = Vec::new();
walk(command, &[], &mut conflicts);
conflicts
}

fn walk(command: &Command, path_prefix: &[String], conflicts: &mut Vec<ShortFlagConflict>) {
let mut path = path_prefix.to_vec();
// A command/subcommand's `name` array holds aliases for one namespace; the first declared
// name is used as the canonical path segment.
path.push(command.name.first().cloned().unwrap_or_default());

conflicts.extend(conflicts_in_options(&command.options, &path));

for subcommand in &command.subcommands {
walk(subcommand, &path, conflicts);
}
}

fn conflicts_in_options(options: &[CommandOption], path: &[String]) -> Vec<ShortFlagConflict> {
let mut claimants_by_flag: BTreeMap<String, Vec<ShortFlagClaimant>> = BTreeMap::new();

for (index, option) in options.iter().enumerate() {
// Repeated spellings of the same normalized flag within one option's `name` array
// describe one option, so it must only be counted once per flag here.
let mut flags_claimed_by_this_option = HashSet::new();
for name in &option.name {
let normalized = html_unescape(name.clone());
if is_short_hand_flag(&normalized)
&& flags_claimed_by_this_option.insert(normalized.clone())
{
claimants_by_flag
.entry(normalized)
.or_default()
.push(ShortFlagClaimant {
index,
names: option.name.clone(),
});
}
}
}

claimants_by_flag
.into_iter()
.filter(|(_, claimants)| claimants.len() > 1)
.map(|(flag, claimants)| ShortFlagConflict {
command_path: path.to_vec(),
flag,
claimants,
})
.collect()
}

// Focused valid/invalid fixture coverage for this rule lives in
// `completion-metadata/tests/duplicate_short_flags.rs`, which exercises the fixtures under
// `completion-metadata/tests/fixtures/duplicate_short_flags/`.
#[cfg(test)]
mod tests {
use super::*;

#[test]
fn join_with_and_formats_by_count() {
assert_eq!(join_with_and(&[]), "");
assert_eq!(join_with_and(&["a".to_string()]), "a");
assert_eq!(
join_with_and(&["a".to_string(), "b".to_string()]),
"a and b"
);
assert_eq!(
join_with_and(&["a".to_string(), "b".to_string(), "c".to_string()]),
"a, b, and c"
);
}

#[test]
fn format_name_array_uses_debug_quoting() {
assert_eq!(
format_name_array(&["-d".to_string(), "--device-id".to_string()]),
"[\"-d\", \"--device-id\"]"
);
}
}
145 changes: 145 additions & 0 deletions completion-metadata/tests/duplicate_short_flags.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
//! Focused valid/invalid fixture coverage for the duplicate-short-flag validation rule
//! (https://github.com/warpdotdev/command-signatures/issues/400).
//!
//! Fixtures live under `tests/fixtures/duplicate_short_flags/`.

use warp_completion_metadata::fig_types::Command;
use warp_completion_metadata::validation::{find_short_flag_conflicts, ShortFlagConflict};

fn load(fixture_name: &str) -> Command {
let path = format!(
"{}/tests/fixtures/duplicate_short_flags/{fixture_name}",
env!("CARGO_MANIFEST_DIR")
);
let json = std::fs::read_to_string(&path)
.unwrap_or_else(|err| panic!("failed to read fixture {path}: {err}"));
serde_json::from_str(&json)
.unwrap_or_else(|err| panic!("fixture {path} failed to deserialize: {err}"))
}

fn conflicts_for(fixture_name: &str) -> Vec<ShortFlagConflict> {
find_short_flag_conflicts(&load(fixture_name))
}

#[test]
fn two_distinct_options_conflict() {
let conflicts = conflicts_for("invalid_two_distinct_options.json");
assert_eq!(conflicts.len(), 1);
let conflict = &conflicts[0];
assert_eq!(conflict.command_path, vec!["flutter", "assemble"]);
assert_eq!(conflict.flag, "-d");
assert_eq!(
conflict
.claimants
.iter()
.map(|c| c.index)
.collect::<Vec<_>>(),
vec![0, 2]
);
assert_eq!(
conflict.describe("command-signatures/json/flutter.json"),
"command-signatures/json/flutter.json: command \"flutter assemble\": duplicate short flag \"-d\" is used by options #1 [\"-d\", \"--device-id\"] and #3 [\"-d\", \"--define\"]"
);
}

#[test]
fn identical_name_arrays_are_distinguished_by_position() {
let conflicts = conflicts_for("invalid_identical_name_arrays.json");
assert_eq!(conflicts.len(), 1);
assert_eq!(
conflicts[0]
.claimants
.iter()
.map(|c| c.index)
.collect::<Vec<_>>(),
vec![0, 1]
);
assert_eq!(
conflicts[0].describe("tool.json"),
"tool.json: command \"tool\": duplicate short flag \"-v\" is used by options #1 [\"-v\", \"--verbose\"] and #2 [\"-v\", \"--verbose\"]"
);
}

#[test]
fn three_claimants_produce_one_diagnostic_listing_all_three() {
let conflicts = conflicts_for("invalid_three_claimants.json");
assert_eq!(conflicts.len(), 1);
assert_eq!(conflicts[0].claimants.len(), 3);
assert_eq!(
conflicts[0].describe("tool.json"),
"tool.json: command \"tool\": duplicate short flag \"-t\" is used by options #1 [\"-t\", \"--type-a\"], #2 [\"-t\", \"--type-b\"], and #3 [\"-t\", \"--type-c\"]"
);
}

#[test]
fn nested_subcommand_conflict_reports_full_root_to_leaf_path() {
let conflicts = conflicts_for("invalid_nested_subcommand.json");
assert_eq!(conflicts.len(), 1);
assert_eq!(conflicts[0].command_path, vec!["tool", "group", "leaf"]);
}

#[test]
fn repeated_internal_spelling_counts_the_option_once() {
let conflicts = conflicts_for("invalid_repeated_internal_spelling.json");
assert_eq!(conflicts.len(), 1);
assert_eq!(conflicts[0].claimants.len(), 2);
assert_eq!(
conflicts[0]
.claimants
.iter()
.map(|c| c.index)
.collect::<Vec<_>>(),
vec![0, 1]
);
}

#[test]
fn html_escaped_spelling_conflicts_with_literal_form() {
let conflicts = conflicts_for("invalid_html_escaped_vs_literal.json");
assert_eq!(conflicts.len(), 1);
assert_eq!(conflicts[0].flag, "-h");
assert_eq!(
conflicts[0].describe("tool.json"),
"tool.json: command \"tool\": duplicate short flag \"-h\" is used by options #1 [\"&#45;h\", \"--help\"] and #2 [\"-h\", \"--history\"]"
);
}

#[test]
fn command_alias_names_share_one_namespace() {
let conflicts = conflicts_for("invalid_command_alias_namespace.json");
assert_eq!(conflicts.len(), 1);
// The conflict is reported once (not once per alias), and the canonical path uses only the
// first declared name.
assert_eq!(conflicts[0].command_path, vec!["foo"]);
}

#[test]
fn distinct_short_flags_do_not_conflict() {
assert!(conflicts_for("valid_distinct_short_flags.json").is_empty());
}

#[test]
fn parent_and_child_may_reuse_a_short_flag() {
assert!(conflicts_for("valid_root_and_child_reuse.json").is_empty());
}

#[test]
fn sibling_subcommands_may_reuse_a_short_flag() {
assert!(conflicts_for("valid_sibling_subcommands_reuse.json").is_empty());
}

#[test]
fn unrelated_top_level_fixtures_may_reuse_a_short_flag() {
assert!(conflicts_for("valid_unrelated_top_level_a.json").is_empty());
assert!(conflicts_for("valid_unrelated_top_level_b.json").is_empty());
}

#[test]
fn short_and_long_alias_on_one_option_does_not_conflict() {
assert!(conflicts_for("valid_short_and_long_alias.json").is_empty());
}

#[test]
fn single_dash_long_names_are_not_short_flags() {
assert!(conflicts_for("valid_long_flags_not_short.json").is_empty());
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"name": ["foo", "bar"],
"options": [
{ "name": ["-x", "--ex-1"] },
{ "name": ["-x", "--ex-2"] }
]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"name": "tool",
"options": [
{ "name": ["&#45;h", "--help"] },
{ "name": ["-h", "--history"] }
]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"name": "tool",
"options": [
{ "name": ["-v", "--verbose"] },
{ "name": ["-v", "--verbose"] }
]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
"name": "tool",
"subcommands": [
{
"name": "group",
"subcommands": [
{
"name": "leaf",
"options": [
{ "name": ["-l", "--long-a"] },
{ "name": ["-l", "--long-b"] }
]
}
]
}
]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"name": "tool",
"options": [
{ "name": ["-h", "--help", "-h"] },
{ "name": ["-h", "--history"] }
]
}
Loading
Loading