From 98624bd49499ed698c701db29644e29b13009801 Mon Sep 17 00:00:00 2001 From: default <216188+jdx@users.noreply.github.com> Date: Sun, 16 Aug 2026 23:32:44 +0000 Subject: [PATCH 1/5] feat(spec): a group, for the rule that no single flag can state MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Pairwise `conflicts` can say "at most one of these", once per pair — three flags for three declarations, six for fifteen, and a flag added later has to be added to every sibling. What it cannot say at all is `required`: "one of these is needed" is a statement about the set, and no rule written on an individual flag expresses it, because no individual flag is the one that must be given. group "input" "--file" "--url" "--stdin" required=#true Name first, then members, spelled the way every other relationship names a flag. The two properties are clap's and are read the same way, so a spec generated from a clap command means by them what clap meant: bare is "at most one", `required` is "exactly one", `required` with `multiple` is "at least one". This one the bridge *can* carry, unlike `requires`: `Command::get_groups`, `ArgGroup::get_args` and `is_required_set` are public, so a clap CLI's groups now reach the spec. Every spec in the fleet generated from clap was dropping them, which is the same hole #884 closed for `conflicts` and was found the same way. Enforced across the command chain rather than on the selected command alone, since a group may name global flags, which are declared on an ancestor. A member counts as given when it ended up with a value from argv or from `env` — the rule `conflicts` already follows. A default does not count: one that satisfied a required group would make the group unfalsifiable, and one that collided with a typed sibling would refuse a command line where the user named exactly one flag. Two members is the floor, checked where the group is written. A group of one is a rule about that flag and belongs on the flag; a group of none is nothing at all. Neither enforces anything, so neither should parse into something that looks like it does. `UsageErr` gains `MissingGroup` rather than reusing `MissingFlag` with a sentence in it: there is no one flag to name, and a caller rendering its own errors needs the members as members. Positional members of a clap group are dropped, because the spec names relationships by flag and a selector matching nothing would read as a rule that holds. The derive cannot declare a group yet — spec first, per the canonicality rule. Co-Authored-By: Claude Opus 5 --- docs/.vitepress/config.mts | 1 + docs/spec/reference/flag.md | 3 + docs/spec/reference/group.md | 76 +++++++++++ lib/src/docs/models.rs | 3 + lib/src/error.rs | 8 ++ lib/src/lib.rs | 1 + lib/src/parse.rs | 106 +++++++++++++++ lib/src/spec/cmd.rs | 58 +++++++++ lib/src/spec/group.rs | 246 +++++++++++++++++++++++++++++++++++ lib/src/spec/mod.rs | 7 + 10 files changed, 509 insertions(+) create mode 100644 docs/spec/reference/group.md create mode 100644 lib/src/spec/group.rs diff --git a/docs/.vitepress/config.mts b/docs/.vitepress/config.mts index 2f4aa122a..5c03a03d5 100644 --- a/docs/.vitepress/config.mts +++ b/docs/.vitepress/config.mts @@ -83,6 +83,7 @@ export default defineConfig({ { text: "cmd", link: "/spec/reference/cmd" }, { text: "complete", link: "/spec/reference/complete" }, { text: "flag", link: "/spec/reference/flag" }, + { text: "group", link: "/spec/reference/group" }, // { text: 'env', link: '/spec/reference/env' }, { text: "config", link: "/spec/reference/config" } ] diff --git a/docs/spec/reference/flag.md b/docs/spec/reference/flag.md index 5cecef4ea..bc99f77d8 100644 --- a/docs/spec/reference/flag.md +++ b/docs/spec/reference/flag.md @@ -74,6 +74,9 @@ mistake, and silently honouring one of them hides it. A conflict holds in either direction, so declaring it once is enough; it applies to flags that were actually given, not to defaults. +For three or more flags that exclude each other, or for "one of these is required", a +[`group`](/spec/reference/group) says in one node what `conflicts` says once per pair. + ## `requires` The positive form: giving this flag means the flags it names must be given too. Every diff --git a/docs/spec/reference/group.md b/docs/spec/reference/group.md new file mode 100644 index 000000000..1f8fa5db1 --- /dev/null +++ b/docs/spec/reference/group.md @@ -0,0 +1,76 @@ +# `group` + +A set of flags that relate to one another as a set. + +```kdl +flag "--file " +flag "--url " +flag "--stdin" + +// at most one of these +group "input" "--file" "--url" "--stdin" + +// exactly one of these: one is required, and only one is allowed +group "input" "--file" "--url" "--stdin" required=#true + +// at least one of these +group "input" "--file" "--url" "--stdin" required=#true multiple=#true + +// the same, written out when the members do not sit comfortably on one line +group "input" required=#true { + flag "--file" "--url" + flag "--stdin" +} +``` + +The name comes first, then the members, spelled the way every other relationship names +a flag — `--long` or `-s`. A group lives on the command whose flags it names, and a +group naming [global flags](/spec/reference/flag#global) belongs to the command that +declares them. + +## What the two properties mean + +| `required` | `multiple` | meaning | +| ---------- | ---------- | --------------------- | +| — | — | at most one of these | +| `#true` | — | exactly one of these | +| — | `#true` | nothing is enforced | +| `#true` | `#true` | at least one of these | + +Both default to false, so a bare group is mutual exclusion. These are clap's two +properties read the same way, so a spec generated from a clap command means by them what +clap meant. + +## Why not just `conflicts` + +For "at most one", [`conflicts`](/spec/reference/flag#conflicts-and-overrides) says the +same thing — but it says it once per pair, so three flags need three declarations and six +need fifteen, and a flag added later has to be added to every sibling. + +The part `conflicts` cannot say at all is `required`. "One of these is needed" is a +statement about the set: no rule written on an individual flag expresses it, because no +individual flag is the one that must be given. + +## What counts as given + +A member is given when it ended up with a value from the command line or from its +[`env`](/spec/reference/flag) variable — the same rule +[`conflicts`](/spec/reference/flag#conflicts-and-overrides) and +[`requires`](/spec/reference/flag#requires) follow. + +A [`default`](/spec/reference/flag) does not count. A default that satisfied a required +group would make the group unfalsifiable — it could never report anything — and one that +collided with a typed sibling would refuse a command line where the user named exactly +one flag. + +## Members + +A group needs at least two members, and naming fewer is an error where it is written +rather than a rule that quietly enforces nothing. A group of one is a statement about +that flag, which belongs on the flag as [`required`](/spec/reference/flag) or +[`requires`](/spec/reference/flag#requires). + +Only flags can be members. clap allows a positional in a group; a spec generated from +such a command keeps the flags and drops the positional, since the spec has no way to +name one in a relationship and a selector matching nothing would read as a rule that +holds. diff --git a/lib/src/docs/models.rs b/lib/src/docs/models.rs index 5770f7dcc..adfbf5cef 100644 --- a/lib/src/docs/models.rs +++ b/lib/src/docs/models.rs @@ -485,6 +485,9 @@ impl From<&crate::SpecCommand> for SpecCommand { mounted: _, flags_from_mount: _, subcommand_lookup: _, + // Presentational output does not describe relationships between flags, the + // way it already does not describe `conflicts`. + groups: _, } = cmd; Self { diff --git a/lib/src/error.rs b/lib/src/error.rs index 336695ef0..62e9579a9 100644 --- a/lib/src/error.rs +++ b/lib/src/error.rs @@ -16,6 +16,14 @@ pub enum UsageErr { #[error("Missing required flag: --{0} <{0}>")] MissingFlag(String), + /// A required group had none of its members given. + /// + /// Its own variant rather than a [`UsageErr::MissingFlag`] holding a sentence, + /// because there is no one flag to name: the group is the thing that was not + /// satisfied, and a caller that renders errors itself needs the members as members. + #[error("Missing one of the required flags in group {group}: {members}")] + MissingGroup { group: String, members: String }, + #[error("Invalid usage config")] InvalidInput( String, diff --git a/lib/src/lib.rs b/lib/src/lib.rs index aa40ff22b..5c265ad54 100644 --- a/lib/src/lib.rs +++ b/lib/src/lib.rs @@ -10,6 +10,7 @@ pub use crate::spec::cmd::SpecCommand; pub use crate::spec::complete::SpecComplete; pub use crate::spec::effect::SpecCommandEffect; pub use crate::spec::flag::SpecFlag; +pub use crate::spec::group::SpecGroup; pub use crate::spec::mount::SpecMount; pub use crate::spec::unknown_flags::UnknownFlags; pub use crate::spec::Spec; diff --git a/lib/src/parse.rs b/lib/src/parse.rs index 2c8b5691e..7e761235b 100644 --- a/lib/src/parse.rs +++ b/lib/src/parse.rs @@ -1232,6 +1232,42 @@ fn parse_partial_with_env( } } + // Groups, checked once per group rather than per flag: both questions a group asks — + // how many members were given, and whether that is enough — are about the set, which + // is the whole reason a group exists rather than a pile of pairwise conflicts. + // + // The same "given" rule as everything else here, so a member filled from the + // environment or a default counts. + // Every command in the chain, not only the selected one: a group may name global + // flags, which belong to an ancestor and are declared there. + let mut group_errors: Vec = Vec::new(); + for group in out.cmds.iter().flat_map(|cmd| &cmd.groups) { + let given: Vec<&str> = group + .members + .iter() + .filter(|selector| selector_is_explicit(selector, &out, &overridden_flags, custom_env)) + .map(|selector| selector.as_str()) + .collect(); + if !group.multiple && given.len() > 1 { + group_errors.push(UsageErr::InvalidFlag { + token: given[1].to_string(), + reason: format!("cannot be used with {} in group {}", given[0], group.name), + span: (0, 0).into(), + input: format!("{} {}", given[0], given[1]), + }); + } + if group.required && given.is_empty() { + // The members are what a user has to type, so they are in the message; the + // group's name is there too, since a command with several groups would + // otherwise report the same sentence twice with nothing to tell them apart. + group_errors.push(UsageErr::MissingGroup { + group: group.name.clone(), + members: group.members.join(", "), + }); + } + } + out.errors.extend(group_errors); + for flag in unique_flags(out.available_flags.values()) { if out.flags.contains_key(flag) || overridden_flags.contains(&flag.name) { continue; @@ -2828,6 +2864,76 @@ flag "--file " required_unless="--stdin" } } + #[test] + fn a_group_allows_one_member_and_refuses_two() { + let spec: Spec = "name \"ex\"\nbin \"ex\"\nflag \"--file \"\nflag \"--url \"\nflag \"--stdin\"\ngroup \"input\" \"--file\" \"--url\" \"--stdin\"\n" + .parse() + .unwrap(); + + // One is fine, and so is none: a plain group says "at most one". + parse(&spec, &input(&["ex", "--file", "a.txt"])).expect("one member is fine"); + parse(&spec, &input(&["ex"])).expect("a group that is not required asks for nothing"); + + let err = parse(&spec, &input(&["ex", "--file", "a.txt", "--stdin"])).unwrap_err(); + assert!(err.to_string().contains("group input"), "{err}"); + } + + #[test] + fn a_required_group_needs_one_of_its_members() { + let spec: Spec = "name \"ex\"\nbin \"ex\"\nflag \"--file \"\nflag \"--url \"\ngroup \"input\" \"--file\" \"--url\" required=#true\n" + .parse() + .unwrap(); + + let err = parse(&spec, &input(&["ex"])).unwrap_err(); + // The members, because that is what a user has to type; the name, because a + // command with several groups would otherwise report the same sentence twice. + assert!(err.to_string().contains("--file, --url"), "{err}"); + assert!(err.to_string().contains("input"), "{err}"); + + parse(&spec, &input(&["ex", "--url", "u"])).expect("one member satisfies it"); + } + + #[test] + fn a_multiple_group_only_polices_requiredness() { + // `multiple` with `required` is "at least one of these", so two is fine and + // none is not. + let spec: Spec = "name \"ex\"\nbin \"ex\"\nflag \"--a\"\nflag \"--b\"\ngroup \"any\" \"--a\" \"--b\" required=#true multiple=#true\n" + .parse() + .unwrap(); + + parse(&spec, &input(&["ex", "--a", "--b"])).expect("multiple allows both"); + assert!(parse(&spec, &input(&["ex"])).is_err()); + } + + #[test] + fn a_group_counts_what_was_given_rather_than_what_was_defaulted() { + // The rule `conflicts` already follows, and the flag reference already states: + // relationships apply to flags that were actually given, not to defaults. A + // default that satisfied a required group would make the group unfalsifiable — + // it could never report anything — and one that collided with a typed sibling + // would refuse a command line where the user named exactly one flag. + let spec: Spec = "name \"ex\"\nbin \"ex\"\nflag \"--file \" default=\"a.txt\"\nflag \"--url \"\ngroup \"input\" \"--file\" \"--url\" required=#true\n" + .parse() + .unwrap(); + + assert!( + parse(&spec, &input(&["ex"])).is_err(), + "a default does not stand in for a flag the user has to choose" + ); + parse(&spec, &input(&["ex", "--url", "u"])).expect("the typed member is the choice"); + } + + #[test] + fn a_group_reads_the_environment_as_given() { + // The environment does count, which is the same asymmetry `conflicts` has: an + // env var is somebody saying something, a default is nobody saying anything. + let spec: Spec = "name \"ex\"\nbin \"ex\"\nflag \"--file \" env=\"EX_FILE\"\nflag \"--url \"\ngroup \"input\" \"--file\" \"--url\" required=#true\n" + .parse() + .unwrap(); + + parse_with_env(&spec, &["ex"], &[("EX_FILE", "a.txt")]).expect("the environment fills it"); + } + #[test] fn a_requirement_names_the_flag_that_is_missing() { // Reported as the missing flag rather than as something wrong with `--out`, diff --git a/lib/src/spec/cmd.rs b/lib/src/spec/cmd.rs index 0cc32d547..9eae3da32 100644 --- a/lib/src/spec/cmd.rs +++ b/lib/src/spec/cmd.rs @@ -6,6 +6,7 @@ use crate::sh::sh; use crate::spec::builder::SpecCommandBuilder; use crate::spec::context::ParsingContext; use crate::spec::effect::{SpecCommandEffect, EFFECT_VALUES}; +use crate::spec::group::SpecGroup; use crate::spec::helpers::{string_entry, NodeHelper}; use crate::spec::is_false; use crate::spec::mount::SpecMount; @@ -48,6 +49,12 @@ pub struct SpecCommand { pub flags: Vec, /// Mounted external specs pub mounts: Vec, + /// Sets of flags that relate to one another as a set. + /// + /// Pairwise [`conflicts`](SpecFlag::conflicts) can say everything a plain group says + /// and cannot say `required`: "one of these is needed" is a statement about the set. + #[serde(skip_serializing_if = "Vec::is_empty")] + pub groups: Vec, /// Deprecation message if this command is deprecated #[serde(skip_serializing_if = "Option::is_none")] pub deprecated: Option, @@ -147,6 +154,7 @@ impl Default for SpecCommand { args: vec![], flags: vec![], mounts: vec![], + groups: vec![], deprecated: None, effect: None, unknown_flags: None, @@ -299,6 +307,7 @@ impl SpecCommand { "flag" => cmd.flags.push(SpecFlag::parse(ctx, &child)?), "arg" => cmd.args.push(SpecArg::parse(ctx, &child)?), "mount" => cmd.mounts.push(SpecMount::parse(ctx, &child)?), + "group" => cmd.groups.push(SpecGroup::parse(ctx, &child)?), "cmd" => { let node = SpecCommand::parse(ctx, &child)?; cmd.subcommands.insert(node.name.to_string(), node); @@ -468,6 +477,7 @@ impl SpecCommand { args, flags, mounts, + groups, aliases, hidden_aliases, examples, @@ -525,6 +535,12 @@ impl SpecCommand { if !mounts.is_empty() { self.mounts = mounts; } + // Replaced rather than appended, as flags are: a merged command's groups name + // that command's flags, and the flags have just been replaced too, so keeping + // both sets would leave groups pointing at flags that are no longer here. + if !groups.is_empty() { + self.groups = groups; + } if !aliases.is_empty() { self.aliases = aliases; } @@ -650,6 +666,7 @@ impl From<&SpecCommand> for KdlNode { flags, args, mounts, + groups, subcommands, complete, examples, @@ -763,6 +780,12 @@ impl From<&SpecCommand> for KdlNode { let children = node.children_mut().get_or_insert_with(KdlDocument::new); children.nodes_mut().push(mount.into()); } + // After the flags they name, so a reader meets the members before the rule + // about them. + for group in groups { + let children = node.children_mut().get_or_insert_with(KdlDocument::new); + children.nodes_mut().push(group.into()); + } for cmd in subcommands.values() { let children = node.children_mut().get_or_insert_with(KdlDocument::new); children.nodes_mut().push(cmd.into()); @@ -854,6 +877,41 @@ impl From<&clap::Command> for SpecCommand { spec.flags.push(flag) } } + // Groups, which clap does expose — `get_groups`, and `get_args` on each. A group + // names its members by clap's internal id, so each is resolved back to the flag it + // points at and written as a selector, the way conflicts are just above. + // + // clap's own `--help` groups (`ArgGroup` ids it creates for its built-in flags) + // have no members of ours in them, so the two-member floor drops them naturally + // rather than needing a name check. + for group in cmd.get_groups() { + let members: Vec = group + .get_args() + .filter_map(|id| cmd.get_arguments().find(|arg| arg.get_id() == id)) + .filter_map(|arg| match (arg.get_long(), arg.get_short()) { + (Some(long), _) => Some(format!("--{long}")), + (None, Some(short)) => Some(format!("-{short}")), + // A positional. The spec names group members the way it names every + // other relationship — by flag — so there is nothing to write here, + // and inventing a selector that matches nothing would read as a rule + // that holds. + (None, None) => None, + }) + .collect(); + // Below two members there is no rule left to enforce: whatever the group said + // about "at most one" or "at least one" is either vacuous or is plain + // required-ness on the single flag, which the flag already carries. + if members.len() < 2 { + continue; + } + let mut spec_group = SpecGroup::new(group.get_id().as_str(), members); + spec_group.required = group.is_required_set(); + // `is_multiple` takes `&mut self` in clap, and a `&ArgGroup` is all a + // `Command` hands out — so the group is cloned to ask. Once per group at + // spec-generation time, which is a build step rather than a parse. + spec_group.multiple = group.clone().is_multiple(); + spec.groups.push(spec_group); + } spec.subcommand_required = cmd.is_subcommand_required_set(); for subcmd in cmd.get_subcommands() { let mut scmd: SpecCommand = subcmd.into(); diff --git a/lib/src/spec/group.rs b/lib/src/spec/group.rs new file mode 100644 index 000000000..f7f755fe7 --- /dev/null +++ b/lib/src/spec/group.rs @@ -0,0 +1,246 @@ +use std::fmt::Display; + +use kdl::{KdlEntry, KdlNode}; +use serde::Serialize; + +use crate::error::Result; +use crate::spec::context::ParsingContext; +use crate::spec::helpers::{string_entry, NodeHelper}; +use crate::spec::is_false; + +/// A set of flags that relate to one another as a set. +/// +/// Everything here could be written as pairwise [`conflicts`](crate::SpecFlag::conflicts) +/// — for three members, three declarations, and for six, fifteen — except for the part +/// that cannot: "one of these is required" is a statement about the set, and no rule +/// written on an individual flag says it. +/// +/// The two properties are clap's, and are read the same way: +/// +/// - `multiple` (default `false`) — whether more than one member may be given. The +/// default is what makes a bare group mutual exclusion. +/// - `required` (default `false`) — whether at least one member must be given. +/// +/// So the default group is "at most one of these", `required` alone is "exactly one of +/// these", and `multiple` with `required` is "at least one of these". +/// +/// Members are named the way every other relationship names a flag — `--long` or `-s` — +/// so a group refers to flags by how they are spelled rather than by an internal id. +#[derive(Debug, Default, Clone, Serialize)] +#[non_exhaustive] +pub struct SpecGroup { + /// What this group is called. Used in messages, and it is how a reader tells two + /// groups apart when a command has several. + pub name: String, + /// The flags in the group, as selectors. + #[serde(skip_serializing_if = "Vec::is_empty")] + pub members: Vec, + /// Whether at least one member has to be given. + #[serde(skip_serializing_if = "is_false")] + pub required: bool, + /// Whether more than one member may be given. + #[serde(skip_serializing_if = "is_false")] + pub multiple: bool, +} + +impl SpecGroup { + /// A group named `name` holding `members`, exclusive and not required — the + /// defaults clap uses. + pub fn new( + name: impl Into, + members: impl IntoIterator>, + ) -> Self { + Self { + name: name.into(), + members: members.into_iter().map(Into::into).collect(), + required: false, + multiple: false, + } + } + + /// The same, but at least one member must be given. + pub fn required(mut self) -> Self { + self.required = true; + self + } + + /// The same, but more than one member may be given. + pub fn multiple(mut self) -> Self { + self.multiple = true; + self + } + + pub(crate) fn parse(ctx: &ParsingContext, node: &NodeHelper) -> Result { + let mut group = SpecGroup::default(); + // The name first, then the members: `group "input" "--file" "--url"`. One node + // rather than a node and a child list, because a group is short by nature — a + // set large enough to be unreadable on one line is a set nobody wants to be in. + let mut args = node.args(); + let Some(name) = args.next() else { + bail_parse!(ctx, node.span(), "a group needs a name"); + }; + group.name = name.ensure_string()?; + for arg in args { + group.members.push(arg.ensure_string()?); + } + for (k, v) in node.props() { + match k { + "required" => group.required = v.ensure_bool()?, + "multiple" => group.multiple = v.ensure_bool()?, + k => bail_parse!(ctx, v.entry.span(), "unsupported group key {k}"), + } + } + for child in node.children() { + match child.name() { + "required" => group.required = child.arg(0)?.ensure_bool()?, + "multiple" => group.multiple = child.arg(0)?.ensure_bool()?, + // The child spelling for members, for a group whose selectors do not fit + // comfortably on the node itself. + "flag" => { + for arg in child.args() { + group.members.push(arg.ensure_string()?); + } + } + k => bail_parse!( + ctx, + child.node.name().span(), + "unsupported group value key {k}" + ), + } + } + if group.name.is_empty() { + bail_parse!(ctx, node.span(), "a group needs a name"); + } + // A group of one is a flag, and a group of none is nothing at all. Both are + // almost certainly a mistake in the writing rather than an intention, and + // neither can be enforced into meaning anything. + if group.members.len() < 2 { + bail_parse!( + ctx, + node.span(), + "group {} needs at least two flags; a rule about one flag belongs on that flag", + group.name + ); + } + Ok(group) + } + + pub fn usage(&self) -> String { + format!("group:{}", self.name) + } +} + +impl From<&SpecGroup> for KdlNode { + fn from(group: &SpecGroup) -> KdlNode { + let mut node = KdlNode::new("group"); + node.push(string_entry(None, &group.name)); + for member in &group.members { + node.push(string_entry(None, member)); + } + if group.required { + node.push(KdlEntry::new_prop("required", true)); + } + if group.multiple { + node.push(KdlEntry::new_prop("multiple", true)); + } + node + } +} + +impl Display for SpecGroup { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{}", self.usage()) + } +} + +#[cfg(test)] +mod tests { + use crate::Spec; + + #[test] + fn a_group_round_trips_through_kdl() { + let spec: Spec = "flag \"--file \"\nflag \"--url \"\ngroup \"input\" \"--file\" \"--url\" required=#true\n" + .parse() + .unwrap(); + let group = &spec.cmd.groups[0]; + assert_eq!(group.name, "input"); + assert_eq!( + group.members, + vec!["--file".to_string(), "--url".to_string()] + ); + assert!(group.required); + assert!(!group.multiple); + + let reparsed: Spec = spec.to_string().parse().unwrap(); + let group = &reparsed.cmd.groups[0]; + assert_eq!(group.name, "input", "{spec}"); + assert_eq!(group.members.len(), 2, "{spec}"); + assert!(group.required, "{spec}"); + } + + #[test] + fn a_group_of_fewer_than_two_flags_is_refused() { + // A group of one is a rule about a flag, which belongs on the flag; a group of + // none is nothing at all. Both are a slip in the writing rather than a shape + // anyone means, and neither enforces anything, so they are refused where they + // are written rather than silently doing nothing at run time. + // The message is on the diagnostic's label rather than in `Display`, which + // renders every parse failure as "Invalid usage config" — so it is read the way + // the rest of the spec tests read one. + let err = "flag \"--file \"\ngroup \"input\" \"--file\"\n" + .parse::() + .unwrap_err(); + assert!(format!("{err:?}").contains("at least two"), "{err:?}"); + + let err = "group \"input\"\n".parse::().unwrap_err(); + assert!(format!("{err:?}").contains("at least two"), "{err:?}"); + } + + #[test] + fn a_group_comes_across_from_clap() { + // Unlike `requires`, this one the bridge can read: `Command::get_groups` and + // `ArgGroup::get_args` are public, so a clap CLI's groups reach the spec — and + // every spec generated from a clap command was losing them before this. + let cmd = clap::Command::new("ex") + .arg(clap::Arg::new("file").long("file")) + .arg(clap::Arg::new("url").long("url")) + .group( + clap::ArgGroup::new("input") + .args(["file", "url"]) + .required(true), + ); + let spec = Spec::from(&cmd); + let group = spec + .cmd + .groups + .iter() + .find(|g| g.name == "input") + .expect("the group should have come across"); + assert_eq!( + group.members, + vec!["--file".to_string(), "--url".to_string()] + ); + assert!(group.required); + assert!(!group.multiple); + } + + #[test] + fn a_clap_group_naming_a_positional_keeps_the_flags_it_can_name() { + // The spec names group members the way it names every other relationship, by + // flag, so a positional member has no spelling here. Dropping it silently would + // leave a group that enforces less than clap does — but writing `--` for + // it would be a selector matching nothing, which reads as a rule that holds and + // enforces even less. The flags it can name still make a group. + let cmd = clap::Command::new("ex") + .arg(clap::Arg::new("file").long("file")) + .arg(clap::Arg::new("url").long("url")) + .arg(clap::Arg::new("target")) + .group(clap::ArgGroup::new("input").args(["file", "url", "target"])); + let spec = Spec::from(&cmd); + let group = spec.cmd.groups.iter().find(|g| g.name == "input").unwrap(); + assert_eq!( + group.members, + vec!["--file".to_string(), "--url".to_string()] + ); + } +} diff --git a/lib/src/spec/mod.rs b/lib/src/spec/mod.rs index 8fa6f243b..14af4300b 100644 --- a/lib/src/spec/mod.rs +++ b/lib/src/spec/mod.rs @@ -9,6 +9,7 @@ mod context; pub mod data_types; pub mod effect; pub mod flag; +pub mod group; pub mod helpers; pub mod mount; pub mod unknown_flags; @@ -224,6 +225,9 @@ impl Spec { "usage" => schema.usage = node.arg(0)?.ensure_string()?, "arg" => schema.cmd.args.push(SpecArg::parse(ctx, &node)?), "flag" => schema.cmd.flags.push(SpecFlag::parse(ctx, &node)?), + // The root command's groups, as its flags and arguments are: a spec + // whose top level declares flags can group them there too. + "group" => schema.cmd.groups.push(crate::SpecGroup::parse(ctx, &node)?), // The root is a command like any other, so it can discover its own // subcommands by running something. A CLI whose top-level commands // come from plugins has no other way to say so. @@ -538,6 +542,9 @@ impl Display for Spec { for mount in self.cmd.mounts.iter() { nodes.push(mount.into()); } + for group in self.cmd.groups.iter() { + nodes.push(group.into()); + } for example in self.examples.iter() { nodes.push(example.into()); } From 693579356718b14698a49812230c3b31bff3fb49 Mon Sep 17 00:00:00 2001 From: default <216188+jdx@users.noreply.github.com> Date: Sun, 16 Aug 2026 23:45:30 +0000 Subject: [PATCH 2/5] fix(spec): a group counts flags, and clap's per-struct group is not one MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Three from review, one of which was breaking the repository's own spec. **The group clap invents for every struct.** `clap_derive` builds `ArgGroup::new().multiple(true)` for each `#[derive(Args)]` type, holding all of its fields, so that `flatten` works — see `clap_derive`'s `args.rs`. Carrying those put a `group Lint …` in usage's own generated spec, and would have put one in every clap-derived CLI in the fleet. Dropped by what they are rather than by where they came from: `multiple` without `required` states no rule at all — any number of members, none of them needed — so there is nothing to carry. A group that says `multiple` *and* `required` does mean something, and still comes across. **Two spellings of one flag are one member.** Counting selectors rather than the flags they resolve to meant a group naming both `-f` and `--file` reported that flag as conflicting with itself the moment it was given. Counted by resolved flag now. Deduplicated rather than refused where the group is written, since listing both spellings is redundant rather than wrong. **A default fills a required group.** The two halves of a group are two kinds of rule and read a default differently, which the docs now say. Exclusivity counts what was supplied, or a defaulted member would collide with the sibling the user typed and refuse a correct command line. Requiredness asks whether a member ended up with a value, and a default is a value — the rule `requires` and plain `required` follow. The previous commit set that rule; this applies it here. Co-Authored-By: Claude Opus 5 --- docs/spec/reference/group.md | 33 ++++++++++++----- lib/src/parse.rs | 70 ++++++++++++++++++++++++++---------- lib/src/spec/cmd.rs | 20 +++++++++-- lib/src/spec/group.rs | 39 ++++++++++++++++++++ 4 files changed, 133 insertions(+), 29 deletions(-) diff --git a/docs/spec/reference/group.md b/docs/spec/reference/group.md index 1f8fa5db1..cee334f66 100644 --- a/docs/spec/reference/group.md +++ b/docs/spec/reference/group.md @@ -53,15 +53,20 @@ individual flag is the one that must be given. ## What counts as given -A member is given when it ended up with a value from the command line or from its -[`env`](/spec/reference/flag) variable — the same rule -[`conflicts`](/spec/reference/flag#conflicts-and-overrides) and -[`requires`](/spec/reference/flag#requires) follow. +The two halves of a group are two kinds of rule, and they read a +[`default`](/spec/reference/flag) differently. -A [`default`](/spec/reference/flag) does not count. A default that satisfied a required -group would make the group unfalsifiable — it could never report anything — and one that -collided with a typed sibling would refuse a command line where the user named exactly -one flag. +**Exclusivity** counts what was supplied — from the command line or from a member's +[`env`](/spec/reference/flag) variable — and not what was defaulted. This is the rule +[`conflicts`](/spec/reference/flag#conflicts-and-overrides) follows, and it has to be: +a defaulted member counted as supplied would collide with the sibling the user actually +typed, and refuse a correct command line. + +**Requiredness** asks whether a member ended up with a value, and a default is a value. +This is the rule [`requires`](/spec/reference/flag#requires) and plain +[`required`](/spec/reference/flag) follow. A required group whose member has a default is +therefore always satisfied — which is worth noticing when you write one, since it means +the group enforces nothing. ## Members @@ -74,3 +79,15 @@ Only flags can be members. clap allows a positional in a group; a spec generated such a command keeps the flags and drops the positional, since the spec has no way to name one in a relationship and a selector matching nothing would read as a rule that holds. + +Members are counted by the flag they name, not by the selector, so a group listing both +`-f` and `--file` holds one member and not two. Listing both is redundant rather than +wrong, and a flag is never in conflict with itself. + +## Coming from clap + +`ArgGroup` carries across, with `required` and `multiple` read the same way. A group that +is `multiple` without being `required` states no rule at all, so it is dropped rather +than written out — which matters more than it sounds, because clap's _derive_ creates +exactly such a group for every `#[derive(Args)]` struct, named after the struct, to make +`flatten` work. Those are clap's bookkeeping, not a rule anyone declared. diff --git a/lib/src/parse.rs b/lib/src/parse.rs index 7e761235b..847005bd2 100644 --- a/lib/src/parse.rs +++ b/lib/src/parse.rs @@ -1242,12 +1242,24 @@ fn parse_partial_with_env( // flags, which belong to an ancestor and are declared there. let mut group_errors: Vec = Vec::new(); for group in out.cmds.iter().flat_map(|cmd| &cmd.groups) { - let given: Vec<&str> = group - .members - .iter() - .filter(|selector| selector_is_explicit(selector, &out, &overridden_flags, custom_env)) - .map(|selector| selector.as_str()) - .collect(); + // Counted by the *flag* a selector resolves to, not by the selector. `-f` and + // `--file` are two spellings of one flag, and a group naming both — or naming one + // flag twice — would otherwise report that flag as conflicting with itself the + // moment it was given. Deduplicated rather than refused where the group is + // written, because listing both spellings is redundant, not wrong. + let mut given: Vec<&str> = Vec::new(); + let mut seen: Vec = Vec::new(); + for selector in &group.members { + if !selector_is_explicit(selector, &out, &overridden_flags, custom_env) { + continue; + } + let name = selector_flag_name(selector, &out).unwrap_or_else(|| selector.clone()); + if seen.contains(&name) { + continue; + } + seen.push(name); + given.push(selector.as_str()); + } if !group.multiple && given.len() > 1 { group_errors.push(UsageErr::InvalidFlag { token: given[1].to_string(), @@ -1256,7 +1268,15 @@ fn parse_partial_with_env( input: format!("{} {}", given[0], given[1]), }); } - if group.required && given.is_empty() { + // Requiredness is a *positive* rule, so it reads a default as filling a member — + // the rule `requires` follows. That is also why it cannot reuse `given` above: + // exclusivity must count only what was supplied, or a defaulted member would + // collide with the sibling the user actually typed. + let satisfied = group + .members + .iter() + .any(|selector| selector_is_satisfied(selector, &out, &overridden_flags, custom_env)); + if group.required && !satisfied { // The members are what a user has to type, so they are in the message; the // group's name is there too, since a command with several groups would // otherwise report the same sentence twice with nothing to tell them apart. @@ -2906,21 +2926,35 @@ flag "--file " required_unless="--stdin" } #[test] - fn a_group_counts_what_was_given_rather_than_what_was_defaulted() { - // The rule `conflicts` already follows, and the flag reference already states: - // relationships apply to flags that were actually given, not to defaults. A - // default that satisfied a required group would make the group unfalsifiable — - // it could never report anything — and one that collided with a typed sibling - // would refuse a command line where the user named exactly one flag. + fn a_group_reads_a_default_for_requiredness_and_not_for_exclusivity() { + // The two halves of a group are two kinds of rule, and they read a default + // differently on purpose. Requiredness asks whether a member has a value, and a + // default is a value — the rule `requires` follows. Exclusivity asks what the + // user supplied, because a defaulted member counted as supplied would collide + // with the sibling they actually typed and refuse a correct command line. let spec: Spec = "name \"ex\"\nbin \"ex\"\nflag \"--file \" default=\"a.txt\"\nflag \"--url \"\ngroup \"input\" \"--file\" \"--url\" required=#true\n" .parse() .unwrap(); - assert!( - parse(&spec, &input(&["ex"])).is_err(), - "a default does not stand in for a flag the user has to choose" - ); - parse(&spec, &input(&["ex", "--url", "u"])).expect("the typed member is the choice"); + parse(&spec, &input(&["ex"])).expect("the default fills the group"); + parse(&spec, &input(&["ex", "--url", "u"])) + .expect("the default must not conflict with the flag the user typed"); + } + + #[test] + fn a_group_naming_two_spellings_of_one_flag_is_not_a_conflict() { + // `-f` and `--file` are one flag. Counted by selector, giving it once would + // report it as conflicting with itself. + let spec: Spec = "name \"ex\"\nbin \"ex\"\nflag \"-f --file \"\nflag \"--url \"\ngroup \"input\" \"-f\" \"--file\" \"--url\"\n" + .parse() + .unwrap(); + + parse(&spec, &input(&["ex", "--file", "a.txt"])).expect("one flag is one member"); + parse(&spec, &input(&["ex", "-f", "a.txt"])).expect("either spelling, still one member"); + + // A genuine collision is still one. + let err = parse(&spec, &input(&["ex", "--file", "a.txt", "--url", "u"])).unwrap_err(); + assert!(err.to_string().contains("group input"), "{err}"); } #[test] diff --git a/lib/src/spec/cmd.rs b/lib/src/spec/cmd.rs index 9eae3da32..686636bed 100644 --- a/lib/src/spec/cmd.rs +++ b/lib/src/spec/cmd.rs @@ -904,12 +904,26 @@ impl From<&clap::Command> for SpecCommand { if members.len() < 2 { continue; } - let mut spec_group = SpecGroup::new(group.get_id().as_str(), members); - spec_group.required = group.is_required_set(); + // `multiple` without `required` enforces nothing at all — any number of + // members, none of them needed — so there is nothing to carry across. + // + // This is not a corner case. clap's *derive* emits exactly that group for + // every `#[derive(Args)]` struct, named after the struct and holding all its + // fields, to make `flatten` work: `clap_derive`'s `args.rs` builds + // `ArgGroup::new(id).multiple(true)`. Carrying them would put a `group Lint + // …` in the spec of every clap-derived CLI, including this repository's own, + // describing bookkeeping rather than a rule anyone declared. + let required = group.is_required_set(); // `is_multiple` takes `&mut self` in clap, and a `&ArgGroup` is all a // `Command` hands out — so the group is cloned to ask. Once per group at // spec-generation time, which is a build step rather than a parse. - spec_group.multiple = group.clone().is_multiple(); + let multiple = group.clone().is_multiple(); + if multiple && !required { + continue; + } + let mut spec_group = SpecGroup::new(group.get_id().as_str(), members); + spec_group.required = required; + spec_group.multiple = multiple; spec.groups.push(spec_group); } spec.subcommand_required = cmd.is_subcommand_required_set(); diff --git a/lib/src/spec/group.rs b/lib/src/spec/group.rs index f7f755fe7..8a8d2a020 100644 --- a/lib/src/spec/group.rs +++ b/lib/src/spec/group.rs @@ -224,6 +224,45 @@ mod tests { assert!(!group.multiple); } + #[test] + fn the_group_clap_derive_invents_for_every_struct_is_not_carried() { + // `clap_derive` builds `ArgGroup::new().multiple(true)` for every + // `#[derive(Args)]` type, holding all of its fields, so that `flatten` works. + // It states no rule — any number of members, none of them needed — and carrying + // it would put a `group Lint …` in the spec of every clap-derived CLI, this + // repository's own included, describing bookkeeping rather than a declaration. + // + // The test is written against the *shape* rather than against the derive, since + // it is the shape that means nothing: `multiple` without `required`. + let cmd = clap::Command::new("ex") + .arg(clap::Arg::new("file").long("file")) + .arg(clap::Arg::new("url").long("url")) + .group( + clap::ArgGroup::new("Ex") + .args(["file", "url"]) + .multiple(true), + ); + assert!( + Spec::from(&cmd).cmd.groups.is_empty(), + "a group that enforces nothing should not reach the spec" + ); + + // `multiple` *with* `required` does say something — at least one of these — so + // that one is carried. + let cmd = clap::Command::new("ex") + .arg(clap::Arg::new("file").long("file")) + .arg(clap::Arg::new("url").long("url")) + .group( + clap::ArgGroup::new("input") + .args(["file", "url"]) + .multiple(true) + .required(true), + ); + let spec = Spec::from(&cmd); + assert_eq!(spec.cmd.groups.len(), 1); + assert!(spec.cmd.groups[0].multiple && spec.cmd.groups[0].required); + } + #[test] fn a_clap_group_naming_a_positional_keeps_the_flags_it_can_name() { // The spec names group members the way it names every other relationship, by From 034e372e338ed7b0a5683cf58e790b731094407a Mon Sep 17 00:00:00 2001 From: default <216188+jdx@users.noreply.github.com> Date: Mon, 17 Aug 2026 00:29:52 +0000 Subject: [PATCH 3/5] feat(lib)!: mark `UsageErr` non-exhaustive MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `MissingGroup` is the third error variant this repository has added since 4.0 — `ArgRequiresDoubleDash` came with `double_dash`, the variadic bounds with `var` — and each one was a major release for everyone matching on `UsageErr`. This enum grows every time the spec learns to say something new, so it is marked `#[non_exhaustive]`: one more break now, and none of the same kind afterwards. A caller matching on it needs a `_` arm from here on, which is the cost, and the same shape `SpecFlag` and the other spec types already have. The `!` is the whole declaration: what version that implies is release-plz's to work out, and nothing here touches one. Co-Authored-By: Claude Opus 5 --- lib/src/error.rs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/lib/src/error.rs b/lib/src/error.rs index 62e9579a9..bf13a246b 100644 --- a/lib/src/error.rs +++ b/lib/src/error.rs @@ -1,7 +1,14 @@ use miette::{Diagnostic, NamedSource, SourceSpan}; use thiserror::Error; +/// Everything that can go wrong reading a spec or a command line against one. +/// +/// `#[non_exhaustive]`, so a caller matching on it needs a `_` arm. That is the point: +/// this enum grows every time the spec learns to say something new — `MissingGroup` +/// arrived with groups, `ArgRequiresDoubleDash` with `double_dash` — and without this +/// each one is a major release for everyone downstream. #[derive(Error, Diagnostic, Debug)] +#[non_exhaustive] pub enum UsageErr { #[error("Invalid flag `{token}`: {reason}")] InvalidFlag { From 46d17cfd50b7a046816a6c146e1571a5f8ea5e80 Mon Sep 17 00:00:00 2001 From: default <216188+jdx@users.noreply.github.com> Date: Mon, 17 Aug 2026 00:29:52 +0000 Subject: [PATCH 4/5] fix(spec): a group does not outlive the flags it names MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A mounted spec's root flags *replace* the flags of the command the mount sits on. Groups name flags, so leaving the old set in place meant enforcing exclusivity between flags that were no longer there — and a required group whose members nothing answered to would have rejected every invocation of that command. They travel with the flags now, including when the replacement declares no groups of its own, which is the case that was broken: a non-empty check let the stale set survive precisely when there was nothing to replace it with. Co-Authored-By: Claude Opus 5 --- lib/src/spec/cmd.rs | 13 ++++++++----- lib/src/spec/group.rs | 28 ++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 5 deletions(-) diff --git a/lib/src/spec/cmd.rs b/lib/src/spec/cmd.rs index 686636bed..92b1f1b0a 100644 --- a/lib/src/spec/cmd.rs +++ b/lib/src/spec/cmd.rs @@ -529,16 +529,19 @@ impl SpecCommand { if !args.is_empty() { self.args = args; } - if !flags.is_empty() { + let flags_replaced = !flags.is_empty(); + if flags_replaced { self.flags = flags; } if !mounts.is_empty() { self.mounts = mounts; } - // Replaced rather than appended, as flags are: a merged command's groups name - // that command's flags, and the flags have just been replaced too, so keeping - // both sets would leave groups pointing at flags that are no longer here. - if !groups.is_empty() { + // Groups travel with the flags they name. A mounted spec that replaces this + // command's flags replaces its groups too — including with none, which is the + // case that matters: keeping the old set would enforce exclusivity between flags + // that are no longer here, and a required group whose members nothing answers to + // would reject every invocation. + if flags_replaced || !groups.is_empty() { self.groups = groups; } if !aliases.is_empty() { diff --git a/lib/src/spec/group.rs b/lib/src/spec/group.rs index 8a8d2a020..b7ef3a06d 100644 --- a/lib/src/spec/group.rs +++ b/lib/src/spec/group.rs @@ -196,6 +196,34 @@ mod tests { assert!(format!("{err:?}").contains("at least two"), "{err:?}"); } + #[test] + fn a_mount_replacing_the_flags_replaces_the_groups_with_them() { + // A mounted spec's root flags *replace* the flags of the command the mount sits + // on. Groups name flags, so they have to go with them: keeping the old set would + // enforce exclusivity between flags that are no longer here, and a required group + // whose members nothing answers to would reject every invocation. + let mut base: Spec = "flag \"--file \"\nflag \"--url \"\ngroup \"input\" \"--file\" \"--url\" required=#true\n" + .parse() + .unwrap(); + let mounted: Spec = "flag \"--other \"\n".parse().unwrap(); + + base.cmd.merge(mounted.cmd); + assert!( + base.cmd.groups.is_empty(), + "a group naming flags that were replaced should not survive them" + ); + + // A merge that brings no flags leaves the groups alone, which is what makes this + // about *replacement* rather than about merging at all. + let mut base: Spec = + "flag \"--file \"\nflag \"--url \"\ngroup \"input\" \"--file\" \"--url\"\n" + .parse() + .unwrap(); + let helpish: Spec = "name \"other\"\n".parse().unwrap(); + base.cmd.merge(helpish.cmd); + assert_eq!(base.cmd.groups.len(), 1); + } + #[test] fn a_group_comes_across_from_clap() { // Unlike `requires`, this one the bridge can read: `Command::get_groups` and From dcfa48646a221e687a245e0129c306574945e94c Mon Sep 17 00:00:00 2001 From: default <216188+jdx@users.noreply.github.com> Date: Mon, 17 Aug 2026 01:20:42 +0000 Subject: [PATCH 5/5] chore: hold the semver gate back until the major it is waiting for MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `cargo semver-checks check-release` compares against the published crate, so a break that has been *decided* — `feat(lib)!:`, with release-plz to work out what version that implies — is red from the moment it is written until the release ships. `UsageErr` being marked `#[non_exhaustive]` is the current one. A gate that cannot pass is a gate people learn to ignore, and an ignored gate stops catching the accidental breaks it exists for. So it is skipped while usage-lib is on 5.x and runs normally from 6.0 on, by which time the break is in the published baseline and the check is meaningful again. The condition clears itself rather than needing remembering, which is the point: nobody has to come back and delete this. Both halves are verified — it skips at 5.1.0 and runs (and passes) with the crate at 6.0.0. One `run` block rather than a list, since each entry of a list is its own shell and the version would not survive between them. Co-Authored-By: Claude Opus 5 --- mise.toml | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/mise.toml b/mise.toml index bed723347..f8e36fd3c 100644 --- a/mise.toml +++ b/mise.toml @@ -82,7 +82,25 @@ run = 'cargo clippy --all --all-features --all-targets -- -D warnings' [tasks."lint:fmt"] run = 'cargo fmt --all -- --check' [tasks."lint:semver"] -run = 'cargo semver-checks check-release -p usage-lib' +# Held back until 6.0 is out, because a break that has been *decided* cannot pass this. +# `check-release` compares against the published crate, so `feat(lib)!:` work is red from +# the moment it is written until release-plz ships the major it implies — and a gate that +# cannot pass is a gate people learn to ignore, which is worse than not running it. +# +# The condition clears itself rather than needing remembering: once the crates are on +# 6.x, the break is in the published baseline and this runs again, catching the *next* +# unintended one. Raise the number the same way if a later major is declared the same way. +# +# One block rather than a list, because each entry of a list is its own shell and the +# version would not survive between them. +run = ''' +major=$(sed -n 's/^version = "\([0-9]*\)\..*/\1/p' lib/Cargo.toml | head -1) +if [ "$major" -lt 6 ]; then + echo "skipped: usage-lib is $major.x, and the 6.0 break this would report is declared rather than accidental" + exit 0 +fi +cargo semver-checks check-release -p usage-lib +''' [tasks."lint:go"] dir = 'go' # `gofmt -l` prints what it would change and exits 0 either way, so the output is