I've started to use ArgumentParser for some command-line programs and like it. What I am wondering about now is whether it would be appropriate to use it to parse commands that are issued from within a program?
ArgumentParser has a tendency to call exit when bad things happen and I don't want that to happen. I want to retain control and let the user try again. In my slight experimentation so far, I see that Cmd.parse(arguments) and Cmd.parseAsRoot(arguments) throw so I can catch errors and keep going.
Two questions really:
(a) is such a non-command-line usage bending the purpose of ArgumentParser too much? I have read far and wide, and not found any suggestion that others are using it like this. Is there reason I have missed?
(b) errors thrown by parseAsRoot such as:
CommandError(commandStack: [ArgsParzChex.Cmd],
parserError: ArgumentParser.ParserError.noValue(
forKey: ArgumentParser.InputKey(rawValue: "outputFile")))
require processing before being exposed to readers; is ArgumentParser's code that does this exposed in the public API?
nnnnnnnn
(Nate Cook)
2
I think only you can define how far is too far to bend the purpose of a library.
If you want to refactor a bit, it may make more sense to build the functionality of your tool as a separate type or even a separate module, and then have both the CLI and your other uses call into that.
Yes, you can call MyCommand.message(for: error) to get the user-visible text from any of the errors that the parser throws.
Absolutely! That's the way I'm heading. From the beginnings of Mac, I've liked the model of a [thin] expressive layer over core functionality .. MacPaint over QuickDraw! And thanks for the .message(for: error) .. I'd have found that eventually, but was struggling last night.
1 Like