fsprojects / Argu

A declarative CLI argument parser for F#
https://fsprojects.github.io/Argu
MIT License
453 stars 75 forks source link

How to add an optional boolean flag? #169

Closed KenBonny closed 2 years ago

KenBonny commented 2 years ago

I'm writing a little helper that renames files, but sometimes I want to know what the result of the rename is going to be before I do it. So I wanted to add an optional flag --whatif. I'm not sure how to do this in Argu.

I've tried

type RenameArgs =
    | WhatIf of bool

type RenameArgs =
    | WhatIf of bool option

type RenameArgs =
    | WhatIf

I've tried to get the result with and without a default value. But I get either the error that --whatif is missing, needs an explicit --whatif true|false or returns an null result. Could anybody help me get the syntax right?

I've googled this issue and found a lot of basic tutorials, but nothing with this example. I know it's possible as there is a default --help option.

eiriktsarpalis commented 2 years ago

It should work with the last example (WhatIf without any parameters). I'm surprised that it doesn't work, maybe a minimal reproduction might help.

KenBonny commented 2 years ago

Ok, fair warning, I'm still learning F# and the functional paradigms. I just figured out what I did wrong: I should've used parsedArgs.TryGetResult WhatIf instead of parsedArgs.GetResult WhatIf. The TryGetResult returns a WhatIf option which I can check. That works like a charm.

Thank you so much for telling me what the correct option was, that put me on the right path to figure things out!

This ticket may be closed. Chalk it up to me being a n00b at F#. 😳

bartelink commented 2 years ago

@KenBonny You should also be able to use .Contains like this

KenBonny commented 2 years ago

Cool, thanks for letting me know. At the moment, I'm really enjoying the match keyword, I'm trying to not do things the C# way. I know, if is still useful or I could use match with a bool, but I'm trying to learn the typing system better. Not having to worry (as much) about null is such a relief.

bartelink commented 2 years ago

That's not unreasonable, but DUs very much implement equality unless you ask them not to via NoEquality and participate in normal .NET conventions, so if you're checking whether a list oriented thing (like the parsed args) contains a value, it's not unreasonable - i.e. for a List, you'd use List.contains, and the .Contains here is the moral equivalent of that. More importantly for me, I find that it makes the processing of the argument clear and terse. (lots more examples of how to make it hairy in that repo though!)