CLI tools is a great way to automate certain tasks for your CI needs. For example you re-use same shell scripts project to project. Or maybe you are integrating with some third-party service. Abstracting these tasks into your own CLI tool could be a great way to go.
You can think about some examples from Drupal world — each hosting provider has some sort of CLI tool. European Commission has one to automate certain DevOps tasks (https://github.com/openeuropa/task-runner).
In my case I was building one for interacting with Diffy — visual testing platform. Repository of the CLI tool is https://github.com/DiffyWebsite/diffy-cli
First, when I initially thought about idea of building a CLI tool I thought about the tools I used myself. Among them there were Drush and Terminus (Pantheon’s CLI tool). They both use https://robo.li/ so my choice was obviously to use this framework as well.
One of the best parts of Robo is that they is a Starter project (https://github.com/g1a/starter) that will create a code for you and also push it to your github.
Once you’ve done that you can start creating your commands right away.
And that is simply creating classes that extend
For example here is a command that saves a configuration variable:
You can definitively recognize annotations if you have build custom Drush commands in the past.
As for configuration Robo already promotes having a config file in your home folder as a YAML file. So for Diffy we store it in
There is a component https://github.com/consolidation/config/ that is used in Terminus and Drush. It is really great. Allows merging configs (imagine providing defaults and allowing override them) and also getting nested properties (get(‘foo.bar.baz’) type syntax).
But for my case I just needed to save an API key. So I went with a custom Config that simply saved or loaded parsed YAML file https://github.com/DiffyWebsite/diffy-cli/blob/master/src/Config.php.
Distribution as a PHAR file, self:update
Best part of the starter project is an example how you can pack the tool into single PHAR file.
Main idea is to use Travis to build and publish your PHAR file. Main idea is that you will need to use Travis CLI tool and run “travis setup releases”. Make sure to deploy released for tags only.
Because of the starter project sets the setSelfUpdateRepository() for the runner whenever in the future next release will be available — you can simply run
yourcommand self:update to self update the tool.