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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions PLAN.md
Original file line number Diff line number Diff line change
Expand Up @@ -503,9 +503,12 @@ Groups are the opposite case: `Command::get_groups`, `ArgGroup::get_args` and
command receives no argv tokens. This deliberately reads argv rather than
bound values: an environment variable or default may fill a field, but an
empty command line still means help.
- [x] **`subcommand_negates_reqs`.** A selected child suppresses every positive
requirement declared by its parent while conflicts and the child's own requirements
still apply. KDL, usage-lib, typed Rust, generated Go, and the clap bridge agree.
- [ ] **Remaining command parsing policy** —
`args_conflicts_with_subcommands`, `subcommand_negates_reqs`,
`subcommand_precedence_over_arg`, and `allow_missing_positional`.
`args_conflicts_with_subcommands`, `subcommand_precedence_over_arg`, and
`allow_missing_positional`.
- [x] **`args_override_self`.** Repeated scalar flags are corrections by default;
the later value wins. `args_override_self=false` opts a command into duplicate
errors. KDL, usage-lib, the typed derive/static metadata, generated Go, and the
Expand Down
3 changes: 3 additions & 0 deletions argv/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,8 @@ pub struct Command<'a> {
/// bound values: an environment variable or default may fill a field, but neither means
/// the user supplied an argument to this invocation.
pub arg_required_else_help: bool,
/// Selecting a subcommand suppresses this command's required arguments.
pub subcommand_negates_reqs: bool,
/// Disable delimiter splitting for positional values after `--` or on an
/// automatic trailing argument. Inherited by subcommands.
pub dont_delimit_trailing_values: bool,
Expand Down Expand Up @@ -234,6 +236,7 @@ impl Command<'_> {
default_subcommand: ::core::option::Option::None,
external_subcommand: false,
arg_required_else_help: false,
subcommand_negates_reqs: false,
dont_delimit_trailing_values: false,
unknown_flags: ::core::option::Option::None,
version: false,
Expand Down
6 changes: 6 additions & 0 deletions argv/src/spec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1134,6 +1134,9 @@ impl Spec<'_> {
if !self.root.args_override_self {
writeln!(out, "args_override_self #false")?;
}
if self.root.cmd.subcommand_negates_reqs {
writeln!(out, "subcommand_negates_reqs #true")?;
}
// A `complete` block for every completer this CLI declares, naming the command that
// asks the binary itself. Written rather than declared, so there is one place a
// completer is said to exist: the Rust function. Everything that reads a spec — the
Expand Down Expand Up @@ -1383,6 +1386,9 @@ fn write_command<'a>(
if !meta.args_override_self {
out.push_str(" args_override_self=#false");
}
if meta.cmd.subcommand_negates_reqs {
out.push_str(" subcommand_negates_reqs=#true");
}
out.push_str(" {\n");

