swift-argument-parser icon indicating copy to clipboard operation
swift-argument-parser copied to clipboard

Allow options to stop capturing if there are trailing arguments

Open rsalesas opened this issue 4 years ago • 1 comments

It would be good to be able to specify that an option should exclude catching trailing arguments. For example, it's quite common to have an option like:

--option a b c

but currently the only way to do this is to specify it should capture until the next -- option is encountered. That means that if you have a trailing argument, like this:

program command --option a b c filename.txt

The trailing argument filename.txt will be captured by the option. This would be easy to implement by allowing any trailing arguments to capture "first", leaving the option to capture the remainder. In any case, if there are insufficient parameters, it will result in an error.

rsalesas avatar Apr 01 '20 06:04 rsalesas

How would you distinguish trailing arguments from the option list? For example, given the following command:

struct Command: ParsableCommand {
  @Option(parsing: .upToNextOption)
  var options: [String]
  
  @Argument()
  var arguments: [String]
    
  func run() throws {
    print("options: \(options)")
    print("arguments: \(arguments)")
  }
}

all strings are captured by the option:

% command --option a b c filename.txt
options: ["a", "b", "c", "filename.txt"]
arguments: []

But capturing trailing arguments first, you'd get the equally wrong:

% command --option a b c filename.txt
options: []
arguments: ["a", "b", "c", "filename.txt"]

Both of the following solutions do currently work:

% command filename.txt --option a b c
options: ["a", "b", "c"]
arguments: ["filename.txt"]
% command --option a b c -- filename.txt
options: ["a", "b", "c"]
arguments: ["filename.txt"]

john-mueller avatar Jun 15 '20 20:06 john-mueller