Skip to content

Adding cli interfaces

CrackerJackMack edited this page Feb 14, 2013 · 12 revisions

A CLI interface is broken into two major parts:

  • module
  • action

Module

A module is a python module residing in SoftLayer/CLI/modules/<module>.py. The filename represented here is what is directly exposed after the sl command. I.e. sl cci is SoftLayer/CLI/modules/cci.py. The module's docblock is exposed as the description. SoftLayer.CLI.helpers contain all the helper functions and classes used for creating a CLI interface. This is a typical setup and how it maps:

"""Example module for developer guide"""

from SoftLayer.CLI.helpers import (
    CLIRunnable, Table, no_going_back, confirm, add_really_argument, CLIAbort)
$ sl example
usage: sl example [-h] {example} ...

Example module for developer guide

...

Action

Actions are implemented using classes in the module that subclass CLIRunnable. The actual class name is irrelevant for the implementation details as it isn't used anywhere.

class CLIRunnable(object):
    action = None

    @staticmethod
    def add_additional_args(parser):
        pass

    @staticmethod
    def execute(client, args):
        pass

The required interfaces are:

  • The docblock (doc)
  • action
  • def execute(client, args)
    • Don't forget the @staticmethod annotation!

A minimal implementation for sl example print would look like this:

class ExampleAction(CLIRunnable):
    """example print action for developer guide"""

    action = 'print'

    # always include @staticmethod !!!!
    @staticmethod
    def execute(client, args):
        print "EXAMPLE!"

Which in turn, works like this:

$ sl example print
EXAMPLE!

Output

The execute() method is expected to return either None or an instance of SoftLayer.CLI.helpers.Table. When None is returned, it assumes all output is handled inside of execute. SoftLayer.CLI.modules.dns.DumpZone is a great example of when handling your own output is ideal as the data is already coming back preformatted from the API. 99% of the time though, data will be raw and unformatted. As an example, we create sl example pretty as such:

class ExamplePretty(CLIRunnable):
    """ Example table output for developer guide"""

    action = 'pretty'

    @staticmethod
    def execute(client, args):
        # create a table with two columns: col1, col2
        t = Table(['col1', 'col2'])

        # align the data facing each other
        # valid values are r, c, l for right, center, left
        # note, these are suggestions based on the format chosen by the user
        t.align['col1'] = 'r'
        t.align['col2'] = 'l'

        # add rows 
        t.add_row(['test', 'test'])
        t.add_row(['test2', 'test2'])

        return t

Which gives us

$ sl example pretty
:.......:.......:
:  col1 : col2  :
:.......:.......:
:  test : test  :
: test2 : test2 :
:.......:.......:

$ sl example pretty --format raw
 test   test  
 test2  test2 

Formatting of the data represented in the table is actually controlled upstream from the CLIRunnable's making supporting more data formats in the future easier.

Adding arguments

Additional arguments can be added to the parser by implementing the add_additional_args(parser) interface. It is passed a reference of argparse (specifically a reference to the subparser). There is no need to return the parser at the end. The arguments are parsed before calling execute as is passed in the named type object (Namespace) as the second parameter to execute. For more indepth examples please refer to the argparse documentation and tutorial.

class ExampleArgs(CLIRunnable):
    """ example arguments interface """

    action = 'options'

    @staticmethod
    def add_additional_args(parser):
        parser.add_argument(
            '--test',
            default=False,
            action='store_true',
            required=False)

    @staticmethod
    def execute(client, args):
        if args.test:
            print "Just testing, move along..."
        else:
            print "This is fo'realz!"
$ sl example options
This is fo'realz!
$ sl example options --test
Just testing, move along...

Accessing the API

API access is available via the first argument of execute which will be an initialized copy of SoftLayer.API.Client. Please refer to using the api for further details on howto use the Client object.

Confirmations

All confirmations should be easily bypassed by checking for args.really. To inject --really in add_additional_args call SoftLayer.CLI.helpers.add_really_argument(parser). This ensures that --really is consistent throughout the CLI.

if args.really or confirm():
    ....

There are two primary confirmation prompts that both leverage SoftLayer.CLI.valid_response:

  • SoftLayer.CLI.helpers.confirm
  • SoftLayer.CLI.helpers.no_going_back

no_going_back accepts a single confirmation parameter that is generally unique to that action. This is similar to typing in the hostname of a machine you are canceling or some other string that isn't reactionary such as "yes", "just do it". Some good examples would be the ID of the object, a phrase "I know what I am doing" or anything of the like. It returns True, False, or None. The prompt string is pre-defined.

confirm is a lot more flexible in that you can set the prompt string, allowing default values, and such. But it's limited to 'yes' or 'no' values. Returns True, False, or None.

Aborting execution

When a confirmation fails, you will need to bail out of execute(). Raise a SoftLayer.CLI.helpers.CLIAbort with the message for the user as the first parameter. This will prevent any further execution and properly return the right error code.

if not args.really or not no_going_back('yes really do this'):
   raise CLIAbort("Aborting. Failed confirmation")

Clone this wiki locally