node.jscommand-line-interfaceoclif

How can I create Git-style subcommands with oclif?


I'm writing a CLI using Heroku's CLI framework oclif. It works great, but I would like to have Git-like subcommands, something like that:

$ mycli mycommand subcommand

$ mycli mycommand subcommand --flags="are awesome"

$ mycli mycommand another-subcommand --name="John Doe"

I've gone through the docs but I couldn't find any information related to command structure, layout, hierarchy, etc. I could write mycommand as a normal command and have a switch on argv's first argument, but my subcommands accept different flags, so I lose oclif's ability to report some help when someone runs mycli help mycommand.

So, my question is: what is the best way to create subcommands using oclif?


Solution

  • You can create the following structure:

     - src
     --- commands // all your commands will be on this folder
     ----- subcommand1 // if you have more commands from after subcomand1 include them in this folder like the one bellow.
     ------ command.js // a simple command
     ----- subcommand2.js
    

    This would produce commands like:

    cli subcommand1 command --some-flag --some-argument="xpto"
    cli subcommand2 --some-other-flag --some-other-argument="WAT"
    

    One thing that I've noticed is that if you want to share some flags or arguments with other commands you either will have to use a base class for that or declare the flags/switches/arguments on another file and import them on the desired command