Skip to content

Make it possible to pass boolean flags dynamically #7260

Closed

Description

@Veetaha

Related problem

Suppose we have a command that wraps another command where we want to forward --push and --release boolean flags to the inner command called build-imp.

def build-imp [--push, --release] {
    # This isn't a real example. Here we would actually do smth useful like building a docker image
    # optionally in release mode and optionally pushing it to the remote registry
    echo $"Doing a build with push: ($push) and release: ($release)"
}

At the time of this writing, it isn't possible to do this naturally. The following doesn't work, because nu complains that there are excessive positional parameters $push and $release:

def build [--push, --release] {
    build-imp --push $push --release $release
}
Error message
Error: nu::parser::extra_positional (link)

  × Extra positional argument.
   ╭─[entry #6:1:1]
 1 │ def build [--push, --release] {
 2 │     build-imp --push $push --release $release
   ·                      ──┬──
   ·                        ╰── extra positional argument
 3 │ }
   ╰────
  help: Usage: build-imp {flags}

This also doesn't work, although it compiles. Any invocation of build (even with all flags unset) results in $push and $release arguments inside build-imp set to true.

def build [--push, --release] {
    build-imp --push=$push --release=$release
}
Demo of the variant higher
❯ build
Doing a build with push: true and release: true
❯ build --push
Doing a build with push: true and release: true
❯ build --push --release
Doing a build with push: true and release: true
❯ build --release
Doing a build with push: true and release: true

Workarounds

Combinatorial explosion

Handle all possible combinations of all flags with an if-else chain. This solution preserves the desired command signature but requires a huge amount of boilerplate. This solution suffers from copy-paste exponentially (pow(2, number_of_flags)) with the total number of flags to forward. The situation is worsened if there are other arguments to pass other than the flags that will also need to be copy-pasted

def build [--push, --release] {
    if $push and $release {
        build-imp --push --release
    } else if $push and not $release {
        build-imp --push
    } else if not $push and $release {
        build-imp        --release
    } else {
        build-imp
    }
}
A variation of the solution that uses a bit nicer grouping of combinations with bitflags
def build [--push, --release] {
    let invocations = [
        { build-imp                  }
        { build-imp           --push }
        { build-imp --release        }
        { build-imp --release --push }
    ]

    do ($invocations | get (($release | into int) bit-shl 1 bit-or ($push | into int)))
}

Use non-boolean type for flags

UPD: there was found a better version of this workaround that allows you to use booleans, but doesn't enable a bare --flag syntax: #7260 (comment)

The downside of this approach is that we make the API uglier, although the boilerplate doesn't grow exponentially here. We can define the underlying command with int arguments, but also make a wrapper that provides the same nice boolean flag API and just converts its arguments to integers.

def build-imp-int [--push: int, --release: int] {
    let $push = $push == 1
    let $release = $release == 1
    # ...
}

# If this function needs to be reused in a bunch of places where boolean flags API suffices,
# then we may define a simple wrapper around it that takes boolean flags and forwards
# them to the inner function with `int` flags, but that's also boilerplate, so not ideal:
def build-imp [--push, --release] {
    build-imp-int --push ($push | into int) --release ($release | into int)
}

Describe the solution you'd like

The easiest solution that may probably be implemented quickly is to allow using --flag=boolean_expression syntax for boolean flags. The equals sign (=) between the argument name and the boolean expression disambiguates that the argument following the boolean flag isn't a positional parameter.

Right now we can pass literally any expression using --flag=expression, but that results in the boolean $flag variable to be set to true unconditionally. Maybe this was the intended solution of this problem at all, but it doesn't work today. Maybe it's a bug then?

Describe alternatives you've considered

A more general solution to the problem may also encompass solving the problem of passing optional flags to external commands.

For example, today we can't do this:

let push = if condition { "--push" } else { null }

docker buildx build $push ...args...

Because nutshell will complain that it can't convert null to string. If we were to use an empty string instead of null nushell would forward it to the external binary as a separate empty string positional parameter. So instead we have to do this today:

let args = [...args...]
let args = if condition { $args | prepend "--push" } else { $args }

docker buildx build $args

This works because an array is spread to positional parameters when invoking an external binary from nushell, but it also looks like some kind of inconvenient dark magic.

A more general problem is omitting named parameters to commands. I think it deserves a special syntax like this:

docker buildx build (--push $push)? (--named-arg-with-value $value)?

With the question mark operator appended nushell would omit the parameter if the value is false or null for example. This is quite a naive first-comes-to-mind solution. I bet there could be some limitations with this, so feel free to share better proposals.

Activity

  1. added
    category:enhancement
    on Nov 27, 2022
  2. melMass commented on Nov 28, 2022

    @melMass
    Contributor

    Do you have other use cases for flags that accepts booleans or is it just to solve passing them to external commands?
    The alternatives part I believe this is doable with run-external, I haven't tried myself but I had the exact same case to solve a few weeks ago and someone mentioned run-external on discord recently I think it fits this usecase.

  3. Veetaha commented on Nov 28, 2022

    @Veetaha
    Author

    I don't think run-external improves the experience for external commands. How would one use it to pass the --push flag based on the boolean value stored in $push variable? I don't see other approaches than specified in alternatives (i.e. make the array of args and extend it dynamically).

  4. melMass commented on Nov 28, 2022

    @melMass
    Contributor

    Maybe I was not clear but I meant that this shoud be doable in run-external

    def do_it [--push] {
    	let flags = []
    
    	let flags = if ($push) {
    		$flags | append "--push"
    	} else {
    		$flags
    	}
    	run-external "echo" $flags
    }

    Obviously not ideal I agree

  5. melMass commented on Nov 28, 2022

    @melMass
    Contributor

    Oh my bad, while first reading the issue I skipped exactly this part of your issue (where you suggest the same solution without run-external)!

  6. Veetaha commented on Nov 28, 2022

    @Veetaha
    Author

    @melMass

    Regarding the uses case for non-external commands. I have a development script that has commands:

    • "main docker build" [--push, --release] - build the app's docker image
    • "main deploy" [--release] - deploy the app and automatically build it; it has to inherit the same --release flag as build command

    I need to forward the release flag from deploy command into build command, and now it looks quite clumsy due to the limitation described in this issue.

  7. added
    semantics
    on Nov 28, 2022
  8. theAkito commented on Apr 18, 2023

    @theAkito

    Because nutshell will complain that it can't convert null to string. If we were to use an empty string instead of null nushell would forward it to the external binary as a separate empty string positional parameter.

    Related to #7033 due to quote & the whole issue in its entirety.

    This whole forced to String conversion problem is a huge super-topic. That it is really hard to dynamically generate command chains is one of its biggest effects.

  9. amtoine commented on Apr 18, 2023

    @amtoine
    Member

    @Veetaha
    does the following solve your issue? 😋

    def build-imp [--push: bool = false, --release: bool = false] {
        echo $"Doing a build with push: ($push) and release: ($release)"
    }
    
    def build [--push, --release] {
        build-imp --push $push --release $release
    }

    which gives

    >_ build
    Doing a build with push: false and release: false
    >_ build --push
    Doing a build with push: true and release: false
    >_ build --release
    Doing a build with push: false and release: true
    >_ build --push --release
    Doing a build with push: true and release: true
  10. cumber commented on May 20, 2023

    @cumber

    @amtoine Honestly I kind of expected something like def build [--push] to be syntactic sugar for def build [--push : bool = false], and build --push to be syntactic sugar for build --push=true. It's really surprising that build --push=false neither passes $push as false nor throws a syntax error!

  11. amtoine commented on May 20, 2023

    @amtoine
    Member

    the build --push=false part looks a bit odd 🤔

    however, the rest looks sensible to me

    def foo [--bar] {
        if $bar {
            print "bar!"
        } else {
            print "no bar..."
        }
    }

    does give

    > foo
    no bar...
    
    > foo --bar
    bar!
    

    which is expected, isn't it? 😋

  12. melMass commented on May 20, 2023

    @melMass
    Contributor

    I think the OP wants to conditionally set flags for a wrapper. Hence the need for a value flag (--b:bool). If I understand right this is to wrap externals.
    Although there is no equal in nu arg so you must do --b true

    Afaik there is no fix for all that yet

  13. Veetaha commented on Aug 25, 2023

    @Veetaha
    Author

    The suggestion from @amtoine regarding the def build-imp [--push: bool = false, --release: bool = false] slightly improves the situation, but then you can no longer call the build-imp this way:

    build-imp --push --release

    You can only call it this way now

    build-imp --push true --release false
    
  14. amtoine commented on Aug 25, 2023

    @amtoine
    Member

    The suggestion from @amtoine regarding the def build-imp [--push: bool = false, --release: bool = false] slightly improves the situation, but then you can no longer call the build-imp this way ...

    this is very true @Veetaha 👍

    i use this trick inside modules, when the build-imp-like command wouldn't leak to the outside, which is fine when it does not impact the user API imo 😋

    but yeah for interactive usage, that might not be ideal 😕

  15. crabdancing commented on Sep 14, 2023

    @crabdancing

    I ran into this too! Glad to see there's already an issue on it. This isn't a general solution, but it's what I came up with to soften the pain of this:

    export def "append-if" [cond: bool, target: any] -> list {
        if $cond {
            $in | append $target
        } else {
            $in
        }
    }
    
    # List installed unit files
    export def "sctl list unit-files" [
        --all: bool # List all unit files
        --user: bool # Run as non-root
    ] {
        let args = ['-o' 'json'] | append-if $all "--all" | append-if $user "--user"
        systemctl list-unit-files $args | from json
    }

    Unfortunately, it doesn't work on Nushell's custom commands

  16. 12 remaining items

  17. crabdancing commented on Nov 14, 2023

    @crabdancing

    Is the reason this was done purely a matter of syntactic uniformity? It seems the community is leaning in the direction of special behavior for boolean flags, anyway. (Which could be later made uniform by having flags accept either --my-flag my-value or --my-flag=my-value.) The ecosystem is small enough still that a breaking change isn't that big a deal (At least, IMO!) and is worth setting a standard that will cause the least sadness. :P

  18. flying-sheep commented on Nov 14, 2023

    @flying-sheep
    Contributor

    I think if you add an --xy as a boolean flag, you should be able to pass it alone to enable it, but also optionally add --xy=false to disable it. Or at least, that's the best I've come up with so far. The downside is, I don't know how well it fits with the rest of the syntactic standards.

    That would be a great solution if we lived in a vacuum (i.e. it was a great solution for React when they were free to design JSX however they liked: <Comp prop /> is the same as <Comp prop={true} />, so you can pass a variable when deriving this prop value and have concise syntax when not.)

    But as I said above: It doesn’t help in the slightest with 3rd party commands. There I still have to do stuff like

    let args = ([(if ($info) { ['-i'] } else []), $pkg] | flatten)
    ^my-cmd $args
  19. theAkito commented on Nov 14, 2023

    @theAkito

    But as I said above: It doesn’t help in the slightest with 3rd party commands. There I still have to do stuff like

    Already pointed as well, that this is actually a bigger, essential issue, which crosses a lot of Nushell surface.

    Related to #7033 due to quote & the whole issue in its entirety.

    This whole forced to String conversion problem is a huge super-topic. That it is really hard to dynamically generate command chains is one of its biggest effect

    This specific super-issue is already tracked in #7033.

  20. WindSoilder commented on Nov 14, 2023

    @WindSoilder
    Contributor

    Thanks for all your comments! Let me try to summarize the path we're trying to move:

    switch

    For the given example:

    def foo [--xyz] { print $xyz }

    It needs to support: foo(print false), foo --xyz(print true), foo --xyz=false(print false), foo --xyz=true(print true), and we can only set it with true or false, something like this will result to error: foo --xyz=1

    It doesn't support: foo --xyz false, foo --xyz true (For the reason please check the comment: #7260 (comment))

    flag which takes boolean value

    For the given example:

    def foo2 [--xyz: bool] { print $xyz }
    def foo2 [--xyz = false] { print $xyz }

    I'd like to make it as normal as other flags which takes a value for consistency (I have the same institution to #7260 (comment)). Which is handled by #10456

  21. theAkito commented on Nov 14, 2023

    @theAkito

    It needs to support: foo --xyz, foo --xyz=false, foo --xyz=true, and we can only set it with true or false, something like this will result to error: foo --xyz=1

    The default will be set to false though, right?

  22. WindSoilder commented on Nov 14, 2023

    @WindSoilder
    Contributor

    Yup, if we call foo directly, the value of $xyz is false, I've updated the comment.

  23. cumber commented on Nov 14, 2023

    @cumber

    Thanks @WindSoilder, that sounds exactly right.

    It needs to support: foo(print false), foo --xyz(print true), foo --xyz=false(print false), foo --xyz=true(print true)

    I assume you intended this, but just to be explicit: it should also support foo --xyz=<EXPR>, where <EXPR> stands for any expression that could be used as a flag argument (provided it results in a Boolean value of course). Most usefully the expression could be a variable reference, e.g. foo --xyz=$abc.

  24. added a commit that references this issue on Nov 22, 2023
    6cfe35e
  25. added this to the v0.88.0 milestone on Nov 22, 2023
  26. added a commit that references this issue on Feb 20, 2024
    c0c514f
  27. wthueb commented on Jan 18, 2026

    @wthueb

    #11057 doesn't close this issue for external commands. You still need to do the if/else/match thing as of 0.109.1, unless I'm wildly missing something. This seems like a big deal and comes up for me a lot, usually with flags like --verbose (-v) and wanting to forward them to external commands called. Most I've come across don't support the --flag=false syntax.

  28. flying-sheep commented on Jan 18, 2026

    @flying-sheep
    Contributor

    Probably not possible. There are two conventions here; a) --flag/--no-flag and b) only --flag, which behave differently:

    passed a) --flag /
    --no-flag
    b) only
    --flag
    --flag on on
    --no-flag off error
    nothing ???1 off

    Footnotes

    1. this is the issue: a command which has a --flag/--no-flag pair as convention might default to --no-flag ↩

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    category:enhancementsemantics

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions