Skip to content

Instantly share code, notes, and snippets.

@daviddenton
Last active June 23, 2020 20:32
Show Gist options
  • Save daviddenton/65862a603af22cf541d21d5ff24e2741 to your computer and use it in GitHub Desktop.
Save daviddenton/65862a603af22cf541d21d5ff24e2741 to your computer and use it in GitHub Desktop.
Bunting - A nano command-line flags library extracted from http4k
import kotlin.properties.ReadOnlyProperty
import kotlin.reflect.KProperty
abstract class Bunting(val args: Array<String>) {
fun requiredFlag() = BuntingFlag()
fun defaultedFlag(default: String?) = BuntingFlag(default)
}
class BuntingFlag internal constructor(private val default: String? = null) : ReadOnlyProperty<Bunting, String> {
override fun getValue(thisRef: Bunting, property: KProperty<*>): String {
val windowed = thisRef.args.toList().windowed(2).map { it[0] to it[1] }.toMap()
return windowed["--${property.name}"] ?: default
?: throw IllegalArgumentException("no --${property.name} passed")
}
}
fun <T : Bunting> T.use(fn: T.() -> Unit): Unit = fn(this)
class MyGreatFlags(args: Array<String>) : Bunting(args) {
val user by requiredFlag()
val password by requiredFlag()
val version by defaultedFlag("0.0.0")
}
// run the main with: java (...) Mainkt --user foo --password bar
fun main(args: Array<String>) = MyGreatFlags(args).use {
println(user) // foo
println(password) // bar
println(version) // 0.0.0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment