I'm building a command-line interface (CLI) in Node.js using the 'commander' library. I've created a command called 'groupBy' which accepts two options:
'--paths' for a list of file paths.
'--jsonPaths' for a list of JSON paths.
I can successfully print something like this:
$ index.js groupBy --paths path1 path2 --jsonPaths jsonPath1 jsonPath2
In the given files path1, path2
I want to show jsonPath1, jsonPath2 values
Now, I want to add the ability to filter by values for specific JSON paths and print something like this:
In the given files path1, path2
I want to show jsonPath1, jsonPath2, jsonPath3 values
Not filtering on jsonPath1
Filtering by value1 on jsonPath2
Filtering by value2, value3 on jsonPath3
I'm struggling with the correct command structure and 'commander' implementation. I had an idea to use a command like this:
$ index.js groupBy --paths path1 path2 --jsonPaths jsonPath1 jsonPath2 jsonPath3 --filter jsonPath1 '' --filter jsonPath2 value1 --filter jsonPath3 value2 value3
However, when using 'commander,' the 'filter' option generates an array like this: [jsonPath, '', jsonPath2, value1, value2, value3]
. I can't distinguish between JSON paths and values, and I can't determine which values apply to which JSON paths.
I'm looking for a way to implement this functionality with 'commander.' Any ideas or suggestions would be greatly appreciated. Thank you!
'commander' library let customize option processing
It let replace the default string array by anything else.
So it is possible to use an array of object like this :
where jsonPath is the first arg of the option, and jsonValues are the others args of the option :
Have to apply argParser(value, previous) method on the Option object after the creation and before the addition to the command.
argParser
will be called for every arg of the option.value
is the current argprevious
is the value returned by the previous call, the first time his value is undefined. The final value offilters
depend of the last value returned in the last call toargParser
In each call, there is no no easy way to differenciate args from a first filter to the others. Have to parse all the args ourself. We can access to them by using
parent.args
property on the current command objectgroupBy
.In each call, it is not easy to know what arg is already parsed. So I choice to calculate the final result at the first call and return it. In the other calls, do nothing except returning the previous result.