66 lines
2.3 KiB
Kotlin
66 lines
2.3 KiB
Kotlin
package com.infendro.cli.command.context
|
|
|
|
import com.infendro.cli.Dsl
|
|
import com.infendro.cli.command.Argument
|
|
import com.infendro.cli.command.Command
|
|
import com.infendro.cli.command.Option
|
|
import kotlin.reflect.KProperty
|
|
|
|
@Dsl
|
|
class Context internal constructor(
|
|
val command: Command,
|
|
val commands: List<Cmd>,
|
|
val arguments: List<Arg>,
|
|
val options: List<Opt>,
|
|
) {
|
|
class Cmd(
|
|
val name: String,
|
|
)
|
|
|
|
class Arg(
|
|
val value: Any,
|
|
)
|
|
|
|
class Opt(
|
|
val name: String,
|
|
val value: Any,
|
|
)
|
|
|
|
internal fun execute() = (command.execute)()
|
|
|
|
fun help() {
|
|
command.help?.let { println(it) }
|
|
}
|
|
|
|
operator fun Command.Key.getValue(thisRef: Any?, property: KProperty<*>): String = commands[index].name
|
|
|
|
private val <T : Any> Argument<T>.index: Int
|
|
get() = command.arguments.takeWhile { it != this }.sumOf { it.count }
|
|
|
|
@Suppress("UNCHECKED_CAST")
|
|
private val <T : Any> Argument<T>.value: T?
|
|
get() = arguments.getOrNull(index)?.value as? T
|
|
|
|
@Suppress("UNCHECKED_CAST")
|
|
private val <T : Any> Argument.Variable<T>.values: List<T>
|
|
get() = arguments.drop(index).take(count).map { it.value as T }
|
|
|
|
operator fun <T : Any> Argument.Required<T>.getValue(thisRef: Any?, property: KProperty<*>): T = value!!
|
|
operator fun <T : Any> Argument.OrElse<T>.getValue(thisRef: Any?, property: KProperty<*>): T = value ?: other
|
|
operator fun <T : Any> Argument.OrNull<T>.getValue(thisRef: Any?, property: KProperty<*>): T? = value
|
|
operator fun <T : Any> Argument.Variable<T>.getValue(thisRef: Any?, property: KProperty<*>): List<T> = values
|
|
|
|
@Suppress("UNCHECKED_CAST")
|
|
private val <T : Any> Option<T>.value: T?
|
|
get() = options.firstOrNull { it.name in names }?.value as? T
|
|
|
|
@Suppress("UNCHECKED_CAST")
|
|
private val <T : Any> Option.Variable<T>.values: List<T>
|
|
get() = options.filter { it.name in names }.map { it.value as T }
|
|
|
|
operator fun <T : Any> Option.Required<T>.getValue(thisRef: Any?, property: KProperty<*>): T = value!!
|
|
operator fun <T : Any> Option.OrElse<T>.getValue(thisRef: Any?, property: KProperty<*>): T = value ?: other
|
|
operator fun <T : Any> Option.OrNull<T>.getValue(thisRef: Any?, property: KProperty<*>): T? = value
|
|
operator fun <T : Any> Option.Variable<T>.getValue(thisRef: Any?, property: KProperty<*>): List<T> = values
|
|
}
|