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..cee334f66 --- /dev/null +++ b/docs/spec/reference/group.md @@ -0,0 +1,93 @@ +# `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 + +The two halves of a group are two kinds of rule, and they read a +[`default`](/spec/reference/flag) differently. + +**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 + +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. + +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/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..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 { @@ -16,6 +23,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..847005bd2 100644 --- a/lib/src/parse.rs +++ b/lib/src/parse.rs @@ -1232,6 +1232,62 @@ 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) { + // 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(), + reason: format!("cannot be used with {} in group {}", given[0], group.name), + span: (0, 0).into(), + input: format!("{} {}", given[0], given[1]), + }); + } + // 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. + 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 +2884,90 @@ 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_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(); + + 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] + 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..92b1f1b0a 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, @@ -519,12 +529,21 @@ 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; } + // 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() { self.aliases = aliases; } @@ -650,6 +669,7 @@ impl From<&SpecCommand> for KdlNode { flags, args, mounts, + groups, subcommands, complete, examples, @@ -763,6 +783,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 +880,55 @@ 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; + } + // `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. + 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(); 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..b7ef3a06d --- /dev/null +++ b/lib/src/spec/group.rs @@ -0,0 +1,313 @@ +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_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 + // `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 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 + // 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()); } 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