Clikt - Kotlin 命令行接口


Apache-2.0
跨平台
Kotlin

软件简介

Clikt 是一个 Kotlin 库,Kotlin 的命令行接口,能够使编写命令行接口变得简洁直观,同时支持各种各样的用例,并允许在需要时进行高级定制。

Clikt 的特点:

  • 可以任意嵌套命令
  • 可组合,类型安全的参数值
  • 支持多种命令行接口风格

示例代码:

class Hello : CliktCommand() {
    val count: Int by option(help="Number of greetings").int().default(1)
    val name: String by option(help="The person to greet").prompt("Your name")

    override fun run() {
        for (i in 1..count) {
            echo("Hello $name!")
        }
    }
}

fun main(args: Array<String>) = Hello().main(args)

运行结果:

 $ ./hello --count=3
 Your name: John
 Hello John!
 Hello John!
 Hello John!

自动生成帮助参数:

$ ./hello --help
Usage: hello [OPTIONS]

Options:
  --count INT  Number of greetings
  --name TEXT  The person to greet
  -h, --help   Show this message and exit

错误处理:

$ ./hello --whoops
Usage: hello [OPTIONS]

Error: no such option: "--whoops".