swift-argument-parser
swift-argument-parser copied to clipboard
Support passing a negative number as an argument
Imagine a command like this
import ArgumentParser
struct Absolute: ParsableCommand {
@Argument() var number: Int
func run() throws {
print(abs(number))
}
}
Absolute.main()
you can run
command 5
and it works. but running
command -5
fails with Error: Missing expected argument '<number>'
which makes sense.
I would have expected being able to pass the argument as "-5"
but that doesn't work either.
Any advice on how to handle this?
We don't have a workaround for this right now. For an option, you can specify the .unconditional
parsing strategy, but arguments don't provide that capability. The changes in #29 will make it possible to add support for this, though.
This seems a common issue with CLI apps. ls -5
gives error ls: illegal option -- 5
. The solution there is ls -- -5
. That solution seems to also work for SAP v 0.1.0.
@fizker That's not quite true. ls
does support -1
as value for arguments. Consider for example
$ ls -D -1 -la /var/empty/
total 0
drwxr-xr-x 2 root sys 64 -1 .
drwxr-xr-x 36 root wheel 1152 -1 ..
-D
just selects the date/time format in the long (-l
) output. And as you can see, it lists -1
as the time.
@weissi I think you are confusing values for arguments with arguments. In your example, [-D format]
is the argument you are triggering, not -D
followed by -1
. The parser can easily handle that case, because it is expecting (and indeed requiring) a value after -D
, and thus will not attempt to parse it as an argument. Similarly, ls -D -l
will not display the date at all, because it never enables long format.
@fizker oh shoot, you're right. Sorry I thought this issue is about allowing negative numbers as values for arguments (like -D -1
) but actually it's about negative numbers as arguments themselves (like ping -6
).
@weissi No problem, it happens to everyone :). You are correct though in that ls
has an argument -1
:
-1 (The numeric digit “one”.) Force output to be one entry per line. This is the default when output is not to a terminal. ```
`ls` only fails for unknown arguments unless they are succeeding `--`