Skip to content

Command params

Christina-Kang edited this page Apr 5, 2018 · 2 revisions

By default all commands pass arguments as strings. That means the mapped Python functions are called with string arguments. To parse objects or convert the string arguments to another type, add CLI arguments to the associated commands.

Type conversion is performed to modify the command-line arguments into different Python types.

Arguments are added by default from the referenced python definition as string type. You only need to add to src/sfctl/params.py when the parameter has a non-string type.

Arguments

All arguments that require a type conversion are specified in the src/sfctl/params.py file. Each argument is specified inside an argument context.

For example, the --timeout argument, or -t, is defined with a global context:

with ArgumentsContext(self, '') as arg_context:
    arg_context.argument('timeout', type=int, default=60,
                         options_list=('-t', '--timeout'),
                         help='Server timeout in seconds')

timeout has global context because the second argument to the ArgumentsContext is an empty string. The second argument specifies the scope. It is the command that has an argument associated with it. For example, if the value is application create, then the argument conversions will apply only to the create command in application, and not any other command, since it uses the smallest scope.

Complex types

Take a look at how service create specifies int arguments.

with ArgumentsContext(self, 'service create') as arg_context:
    arg_context.argument('instance_count', type=int)
    arg_context.argument('load_metrics', type=json_encoded)

This code associates an argument specified by --instance-count with the command sfctl service create. Furthermore, it calls the function int on the string input prior to invoking the mapped Python command. The --load-metrics argument will be json decoded in the above example.

Custom types

The type argument for arg_context.argument can be any function that takes a string as input. It should return the parsed object. This optional argument can be used if you want to perform additional modification to an argument before invoking the mapped python function.

Optional arguments

Optional arguments can be specified in one of two ways. They can either be a custom argument, or an optional argument in the Python function definition.

If specifying an optional custom argument, specify the optional default argument when calling argument from the ArgumentsContext.

Otherwise, specify the default value inside the Python function definition.

Knack documentation

For more information, take a look at the Knack CLI package documentation.