WIP: Rework action parameters for more stable interface #1405
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Pull Request
Trying out an idea to improve code patterns now and in the future. Long description to work through the reasoning although the key code change is only a few lines of code!
Problem
In Commander v6 the action handler may get passed based on settings and unexpected args:
This has not worked out as nicely as hoped for moving to storing options safely!
Always always passing in command and calling
cmd.opts()
would only be one extra line of code, but would appear in most action handlers in most programs, and feels like paying for the increased safety.There are now multiple variations for passed options/command, so implementations will vary depending on the settings.
There are now multiple variations for passed options/command, so hard to write examples that work whatever the settings. (This is a downside I notice as a maintainer!)
With the extra args only sometimes present, the parameters are not consistent so trickier to write a generic action handler. e.g. Extra arguments : document and add configuration to fail if they exist #1268 (comment)
Solution
Always pass the action handler:
For backwards compatibility, the "options" might actually also be the command! The command still has options on it so the pattern still works.
This means code can access the options without an extra line of code in the common case, and easily access the command if needed without making configuration changes (just declare the parameter). The parameters are not affected by extra args so easier to write generic code if needed.
The one outlier might be if settings are
.storeOptionsAsProperties(false)
but.passCommandToAction(true)
which some people will have adopted in Commander v6. For backwards compatibility will probably pass command + command to avoid breaking this, but will change the documentation so this is less likely in new code.Related:
CommandStrict
to get all the recommended strict settings with latest best practices. #1404ChangeLog