let inner = depth + 1;
Expand Down
6 changes: 0 additions & 6 deletions clap_usage/src/report.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ pub enum FidelityFeature {
AllowMissingPositional,
ArgsConflictWithSubcommands,
SubcommandPrecedenceOverArg,
SubcommandNegatesRequirements,
FlattenHelp,
NextLineHelp,
SubcommandHelpHeading,
Expand Down Expand Up @@ -97,11 +96,6 @@ fn visit(cmd: &Command, ancestors: &[String], losses: &mut BTreeSet<FidelityLoss
FidelityFeature::SubcommandPrecedenceOverArg,
"subcommand_precedence_over_arg",
);
command_loss(
cmd.is_subcommand_negates_reqs_set(),
FidelityFeature::SubcommandNegatesRequirements,
"subcommand_negates_reqs",
);
command_loss(
cmd.is_flatten_help_set(),
FidelityFeature::FlattenHelp,
Expand Down
1 change: 1 addition & 0 deletions conformance/src/tables.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,7 @@ pub fn build(
unknown_flags,
external_subcommand: cmd.external_subcommand,
arg_required_else_help: cmd.arg_required_else_help,
subcommand_negates_reqs: cmd.subcommand_negates_reqs,
dont_delimit_trailing_values: cmd.dont_delimit_trailing_values,
key: 0,
}));
Expand Down
16 changes: 15 additions & 1 deletion derive/src/codegen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,7 @@ pub fn emit(cli: &Cli) -> TokenStream {
let arg_required_else_help = cli.arg_required_else_help;
let dont_delimit_trailing_values = cli.dont_delimit_trailing_values;
let args_override_self = cli.args_override_self;
let subcommand_negates_reqs = cli.subcommand_negates_reqs;
let usage = option_str(cli.usage.as_deref());
let restart_token = option_str(cli.restart_token.as_deref());
let mount = option_str(cli.mount.as_deref());
Expand Down Expand Up @@ -422,6 +423,7 @@ pub fn emit(cli: &Cli) -> TokenStream {
version: #has_version,
unknown_flags: #unknown_flags,
arg_required_else_help: #arg_required_else_help,
subcommand_negates_reqs: #subcommand_negates_reqs,
dont_delimit_trailing_values: #dont_delimit_trailing_values,
name: #name,
key: #root_key,
Expand Down Expand Up @@ -3445,6 +3447,7 @@ pub fn emit_args(cli: &Cli) -> TokenStream {
let arg_required_else_help = cli.arg_required_else_help;
let dont_delimit_trailing_values = cli.dont_delimit_trailing_values;
let args_override_self = cli.args_override_self;
let subcommand_negates_reqs = cli.subcommand_negates_reqs;
let before_help = option_expr(cli.before_help.as_ref());
let before_long_help = option_expr(cli.before_long_help.as_ref());
let after_help = option_expr(cli.after_help.as_ref());
Expand Down Expand Up @@ -3555,6 +3558,7 @@ pub fn emit_args(cli: &Cli) -> TokenStream {
key: #command_key,
unknown_flags: #unknown_flags,
arg_required_else_help: #arg_required_else_help,
subcommand_negates_reqs: #subcommand_negates_reqs,
dont_delimit_trailing_values: #dont_delimit_trailing_values,
flags: #flag_table_ref,
args: #arg_table_ref,
Expand Down Expand Up @@ -4712,6 +4716,16 @@ fn env_fallbacks(cli: &Cli) -> TokenStream {
/// from the environment or a default.
fn post_binding(cli: &Cli) -> TokenStream {
let sub_check = subcommand_parts(cli).map(|p| p.check).unwrap_or_default();
let subcommand_satisfies_requirements = if cli.subcommand_negates_reqs
&& cli
.fields
.iter()
.any(|field| matches!(field.kind, Kind::Subcommand { .. }))
{
quote!(partial.__usage_selected.is_some())
} else {
quote!(false)
};
let direct_exclusive_present = cli.fields.iter().filter_map(|field| {
if !field.exclusive {
return None;
Expand Down Expand Up @@ -5531,7 +5545,7 @@ fn post_binding(cli: &Cli) -> TokenStream {
// An exclusive occurrence is the command's escape from requiredness, just as in clap:
// `--version` remains usable on a command that otherwise requires an input. Conflicts
// and other validation still ran above; only errors about absent siblings are skipped.
if !__usage_exclusive_present {
if !__usage_exclusive_present && !(#subcommand_satisfies_requirements) {
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
#(#requirement_checks)*
#(#conditional_requirement_checks)*
#(#required_checks)*
Expand Down
17 changes: 14 additions & 3 deletions derive/src/model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,7 @@ pub struct Cli {
/// Disable delimiter splitting after `--` and for automatic trailing args.
pub dont_delimit_trailing_values: bool,
pub args_override_self: bool,
pub subcommand_negates_reqs: bool,
/// Declared descriptions, for the case a doc comment cannot express: a long form that does
/// not contain the short one.
pub about_attr: Option<proc_macro2::TokenStream>,
Expand Down Expand Up @@ -556,6 +557,7 @@ impl Cli {
arg_required_else_help: false,
dont_delimit_trailing_values: false,
args_override_self: true,
subcommand_negates_reqs: false,
about_attr: None,
long_about_attr: None,
before_help: None,
Expand Down Expand Up @@ -698,6 +700,7 @@ impl Cli {
cli.dont_delimit_trailing_values = flag_value(&meta)?
}
"args_override_self" => cli.args_override_self = flag_value(&meta)?,
"subcommand_negates_reqs" => cli.subcommand_negates_reqs = flag_value(&meta)?,
"restart_token" => cli.restart_token = Some(string_value(&meta)?),
"mount" => cli.mount = Some(string_value(&meta)?),
"group" => cli.groups.push(group_decl(&meta)?),
Expand All @@ -709,7 +712,7 @@ impl Cli {
format!(
"unknown option `{other}` on a struct; usage::Cli takes \
`name`, `name_spec`, `bin`, `bin_spec`, `version`, `version_spec`, `usage`, `verbatim_doc_comment`, `unknown_flags`, \
`default_subcommand`, `multicall`, `no_binary_name`, `arg_required_else_help`, `dont_delimit_trailing_values`, `args_override_self`, \
`default_subcommand`, `multicall`, `no_binary_name`, `arg_required_else_help`, `dont_delimit_trailing_values`, `args_override_self`, `subcommand_negates_reqs`, \
`next_help_heading`, `restart_token`, `mount` and \
`group` here, and the description comes from the doc \
comment"
Expand Down Expand Up @@ -765,6 +768,7 @@ impl Cli {
field,
cli.rename_all,
cli.rename_all_env,
cli.subcommand_negates_reqs,
)?);
}
if let Some(heading) = &cli.next_help_heading {
Expand Down Expand Up @@ -1678,6 +1682,7 @@ impl Field {
field: &syn::Field,
rename_all: Option<CasingStyle>,
rename_all_env: CasingStyle,
subcommand_negates_reqs: bool,
) -> syn::Result<Self> {
let ident = field
.ident
Expand Down Expand Up @@ -2442,7 +2447,10 @@ impl Field {
// `required` is for the one case the type cannot express. Anywhere else it either
// repeats what the type says or contradicts it, and both are worth refusing: a
// declaration that changes nothing is a declaration someone will trust.
if required_collection && shape != Shape::Many {
if required_collection
&& shape != Shape::Many
&& !(subcommand_negates_reqs && shape == Shape::Optional)
{
return Err(syn::Error::new(
span,
match shape {
Expand Down Expand Up @@ -2566,7 +2574,10 @@ impl Field {
// what the type says or contradicts it, and a declaration that changes nothing is one
// someone will eventually trust. (This guard was lost while two fixes for the same
// review finding met in the middle; the test for it is what noticed.)
if required_collection && shape != Shape::Many {
if required_collection
&& shape != Shape::Many
&& !(subcommand_negates_reqs && shape == Shape::Optional)
{
return Err(syn::Error::new(
span,
match shape {
Expand Down
1 change: 1 addition & 0 deletions docs/rust/clap-compatibility.md
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ the Rust declaration, not only from generated KDL, wherever the bridge column sa
| `infer_subcommands`, `infer_long_args` | no | no | no | no | no | no | Intentional non-goal: usage requires exact flag and subcommand spellings. |
| `arg_required_else_help` | yes | yes | yes | yes | yes | yes | Bare selected commands request short help; defaults and environment values do not count as argv. |
| `args_override_self` | yes | yes | yes | yes | yes | yes | Usage defaults to permissive last-one-wins behavior; set false for strict duplicate checking. |
| `subcommand_negates_reqs` | yes | yes | yes | yes | yes | yes | A selected child suppresses its parent's positive requirements, not conflicts or the child's requirements. |
| remaining subcommand/argument policies | no | no | no | no | no | no | `args_conflicts_with_subcommands`, precedence, and missing positionals are not represented. |
| unknown flags | different | different | different | different | yes | different | usage is permissive by default; `unknown_flags = "error"` opts into strict parsing. |

Expand Down
3 changes: 3 additions & 0 deletions docs/rust/migrating-from-clap.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,9 @@ The clap bridge records clap's setting, so generated specs retain the source com
`#[command(arg_required_else_help)]` migrates in place. usage checks whether the selected
command received an argv token; environment and default fallbacks do not count.

`#[command(subcommand_negates_reqs)]` also migrates in place. Selecting a child suppresses
the parent's positive requirements while leaving conflicts and the child's requirements active.

Container casing also migrates in place. `#[command(rename_all = "snake_case")]` controls
inferred field or subcommand names, and `rename_all_env` controls names generated by bare
`#[arg(env)]`; an explicit `long`, `name`, or `env = "NAME"` still wins.
Expand Down
14 changes: 14 additions & 0 deletions docs/spec/reference/cmd.md
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,20 @@ The policy observes argv belonging to the selected command. A global flag before
subcommand does not count as that subcommand's argument, and values supplied later by an
environment variable or default do not suppress help.

### Let a subcommand satisfy parent requirements

`subcommand_negates_reqs` makes required arguments, flags, groups, and conditional
requirements on a parent optional when a child is selected:

```kdl
subcommand_negates_reqs #true
arg "<input>"
cmd "inspect"
```

`ex inspect` is valid, while bare `ex` still requires `input`. Conflicts continue to apply,
and the selected child must still satisfy its own requirements.

### Preserve delimiters in trailing values

`dont_delimit_trailing_values` keeps a positional token whole after `--`, or once a
Expand Down
2 changes: 2 additions & 0 deletions go/argv/argv.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,8 @@ type Command struct {
ExternalSubcommand bool
// ArgRequiredElseHelp shows this command's help when no argv token follows its name.
ArgRequiredElseHelp bool
// SubcommandNegatesReqs lets a selected child satisfy this command's requirements.
SubcommandNegatesReqs bool
// DontDelimitTrailingValues disables delimiter splitting after -- and for
// automatic trailing arguments. It is inherited by subcommands.
DontDelimitTrailingValues bool
Expand Down
15 changes: 15 additions & 0 deletions go/argv/relationships.go
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,15 @@ func CheckRelationships(meta Metadata, entries []uint64, sourceOf func(uint64) S
// as `--feature`, its negation, or a truthy environment value.
func CheckRelationshipsWithValues(meta Metadata, entries []uint64,
sourceOf func(uint64) Source, valuesOf func(uint64) []string) *Error {
return CheckRelationshipsWithValuesAndRequirements(meta, entries, sourceOf, valuesOf,
func(uint64) bool { return true })
}

// CheckRelationshipsWithValuesAndRequirements additionally selects which entries have their
// positive requirement rules enforced. Conflicts always apply.
func CheckRelationshipsWithValuesAndRequirements(meta Metadata, entries []uint64,
sourceOf func(uint64) Source, valuesOf func(uint64) []string,
requirementsOf func(uint64) bool) *Error {
given := func(key uint64) bool { return sourceOf(key).Given() }

for _, key := range entries {
Expand All @@ -144,6 +153,9 @@ func CheckRelationshipsWithValues(meta Metadata, entries []uint64,
return e
}
}
if !requirementsOf(key) {
continue
}
for _, other := range m.Requires {
if sourceOf(other) == Unset {
if required := meta.Lookup(other); required != nil {
Expand Down Expand Up @@ -176,6 +188,9 @@ func CheckRelationshipsWithValues(meta Metadata, entries []uint64,
if sourceOf(key) != Unset {
continue
}
if !requirementsOf(key) {
continue
}

// Both are skipped where the entry is already `Required`, since that has
// been answered by Check and reporting it twice helps nobody.
Expand Down
18 changes: 14 additions & 4 deletions go/internal/shadow/mise/tables.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions go/internal/spec/spec.go
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@ type Cmd struct {
ArgRequiredElseHelp bool `json:"arg_required_else_help"`
DontDelimitTrailingValues bool `json:"dont_delimit_trailing_values"`
ArgsOverrideSelf bool `json:"args_override_self"`
SubcommandNegatesReqs bool `json:"subcommand_negates_reqs"`
}

// Subcommands is a command's children, in the order the spec declared them.
Expand Down Expand Up @@ -606,6 +607,7 @@ func (b *builder) command(c *Cmd, inherited argv.UnknownFlags) *argv.Command {
UnknownFlags: unknown,
ExternalSubcommand: c.ExternalSubcommand,
ArgRequiredElseHelp: c.ArgRequiredElseHelp,
SubcommandNegatesReqs: c.SubcommandNegatesReqs,
DontDelimitTrailingValues: c.DontDelimitTrailingValues,
Key: b.next(),
}
Expand Down
10 changes: 10 additions & 0 deletions go/internal/spec/spec_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,16 @@ func TestAFlagsDefaultCanBeDeclaredOnItsValue(t *testing.T) {
}
}

func TestSubcommandRequirementPolicyReachesTheCommandTable(t *testing.T) {
root, _ := build(&Spec{
Name: "ex", Bin: "ex",
Cmd: Cmd{Name: "ex", SubcommandNegatesReqs: true},
})
if !root.SubcommandNegatesReqs {
t.Error("subcommand_negates_reqs was lost while lowering JSON tables")
}
}

func TestVariadicFlagMinimumComesFromItsValue(t *testing.T) {
root, meta := build(&Spec{
Name: "ex", Bin: "ex",
Expand Down
1 change: 1 addition & 0 deletions lib/src/docs/models.rs
Original file line number Diff line number Diff line change
Expand Up @@ -485,6 +485,7 @@ impl From<&crate::SpecCommand> for SpecCommand {
arg_required_else_help: _,
dont_delimit_trailing_values: _,
args_override_self: _,
subcommand_negates_reqs: _,
// Rendered above, or deliberately absent from the docs model.
args: _,
flags: _,
Expand Down
Loading