Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for automatic negation flags #815

Open
6 tasks
kbknapp opened this issue Jan 14, 2017 · 24 comments
Open
6 tasks

Add support for automatic negation flags #815

kbknapp opened this issue Jan 14, 2017 · 24 comments
Labels
A-builder Area: Builder API A-derive Area: #[derive]` macro API A-parsing Area: Parser's logic and needs it changed somehow. C-enhancement Category: Raise on the bar on expectations 💸 $10 S-waiting-on-design Status: Waiting on user-facing design to be resolved before implementing

Comments

@kbknapp
Copy link
Member

kbknapp commented Jan 14, 2017

Add a way to automatically generate flags that override (or negate) other flags. This can be done manually already, but doing so for an entire CLI can be tedious, painful, and error prone. Manually doing so will also pollute the --help output.

This proposal offers a way to automatically have these negation flags generated on a case by case basis, or across all flags in the command. This proposal also offers a way to have these negation flags listed in the --help message or hidden.

Design

A negation flag would simply take the long version of the regular flag and pre-pend no; for exmaple --follow would get a --no-follow. If a flag only specifies a short version, the no would be prepended to the short such as -L gets --no-L.

When parsing occurs, if a negation flag is found, and the negated argument was used, it functions exactly like a override that is already supported.

Functionally the following two examples are equivilant:

