Skip to content

jimschubert/kopper

Repository files navigation

Kopper

A simple Kotlin option parser

Maven Central

Maven Central

kopper is the simple Kotlin option parser library.

kopper-typed extends the kopper library to support delegated properties and parsing as simple as constructing an object. It includes the additional dependency of kotlin-reflect.

Examples

Manual parsing…

import us.jimschubert.kopper.*

fun main(args: Array<String>) {
    val parser = Parser()
    parser.setName("Kopper CLI")
    parser.setApplicationDescription("Kopper example application")

    parser.flag("q", listOf("quiet", "silent"), description = "Run silently")
    parser.option("f", listOf("file"), description = "File name")
    parser.flag("a", listOf("allowEmpty"))

    println(parser.printHelp())

    val arguments = parser.parse(arrayOf("-f", "asdf.txt", "--quiet=true", "trailing", "arguments" ))

    println("q=${arguments.flag("q")}")
    println("quiet=${arguments.flag("quiet")}")
    println("silent=${arguments.flag("silent")}")
    println("f=${arguments.option("f")}")
    println("file=${arguments.option("file")}")
    println("allowEmpty=${arguments.flag("allowEmpty")}")
    println("unparsedArgs=${arguments.unparsedArgs.joinToString()}")
}

Parser objects…

fun main(args: Array<String>) {
    val arguments = ExampleArgs(args)

    if (arguments.help) {
        println(arguments.printHelp())
        return
    }

    println("quiet=${arguments.quiet}")
    println("rate=${arguments.rate}")
    println("maxCount=${arguments.maxCount}")
}

class ExampleArgs(args: Array<String>) : TypedArgumentParser(args) {

    val quiet by BooleanArgument(self, "q",
            default = true,
            longOption = listOf("quiet", "silent"),
            description = "Run quietly"
    )

    val rate by NumericArgument(self, "r", 
            default = 1.0f, 
            description = "Rate"
    )

    val maxCount by NumericArgument(self, "m", 
            longOption = listOf("maxCount"), 
            default = 10, 
            description = "Max Count"
    )
}

Typed parser objects support BooleanArgument, StringArgument, and NumericArgument<T> property delegates. They also expose any additional args as a list of strings in the _etc_ property.

License

MIT License