If you are exposing behaviors of your model objects as CLI commands, the easiest way to achieve it is to put @CLIMethod on a method of your model object. See Queue.clear() as an example.
In addition to the command name as specified in the annotation, you also need to define "CLI.command-name.shortDescription" as a message resource, which captures one line human-readable explanation of the command (see CLICommand.getShortDescription()).
public class AbstractItem {
@CLIMethod(name="delete-job")
public synchronized void delete() throws IOException, InterruptedException {
performDelete();
if (this instanceof TopLevelItem) {
Jenkins.get().deleteJob((TopLevelItem)this);
}
Jenkins.get().rebuildDependencyGraph();
}
...
}
Notice that the method is an instance method. So when the delete-job command is executed, which job is deleted?
To resolve this, you also need to define a CLI resolver
, which uses a portion of arguments and options to determine the instance object that receives a method call.
@CLIResolver
public static AbstractItem resolveForCLI(
@Argument(required=true,metaVar="NAME",usage="Job name") String name) throws CmdLineException {
AbstractItem item = Jenkins.get().getItemByFullName(name, AbstractItem.class);
if (item==null)
throw new CmdLineException(null,"No such job exists:"+name);
return item;
}
Of all the resolver methods that are discovered, Jenkins picks the one that returns the best return type.
It doesn’t matter where the resolver method is defined, or how it’s named.
Both resolver methods and CLI methods can have any number of args4j annotations, which causes the parameters and arguments to be injected upon a method invocation.
All the other unannotated parameters receive null.
Combined with the stapler method binding, this enables you to make your method invokable from both CLI and HTTP.