Kest

Search

Search the documentation

Application

Commander

Command-line programs that use your services.

A command is a class marked @Command, declared like a controller (listed under controllers in a module, no @Injectable). It gets the same dependency injection as the rest of the application, so a command can use your services and repositories: seed a database, reindex, send a report.

@Command("greet", "Says hello")
class GreetCommand(private val greeter: Greeter) : CommandRunner {
    override fun run(args: CommandArgs): Int {
        println(greeter.hello(args.positional.firstOrNull() ?: "world", shout = args.flag("shout")))
        return 0                                  // the exit code
    }
}
 
@Module(providers = [Greeter::class], controllers = [GreetCommand::class]) class AppModule
 
fun main(argv: Array<String>) {
    val app = Kest.create<AppModule>()
    exitProcess(app.runCommand(argv, program = "shop"))
}
$ shop greet Ann --shout
HELLO, ANN!
$ shop help                  # lists every command
$ shop greet --help          # one command

CommandArgs understands --name=value, --name value, --flag, -f, -abc (three flags), plain words, and -- (everything after it is a word):

args.positionalthe words that are not options
args.flag("shout")true when --shout is given
args.option("to") / option("to", "default")a value or null / the default
args.int("limit")a whole number, or a clear error
args.required("token")the value, or the message --token is required

An exception thrown by a command prints its message and exits with code 1. An unknown command prints the list.

The container is created without starting an HTTP server, so a command starts fast. Use the same AppModule for the server and the commands, or a smaller module for a worker.

Read more