dotnet / dotnet/command-line-api
Dynamic sub-commands
- Dominant language
- C#
- Stars
- 3.7k
- Forks
- 428
- PR merge metrics
- No merged PRs in 30d
Description
Hi all, following #1882 and #2046, I would like sharing a use case I didn't manage to implement in an elegant way with the current API.
This is a case of dynamic sub-commands, which is a topic already discussed in the past like in #1956, and somewhat used by `dotnet new`. My case might be a bit more challenging as the intent is to have a variable number of sub-commands levels, without limitations on options / arguments, while retaining all features of the API, including of course completion and help.
Consider a cli tool that would be a toolbox that could be done on files. My actual use case is slightly different but this application illustrates my use case pretty well. The sub-commands available would depend on the type and content of the file. So for example, one could do:
`filecli execute ~/file.txt append "hello world"`
But also:
`filecli execute ~/file.json pretty-format`
`filecli execute ~/file.bin dump-hex`
`filecli execute ~/file.bmp add watermark draft`
`filecli execute ~/*.txt ftp upload ftp://myserver.com`
For now the closest approach I found to implement such a dynamic functionality to have a two-pass execution with a middleware. The execute command is declared with a required argument, followed by a dummy argument with arity 0 to many. The middleware executes, the file type is evaluated, all matching sub-commands are added and a magic value is returned, meaning that a second execution is required. Then the invoke is called again, this time with the fully setup cli. This is surely inelegant and there are various issues with the approach though to get all functionality to work properly without side-effects.
I don't know if this is an interesting use case for the API design but given the ongoing and upcoming reviews, I thought it would be interesting to throw it out there. Happy to entertain this some more in case of interst.
Contributor guide
Assessment
This issue has not been assessed yet.