app.arg(Arg::with_name("regular")
        .long("follow-links")
        .help("follows symlinks")
        .overrides_with("override"))
    .arg(Arg::with_name("override)
        .long("no-follow-links")
        .help("does not follow symlinks"))

New proposal:

app.arg(Arg::with_name("regular")
        .long("follow-links")
        .help("follows symlinks")
        .overridable(true))

Concerns

There are two primary concerns with this approach.

Flags that already contian "no"

A flag which already starts with no such as --no-ignore would end up getting a double no in the form of --no-no-ignore. This actually makes sense and is consistent, but looks strange at first glance. An alternative would be to check if a flag starts with no and simply remove the no, i.e. --no-ignore becomes --ignore but this has the downside of additional processing at runtime, becomes slightly more confusing, and has a higher chance of a conflict.

Conflicting names

If a user has selected to auto-generate a negation flag, and the negating flag long conflicts with a flag already in use, a panic! will occur. Example, --ignore and --no-ignore is already defined elsewhere, and the user has selected to automaticlly generate negation flags, this will cause --ignore to generate a --no-ignore flag which already exists causing a panic!. The fix is to either not use a sweeping setting that applies ot all flags indescriminantly, or to change/remove the already defined --no-ignore flag.


Progress

  • Add AppSettings::GenerateNegationFlags which does the above, but automatically for all flags.
    • docs
    • tests
  • Add AppSettings:GenerateHiddenNegationFlags which hides all these negation flags.
    • docs
    • tests

See the discussion in BurntSushi/ripgrep#196

Relates to #748


Edit: Removed Arg::overridable(bool) because this can already be done manually by making another flag.

@kbknapp kbknapp added this to the 2.21.0 milestone Jan 30, 2017
@kbknapp kbknapp added C: flags and removed C: args labels Jan 30, 2017
@kbknapp kbknapp mentioned this issue Feb 15, 2018
87 tasks
@kbknapp kbknapp added W: 3.x and removed W: 2.x labels Jul 22, 2018
@kbknapp kbknapp modified the milestones: 2.21.0, v3.0 Jul 22, 2018
@pksunkara pksunkara modified the milestones: 3.0, 3.1 Apr 10, 2020
@jacobsvante
Copy link

Great proposal @kbknapp. Having a --no-* equivalent just feels natural when it comes to boolean values.

Perhaps this could even be the default, considering that v3 is still in beta? The user would then have to call .overridable(false) instead to get the old behavior.

@pksunkara
Copy link
Member

Not all single flags are need overridable flags. From looking at the clis, this is a minority use case. Which is why this won't be a default behaviour.

@blyxxyz
Copy link
Contributor

blyxxyz commented Feb 15, 2022

EDIT: This can be done more cleanly nowadays, see #815 (comment)

We're currently using this workaround to generate negation flags for all options:

    use once_cell::sync::OnceCell;

    let opts: Vec<_> = app.get_arguments().filter(|a| !a.is_positional()).collect();

    // We use a OnceCell to make strings 'static. Watch out that you don't
    // construct the app multiple times with different arguments because it'll
    // only be initialized once and reused thereafter.
    // Box::leak() would also work, but it makes valgrind unhappy.
    static ARG_STORAGE: OnceCell<Vec<String>> = OnceCell::new();
    let arg_storage = ARG_STORAGE.get_or_init(|| {
        opts.iter()
            .map(|opt| format!("--no-{}", opt.get_long().expect("long option")))
            .collect()
    });

    let negations: Vec<_> = opts
        .into_iter()
        .zip(arg_storage)
        .map(|(opt, flag)| {
            clap::Arg::new(&flag[2..])
                .long(flag)
                .hide(true)
                .overrides_with(opt.get_name())
        })
        .collect();

    app = app.args(negations);

(It also creates --no-help and --no-version, which is weird but harmless.)

@epage
Copy link
Member

epage commented Jun 13, 2022

With the new ArgAction API, one approach we could take for this:

Arg::new("force")
    .action(clap::builder::SetBool)
    .long("force")
    .alias("no-force")

The SetBool action would effectively be

let alias: &str = ...;  // either `force` or `no-force`
let default_missing_value = if alias.starts_with("no-") {
    "false"
} else {
    "true"
};
...

The downside is you wouldn't be able to control whether shorts would set true or false.

@blyxxyz
Copy link
Contributor

blyxxyz commented Jun 13, 2022

In xh we support negating all options, not just boolean options. --style=solarized --no-style becomes a no-op. I don't know how common that is (we imitated it from HTTPie), but it would be nice to have as a supported case.

The prefix check feels too magical, if I found that example in the wild I wouldn't know where to look for an explanation.

@epage
Copy link
Member

epage commented Jun 13, 2022

In xh we support negating all options, not just boolean options. --style=solarized --no-style becomes a no-op. I don't know how common that is (we imitated it from HTTPie), but it would be nice to have as a supported case.

Thanks for bringing up this use case. I don't tend to see this too often. Even if we don't provide a native way of supporting it, there would always be overrides_with for clearing it out.

Speaking of, how are you implementing that today? I looked at your Parser didn't see a --no-style defined.

The prefix check feels too magical, if I found that example in the wild I wouldn't know where to look for an explanation.

I can understand. It is dependent on people thinking to check the the documentation for SetBool.

@blyxxyz
Copy link
Contributor

blyxxyz commented Jun 13, 2022

Speaking of, how are you implementing that today?

See a few comments back: #815 (comment)

The new reflection came in very handy!

@epage
Copy link
Member

epage commented Jun 13, 2022

Oh, I had overlooked in that comment that you meant negations for all options and not just flags.

@dhruvkb
Copy link

dhruvkb commented Aug 7, 2022

Coming from the Python argparse camp, I heavily used the --*/--no-* pattern in my apps. This feature would be very helpful for me.

With the new ArgAction API, one approach we could take for this

@epage is it possible to define our own actions apart from the included standard ones? I couldn't find any examples for this so if you could point me to one, that'd be very helpful.

@tmccombs
Copy link
Contributor

tmccombs commented Aug 7, 2022

is it possible to define our own actions apart from the included standard ones?

Not currently. but I think I saw something saying that was on the roadmap.

@epage
Copy link
Member

epage commented Aug 8, 2022

@dhruvkb the plan is to eventually support it but not yet.

Current blockers:

  • Seeing how actions interact with the parser and other systems as the project evolves to make sure the we expose the right behavior.
  • Work through how to interact with parts of the system that are currently internal.

@dhruvkb
Copy link

dhruvkb commented Aug 8, 2022

I'll subscribe to the issue for updates. In the meantime I've got a variant of @blyxxyz's snippet working for me. Thanks!

@epage
Copy link
Member

epage commented Aug 25, 2022

While I don't think this is the way we should go, I thought I'd record how CLI11 solves this problem: runtime parsing of a declaration string. See https://cliutils.github.io/CLI11/book/chapters/flags.html

charliermarsh added a commit to astral-sh/ruff that referenced this issue Sep 19, 2023
I'd really like this to render as `--preview / --no-preview`, but I
looked for a while in the Clap internals and issue tracker
(clap-rs/clap#815) and I really can't figure
out a way to do it -- this seems like the best we can do? It's also what
they do in Orogene.

Closes #7486.
@fzyzcjy
Copy link

fzyzcjy commented Nov 13, 2023

Hi, is there any updates? Thanks! Especially, it would be great to have one in Parser derivation mode, instead of the builder mode.

P.S. I found https://jwodder.github.io/kbits/posts/clap-bool-negate/ but the workaround is not super neat IMHO

@blyxxyz
Copy link
Contributor

blyxxyz commented Nov 13, 2023

FWIW, in xh we've moved to a still cleaner implementation by enabling clap's string feature and doing this:

let negations: Vec<_> = app
    .get_arguments()
    .filter(|a| !a.is_positional())
    .map(|opt| {
        let long = opt.get_long().expect("long option");
        clap::Arg::new(format!("no-{}", long))
            .long(format!("no-{}", long))
            .hide(true)
            .action(ArgAction::SetTrue)
            // overrides_with is enough to make the flags take effect
            // We never have to check their values, they'll simply
            // unset previous occurrences of the original flag
            .overrides_with(opt.get_id())
    })
    .collect();

app.args(negations)
    .after_help("Each option can be reset with a --no-OPTION argument.")

It no longer feels like a hacky workaround so I'm pretty happy with it. It's cool how flexible clap has become.

@spenserblack
Copy link

spenserblack commented Nov 13, 2023

For my specific use-case, it would be perfect for me if I could use #[derive(Parser)] and use this feature to create an Option<bool> which would automatically have --foo and --no-foo combined as a single --[no-]foo in the help message. IMO --[no-]foo is a very readable and concise way to say "there are two mutually exclusive flags, and the app will decide if neither are specified." For example, --[no-]color to either force colors to be included or excluded in a CLI output, and the executable would try to detect color support if neither are specified.

@pacak
Copy link

pacak commented Nov 13, 2023

use this feature to create an Option<bool> which would automatically have

In my experience you only use Option<bool> if you want to handle case when user did not specify a value differently than from it being true or false, otherwise you just stick to bool and populate the default value from the parser. Option<bool> works on small examples but if you share configurations between apps or even use it in multiple places in the same app you can get into cases where different parts of the app treat None differently.

@fzyzcjy
Copy link

fzyzcjy commented Nov 13, 2023

Thank you! That looks helpful

@kenchou
Copy link

kenchou commented Nov 23, 2023

If the #[derive(Parser)] could implement a boolean flag like Python click,
it would be perfect, combining both readability and flexibility.

@click.option('--color/--no-color', default=False)
@click.option('--enable-option/--disable-option', default=False)
@click.option('--with-something/--without-something', default=False)

Imagine:

    /// Given that the default value is true, providing a short option should be considered as false. And vice versa.
    #[arg(short = "C", long = "--color/--no-color", default_value = "true")]
    color_flag: bool,

    /// Explicitly providing a short option maps to true/false.
    #[arg(short = "o/O", long = "--enable-option/--disable-option", default_value = "true")]
    some_option_flag: bool,

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-builder Area: Builder API A-derive Area: #[derive]` macro API A-parsing Area: Parser's logic and needs it changed somehow. C-enhancement Category: Raise on the bar on expectations 💸 $10 S-waiting-on-design Status: Waiting on user-facing design to be resolved before implementing
Projects
None yet
Development

No branches or pull requests