1.4.0 release #9
@@ -37,11 +37,11 @@ fun main(args: Array<String>) = cli("application") {
|
||||
// declare command "greet"
|
||||
command("greet") {
|
||||
// declare arguments
|
||||
val speakersArg by Argument.string("speakers").variable(min = 1)
|
||||
val speakersArg by argument.string("speakers").variable(min = 1)
|
||||
|
||||
// declare options
|
||||
val greetingOpt by Option.string("greeting", "greet", "g").orElse("Hello")
|
||||
val nameOpt by Option.string("name", "n").orNull()
|
||||
val greetingOpt by option.string("greeting", "greet", "g").orElse("Hello")
|
||||
val nameOpt by option.string("name", "n").orNull()
|
||||
|
||||
execute {
|
||||
// retrieve the arguments and options
|
||||
@@ -56,7 +56,7 @@ fun main(args: Array<String>) = cli("application") {
|
||||
}
|
||||
|
||||
// declare fallback command
|
||||
fallback("value") { valueArg ->
|
||||
fallback.string("value") { valueArg ->
|
||||
execute {
|
||||
// retrieve the value used for the fallback command
|
||||
val value by valueArg
|
||||
|
||||
@@ -1,20 +1,22 @@
|
||||
package com.infendro.cli.command
|
||||
|
||||
import com.infendro.cli.Dsl
|
||||
import com.infendro.cli.command.argument.Argument
|
||||
import com.infendro.cli.command.context.Context
|
||||
import com.infendro.cli.command.context.Parser
|
||||
import com.infendro.cli.command.context.ContextParser
|
||||
import com.infendro.cli.command.help.DefaultHelpRenderer
|
||||
import com.infendro.cli.command.help.HelpRenderer
|
||||
import com.infendro.cli.command.option.Option
|
||||
import com.infendro.cli.exception.build.*
|
||||
import com.infendro.cli.parser.*
|
||||
import com.infendro.cli.util.Regex
|
||||
import com.infendro.cli.util.Regex.ARGUMENT
|
||||
import com.infendro.cli.util.Regex.COMMAND
|
||||
import com.infendro.cli.util.Regex.OPTION
|
||||
import kotlin.reflect.KProperty
|
||||
|
||||
class Command private constructor(
|
||||
sealed class Command private constructor(
|
||||
val parent: Command?,
|
||||
val name: String,
|
||||
val fallback: Boolean,
|
||||
val commands: List<Command>,
|
||||
val arguments: List<Argument<*>>,
|
||||
val options: List<Option<*>>,
|
||||
@@ -31,60 +33,130 @@ class Command private constructor(
|
||||
get() = renderer.render(this)
|
||||
|
||||
fun run(args: Array<String>) {
|
||||
when (val result = Parser(this, args).parse()) {
|
||||
is Parser.Result.Success -> result.context.execute()
|
||||
is Parser.Result.Help -> result.command.help?.let { println(it) }
|
||||
is Parser.Result.Failure -> {
|
||||
println("error: ${result.exception.message}")
|
||||
result.command.help?.let { println("\n$it") }
|
||||
when (val result = ContextParser(this, args).parse()) {
|
||||
is ContextParser.Result.Success -> result.context.execute()
|
||||
is ContextParser.Result.Help -> result.command.help?.let { print(it) }
|
||||
is ContextParser.Result.Failure -> {
|
||||
println("error: ${result.error.message}")
|
||||
result.command.help?.let {
|
||||
println()
|
||||
print(it)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class Named(
|
||||
parent: Command?,
|
||||
name: String,
|
||||
commands: List<Command>,
|
||||
arguments: List<Argument<*>>,
|
||||
options: List<Option<*>>,
|
||||
execute: Context.() -> Unit,
|
||||
renderer: HelpRenderer,
|
||||
) : Command(parent, name, commands, arguments, options, execute, renderer) {
|
||||
class Builder(
|
||||
name: String,
|
||||
) : Command.Builder<Named>(name) {
|
||||
override fun create() =
|
||||
Named(parent, name, commands, arguments, options, execute, renderer)
|
||||
}
|
||||
}
|
||||
|
||||
class Fallback<T : Any>(
|
||||
parent: Command?,
|
||||
val key: Key<T>,
|
||||
val parser: Parser<T>,
|
||||
name: String,
|
||||
commands: List<Command>,
|
||||
arguments: List<Argument<*>>,
|
||||
options: List<Option<*>>,
|
||||
execute: Context.() -> Unit,
|
||||
renderer: HelpRenderer,
|
||||
) : Command(parent, name, commands, arguments, options, execute, renderer) {
|
||||
class Builder<T : Any>(
|
||||
val parser: Parser<T>,
|
||||
name: String,
|
||||
) : Command.Builder<Fallback<T>>(name) {
|
||||
internal val key = Key<T>()
|
||||
|
||||
override fun create() =
|
||||
Fallback(parent, key, parser, name, commands, arguments, options, execute, renderer)
|
||||
}
|
||||
|
||||
class Key<T>
|
||||
}
|
||||
|
||||
@Dsl
|
||||
class Builder internal constructor(
|
||||
private val level: Int,
|
||||
private val name: String,
|
||||
private val fallback: Boolean,
|
||||
var renderer: HelpRenderer,
|
||||
sealed class Builder<COMMAND : Command>(
|
||||
protected val name: String,
|
||||
) {
|
||||
private var parent: Command? = null
|
||||
private val builders = mutableListOf<Builder>()
|
||||
private val arguments = mutableListOf<Argument<*>>()
|
||||
private val options = mutableListOf<Option<*>>()
|
||||
private lateinit var _execute: Context.() -> Unit
|
||||
protected var parent: Command? = null
|
||||
private val builders = mutableListOf<Builder<*>>()
|
||||
protected val commands = mutableListOf<Command>()
|
||||
protected val arguments = mutableListOf<Argument<*>>()
|
||||
protected val options = mutableListOf<Option<*>>()
|
||||
private var _execute: (Context.() -> Unit)? = null
|
||||
private var _renderer: HelpRenderer? = null
|
||||
|
||||
private val key: Key
|
||||
get() = Key(level)
|
||||
protected val execute: Context.() -> Unit
|
||||
get() = _execute!!
|
||||
protected val renderer: HelpRenderer
|
||||
get() = _renderer!!
|
||||
|
||||
fun command(name: String, block: Builder.() -> Unit) {
|
||||
fun command(name: String, block: Builder<*>.() -> Unit) {
|
||||
validateCommand(name)
|
||||
builders += Builder(level + 1, name, fallback = false, renderer).apply(block)
|
||||
builders += Named.Builder(name).apply(block)
|
||||
}
|
||||
|
||||
fun fallback(name: String, block: Builder.(Key) -> Unit) {
|
||||
validateCommand(name)
|
||||
builders += Builder(level + 1, name, fallback = true, renderer).apply { block(key) }
|
||||
inner class FallbackFactory {
|
||||
fun string(name: String, block: Builder<*>.(Fallback.Key<String>) -> Unit) =
|
||||
fallback(StringParser, name, block)
|
||||
|
||||
fun int(name: String, block: Builder<*>.(Fallback.Key<Int>) -> Unit) =
|
||||
fallback(IntParser, name, block)
|
||||
|
||||
fun long(name: String, block: Builder<*>.(Fallback.Key<Long>) -> Unit) =
|
||||
fallback(LongParser, name, block)
|
||||
|
||||
fun float(name: String, block: Builder<*>.(Fallback.Key<Float>) -> Unit) =
|
||||
fallback(FloatParser, name, block)
|
||||
|
||||
fun double(name: String, block: Builder<*>.(Fallback.Key<Double>) -> Unit) =
|
||||
fallback(DoubleParser, name, block)
|
||||
|
||||
fun boolean(name: String, block: Builder<*>.(Fallback.Key<Boolean>) -> Unit) =
|
||||
fallback(BooleanParser, name, block)
|
||||
|
||||
inline fun <reified T : Enum<T>> enum(name: String, noinline block: Builder<*>.(Fallback.Key<T>) -> Unit) =
|
||||
fallback(enumParser<T>(), name, block)
|
||||
}
|
||||
|
||||
fun argument(argument: Argument<*>) {
|
||||
val fallback = FallbackFactory()
|
||||
|
||||
fun <T : Any> fallback(parser: Parser<T>, name: String, block: Fallback.Builder<T>.(Fallback.Key<T>) -> Unit) {
|
||||
validateCommand(name)
|
||||
builders += Fallback.Builder(parser, name).apply { block(key) }
|
||||
}
|
||||
|
||||
fun register(argument: Argument<*>) {
|
||||
validateArgument(argument)
|
||||
arguments += argument
|
||||
}
|
||||
|
||||
fun arguments(vararg arguments: Argument<*>) = arguments.forEach(::argument)
|
||||
fun register(vararg arguments: Argument<*>) = arguments.forEach(::register)
|
||||
|
||||
operator fun <T : Argument<*>> T.provideDelegate(thisRef: Nothing?, property: KProperty<*>) = also(::argument)
|
||||
operator fun <T : Argument<*>> T.provideDelegate(thisRef: Nothing?, property: KProperty<*>) = also(::register)
|
||||
operator fun <T : Argument<*>> T.getValue(thisRef: Nothing?, property: KProperty<*>) = this
|
||||
|
||||
fun option(option: Option<*>) {
|
||||
fun register(option: Option<*>) {
|
||||
validateOption(option)
|
||||
options += option
|
||||
}
|
||||
|
||||
fun options(vararg options: Option<*>) = options.forEach(::option)
|
||||
fun register(vararg options: Option<*>) = options.forEach(::register)
|
||||
|
||||
operator fun <T : Option<*>> T.provideDelegate(thisRef: Nothing?, property: KProperty<*>) = also(::option)
|
||||
operator fun <T : Option<*>> T.provideDelegate(thisRef: Nothing?, property: KProperty<*>) = also(::register)
|
||||
operator fun <T : Option<*>> T.getValue(thisRef: Nothing?, property: KProperty<*>) = this
|
||||
|
||||
fun execute(block: Context.() -> Unit) {
|
||||
@@ -92,28 +164,35 @@ class Command private constructor(
|
||||
_execute = block
|
||||
}
|
||||
|
||||
fun build(): Command {
|
||||
if (!::_execute.isInitialized)
|
||||
_execute = {}
|
||||
fun renderer(renderer: HelpRenderer) {
|
||||
validateRenderer()
|
||||
_renderer = renderer
|
||||
}
|
||||
|
||||
internal fun build(): Command {
|
||||
if (_execute == null) _execute = {}
|
||||
if (_renderer == null) _renderer = DefaultHelpRenderer
|
||||
|
||||
validate()
|
||||
val command = create()
|
||||
|
||||
val commands = mutableListOf<Command>()
|
||||
val command = Command(parent, name, fallback, commands, arguments, options, _execute, renderer)
|
||||
for (builder in builders) {
|
||||
builder.parent = command
|
||||
commands += builder.build()
|
||||
}
|
||||
|
||||
return command
|
||||
}
|
||||
|
||||
internal abstract fun create(): COMMAND
|
||||
|
||||
private fun validateCommand(name: String) {
|
||||
if (builders.isNotEmpty()) {
|
||||
val last = builders.last()
|
||||
if (last.fallback) throw InvalidCommandOrder()
|
||||
if (last is Fallback.Builder<*>) throw InvalidCommandOrder()
|
||||
}
|
||||
when {
|
||||
!name.matches(COMMAND) -> throw InvalidCommand(name)
|
||||
!name.matches(Regex.COMMAND) -> throw InvalidCommand(name)
|
||||
builders.any { it.name == name } -> throw DuplicateCommand(name)
|
||||
}
|
||||
}
|
||||
@@ -139,18 +218,18 @@ class Command private constructor(
|
||||
}
|
||||
|
||||
private fun validateExecute() {
|
||||
if (::_execute.isInitialized) throw DuplicateExecute()
|
||||
if (_execute != null) throw DuplicateExecute()
|
||||
}
|
||||
|
||||
private fun validateRenderer() {
|
||||
if (_renderer != null) throw Exception() //TODO
|
||||
}
|
||||
|
||||
private fun validate() {
|
||||
if (builders.any { it.fallback } && arguments.isNotEmpty()) throw InvalidFallback()
|
||||
if (builders.any { it is Fallback.Builder<*> } && arguments.isNotEmpty()) throw InvalidFallback()
|
||||
}
|
||||
}
|
||||
|
||||
class Key internal constructor(
|
||||
internal val index: Int,
|
||||
)
|
||||
}
|
||||
|
||||
fun cli(name: String, block: Command.Builder.() -> Unit) =
|
||||
Command.Builder(-1, name, fallback = false, DefaultHelpRenderer).apply(block).build()
|
||||
fun cli(name: String, block: Command.Builder<*>.() -> Unit) =
|
||||
Command.Named.Builder(name).apply(block).build()
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
package com.infendro.cli.command
|
||||
package com.infendro.cli.command.argument
|
||||
|
||||
import com.infendro.cli.exception.build.InvalidRange
|
||||
import com.infendro.cli.parser.*
|
||||
import com.infendro.cli.parser.Parser
|
||||
|
||||
sealed class Argument<T : Any>(
|
||||
val parser: Parser<T>,
|
||||
@@ -52,18 +52,4 @@ sealed class Argument<T : Any>(
|
||||
min: Int,
|
||||
max: Int?,
|
||||
) : Argument<T>(parser, name, min, max)
|
||||
|
||||
companion object {
|
||||
fun string(name: String) = argument(StringParser, name)
|
||||
fun int(name: String) = argument(IntParser, name)
|
||||
fun long(name: String) = argument(LongParser, name)
|
||||
fun float(name: String) = argument(FloatParser, name)
|
||||
fun double(name: String) = argument(DoubleParser, name)
|
||||
fun boolean(name: String) = argument(BooleanParser, name)
|
||||
|
||||
inline fun <reified T : Enum<T>> enum(name: String) = argument(enumParser<T>(), name)
|
||||
}
|
||||
}
|
||||
|
||||
fun <T : Any> argument(parser: Parser<T>, name: String) =
|
||||
Argument.Required(parser, name)
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.infendro.cli.command.argument
|
||||
|
||||
import com.infendro.cli.parser.*
|
||||
|
||||
object ArgumentFactory {
|
||||
fun string(name: String) = argument(StringParser, name)
|
||||
fun int(name: String) = argument(IntParser, name)
|
||||
fun long(name: String) = argument(LongParser, name)
|
||||
fun float(name: String) = argument(FloatParser, name)
|
||||
fun double(name: String) = argument(DoubleParser, name)
|
||||
fun boolean(name: String) = argument(BooleanParser, name)
|
||||
|
||||
inline fun <reified T : Enum<T>> enum(name: String) = argument(enumParser<T>(), name)
|
||||
}
|
||||
|
||||
val argument = ArgumentFactory
|
||||
|
||||
fun <T : Any> argument(parser: Parser<T>, name: String) =
|
||||
Argument.Required(parser, name)
|
||||
@@ -1,65 +1,60 @@
|
||||
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 com.infendro.cli.command.argument.Argument
|
||||
import com.infendro.cli.command.option.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>,
|
||||
private val commands: Map<Command.Fallback.Key<*>, Any>,
|
||||
private val arguments: Map<Argument<*>, List<Any>>,
|
||||
private val options: Map<Option<*>, List<Any>>,
|
||||
) {
|
||||
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) }
|
||||
command.help?.let { print(it) }
|
||||
}
|
||||
|
||||
operator fun Command.Key.getValue(thisRef: Any?, property: KProperty<*>): String = commands[index].name
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
private val <T : Any> Command.Fallback.Key<T>.value: T
|
||||
get() = commands[this] as T
|
||||
|
||||
private val <T : Any> Argument<T>.index: Int
|
||||
get() = command.arguments.takeWhile { it != this }.sumOf { it.count }
|
||||
operator fun <T : Any> Command.Fallback.Key<T>.getValue(thisRef: Any?, property: KProperty<*>): T =
|
||||
value
|
||||
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
private val <T : Any> Argument<T>.value: T?
|
||||
get() = arguments.getOrNull(index)?.value as? T
|
||||
private val <T : Any> Argument<T>.values: List<T>
|
||||
get() = arguments[this] as List<T>
|
||||
|
||||
operator fun <T : Any> Argument.Required<T>.getValue(thisRef: Any?, property: KProperty<*>): T =
|
||||
values.first()
|
||||
|
||||
operator fun <T : Any> Argument.OrElse<T>.getValue(thisRef: Any?, property: KProperty<*>): T =
|
||||
values.firstOrNull() ?: other
|
||||
|
||||
operator fun <T : Any> Argument.OrNull<T>.getValue(thisRef: Any?, property: KProperty<*>): T? =
|
||||
values.firstOrNull()
|
||||
|
||||
operator fun <T : Any> Argument.Variable<T>.getValue(thisRef: Any?, property: KProperty<*>): List<T> =
|
||||
values
|
||||
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
private val <T : Any> Argument.Variable<T>.values: List<T>
|
||||
get() = arguments.drop(index).take(count).map { it.value as T }
|
||||
private val <T : Any> Option<T>.values: List<T>
|
||||
get() = options[this] as List<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
|
||||
operator fun <T : Any> Option.Required<T>.getValue(thisRef: Any?, property: KProperty<*>): T =
|
||||
values.first()
|
||||
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
private val <T : Any> Option<T>.value: T?
|
||||
get() = options.firstOrNull { it.name in names }?.value as? T
|
||||
operator fun <T : Any> Option.OrElse<T>.getValue(thisRef: Any?, property: KProperty<*>): T =
|
||||
values.firstOrNull() ?: other
|
||||
|
||||
@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.OrNull<T>.getValue(thisRef: Any?, property: KProperty<*>): T? =
|
||||
values.firstOrNull()
|
||||
|
||||
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
|
||||
operator fun <T : Any> Option.Variable<T>.getValue(thisRef: Any?, property: KProperty<*>): List<T> =
|
||||
values
|
||||
}
|
||||
|
||||
@@ -1,24 +1,13 @@
|
||||
package com.infendro.cli.command.context
|
||||
|
||||
import com.infendro.cli.command.Command
|
||||
import com.infendro.cli.command.context.Context.*
|
||||
import com.infendro.cli.exception.run.*
|
||||
import com.infendro.cli.parser.Parser
|
||||
|
||||
internal class Parser(
|
||||
internal class ContextParser(
|
||||
private val root: Command,
|
||||
private val args: Array<String>,
|
||||
) {
|
||||
private var index = 0
|
||||
private val current: String
|
||||
get() = args[index]
|
||||
private val next: String?
|
||||
get() = args.getOrNull(index)
|
||||
|
||||
private fun hasNext() = index < args.size
|
||||
private fun consume() {
|
||||
index++
|
||||
}
|
||||
|
||||
sealed class Result {
|
||||
data class Success(
|
||||
val context: Context,
|
||||
@@ -30,40 +19,60 @@ internal class Parser(
|
||||
|
||||
data class Failure(
|
||||
val command: Command,
|
||||
val exception: RunException,
|
||||
val error: RuntimeError,
|
||||
) : Result()
|
||||
}
|
||||
|
||||
fun success(context: Context) = Result.Success(context)
|
||||
fun help(command: Command) = Result.Help(command)
|
||||
fun failure(command: Command, exception: RunException) = Result.Failure(command, exception)
|
||||
private fun success(context: Context) = Result.Success(context)
|
||||
private fun help(command: Command) = Result.Help(command)
|
||||
private fun failure(command: Command, exception: RuntimeError) = Result.Failure(command, exception)
|
||||
|
||||
private var index = 0
|
||||
private val current: String
|
||||
get() = args[index]
|
||||
private val next: String?
|
||||
get() = args.getOrNull(index)
|
||||
|
||||
private fun hasNext() = index < args.size
|
||||
private fun consume() {
|
||||
index++
|
||||
}
|
||||
|
||||
fun parse(): Result {
|
||||
var command = root
|
||||
val cmd = mutableListOf<Cmd>()
|
||||
val arg = mutableListOf<Arg>()
|
||||
val opt = mutableListOf<Opt>()
|
||||
|
||||
// command
|
||||
var command = root
|
||||
val commands = mutableMapOf<Command.Fallback.Key<*>, Any>()
|
||||
|
||||
while (hasNext()) {
|
||||
if (current.startsWith("-"))
|
||||
break
|
||||
|
||||
val c = command.commands.firstOrNull { it.name == current || it.fallback }
|
||||
if (c == null) {
|
||||
val cmd = command.commands.firstOrNull {
|
||||
(it is Command.Named && it.name == current) || it is Command.Fallback<*>
|
||||
}
|
||||
if (cmd == null) {
|
||||
when {
|
||||
command.arguments.isEmpty() -> return failure(command, UnknownCommand(current))
|
||||
else -> break
|
||||
}
|
||||
}
|
||||
|
||||
command = c
|
||||
cmd += Cmd(current)
|
||||
command = cmd
|
||||
if (cmd is Command.Fallback<*>) {
|
||||
val value = when (val result = cmd.parser.parse(current)) {
|
||||
is Parser.Result.Success<*> -> result.value
|
||||
is Parser.Result.Failure<*> -> return failure(command, result.error)
|
||||
}
|
||||
commands[cmd.key] = value
|
||||
}
|
||||
|
||||
consume()
|
||||
}
|
||||
|
||||
// arguments and options
|
||||
val arguments = command.arguments.associateWith { mutableListOf<Any>() }
|
||||
val options = command.options.associateWith { mutableListOf<Any>() }
|
||||
|
||||
var endOfOptions = false
|
||||
var argumentIndex = 0
|
||||
var argumentCount = 0
|
||||
@@ -78,8 +87,11 @@ internal class Parser(
|
||||
val argument = command.arguments.getOrNull(argumentIndex)
|
||||
?: return failure(command, UnexpectedArgument())
|
||||
|
||||
val value = argument.parser.parse(trimmed)
|
||||
arg += Arg(value)
|
||||
val value = when (val result = argument.parser.parse(trimmed)) {
|
||||
is Parser.Result.Success<*> -> result.value
|
||||
is Parser.Result.Failure<*> -> return failure(command, result.error)
|
||||
}
|
||||
arguments[argument]!! += value
|
||||
argumentCount++
|
||||
|
||||
if (argumentCount == argument.count) {
|
||||
@@ -124,11 +136,15 @@ internal class Parser(
|
||||
?: return failure(command, UnknownOption(name))
|
||||
|
||||
val value = when {
|
||||
text != null -> option.parser.parse(text)
|
||||
text != null ->
|
||||
when (val result = option.parser.parse(current)) {
|
||||
is Parser.Result.Success<*> -> result.value
|
||||
is Parser.Result.Failure<*> -> return failure(command, result.error)
|
||||
}
|
||||
option.flag -> option.fallback!!
|
||||
else -> return failure(command, MissingOptionValue(option))
|
||||
}
|
||||
opt += Opt(name, value)
|
||||
options[option]!! += value
|
||||
}
|
||||
}
|
||||
|
||||
@@ -148,23 +164,18 @@ internal class Parser(
|
||||
}
|
||||
|
||||
// validate arguments
|
||||
val required = command.arguments.filter { it.required }
|
||||
var consumed = 0
|
||||
for (argument in required) {
|
||||
val needed = if (argument === required.last()) argument.min else argument.count
|
||||
val delta = arg.size - consumed
|
||||
if (delta < needed) return failure(command, InvalidArgumentCount(argument, delta))
|
||||
|
||||
consumed += needed
|
||||
for (argument in command.arguments) {
|
||||
val count = arguments[argument]!!.count()
|
||||
if (count !in argument.min..argument.count) return failure(command, InvalidArgumentCount(argument, count))
|
||||
}
|
||||
|
||||
// validate options
|
||||
for (option in command.options) {
|
||||
val count = opt.count { it.name in option.names }
|
||||
val count = options[option]!!.count()
|
||||
if (count !in option.min..option.count) return failure(command, InvalidOptionCount(option, count))
|
||||
}
|
||||
|
||||
val context = Context(command, cmd, arg, opt)
|
||||
val context = Context(command, commands, arguments, options)
|
||||
return success(context)
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
package com.infendro.cli.command.help
|
||||
|
||||
import com.infendro.cli.command.Argument
|
||||
import com.infendro.cli.command.Command
|
||||
import com.infendro.cli.command.Option
|
||||
import com.infendro.cli.command.argument.Argument
|
||||
import com.infendro.cli.command.option.Option
|
||||
|
||||
object DefaultHelpRenderer : HelpRenderer {
|
||||
override fun render(command: Command) = buildString {
|
||||
@@ -26,7 +26,7 @@ object DefaultHelpRenderer : HelpRenderer {
|
||||
for (command in command.path) {
|
||||
append(" ")
|
||||
when {
|
||||
command.fallback -> append("<${command.name}>")
|
||||
command is Command.Fallback<*> -> append("<${command.name}>")
|
||||
else -> append(command.name)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
package com.infendro.cli.command
|
||||
package com.infendro.cli.command.option
|
||||
|
||||
import com.infendro.cli.exception.build.InvalidRange
|
||||
import com.infendro.cli.exception.build.MissingOptionName
|
||||
import com.infendro.cli.parser.*
|
||||
import com.infendro.cli.parser.Parser
|
||||
|
||||
sealed class Option<T : Any>(
|
||||
val parser: Parser<T>,
|
||||
@@ -90,21 +90,4 @@ sealed class Option<T : Any>(
|
||||
max: Int?,
|
||||
) : this(parser, null, names, min, max)
|
||||
}
|
||||
|
||||
companion object {
|
||||
fun string(vararg names: String) = option(StringParser, *names)
|
||||
fun int(vararg names: String) = option(IntParser, *names)
|
||||
fun long(vararg names: String) = option(LongParser, *names)
|
||||
fun float(vararg names: String) = option(FloatParser, *names)
|
||||
fun double(vararg names: String) = option(DoubleParser, *names)
|
||||
fun boolean(vararg names: String) = option(BooleanParser, true, *names)
|
||||
|
||||
inline fun <reified T : Enum<T>> enum(vararg names: String) = option(enumParser<T>(), *names)
|
||||
}
|
||||
}
|
||||
|
||||
fun <T : Any> option(parser: Parser<T>, vararg names: String) =
|
||||
Option.Required(parser, names.asList())
|
||||
|
||||
fun <T : Any> option(parser: Parser<T>, fallback: T, vararg names: String) =
|
||||
Option.Required(parser, fallback, names.asList())
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.infendro.cli.command.option
|
||||
|
||||
import com.infendro.cli.parser.*
|
||||
|
||||
object OptionFactory {
|
||||
fun string(vararg names: String) = option(StringParser, *names)
|
||||
fun int(vararg names: String) = option(IntParser, *names)
|
||||
fun long(vararg names: String) = option(LongParser, *names)
|
||||
fun float(vararg names: String) = option(FloatParser, *names)
|
||||
fun double(vararg names: String) = option(DoubleParser, *names)
|
||||
fun boolean(vararg names: String) = option(BooleanParser, true, *names)
|
||||
|
||||
inline fun <reified T : Enum<T>> enum(vararg names: String) = option(enumParser<T>(), *names)
|
||||
}
|
||||
|
||||
val option = OptionFactory
|
||||
|
||||
fun <T : Any> option(parser: Parser<T>, vararg names: String) =
|
||||
Option.Required(parser, names.asList())
|
||||
|
||||
fun <T : Any> option(parser: Parser<T>, fallback: T, vararg names: String) =
|
||||
Option.Required(parser, fallback, names.asList())
|
||||
@@ -1,5 +0,0 @@
|
||||
package com.infendro.cli.exception.build
|
||||
|
||||
import com.infendro.cli.exception.CliException
|
||||
|
||||
abstract class BuildException : CliException()
|
||||
@@ -1,3 +1,3 @@
|
||||
package com.infendro.cli.exception
|
||||
package com.infendro.cli.exception.build
|
||||
|
||||
abstract class CliException : Exception()
|
||||
@@ -2,4 +2,4 @@ package com.infendro.cli.exception.build
|
||||
|
||||
class DuplicateCommand(
|
||||
val command: String,
|
||||
) : BuildException()
|
||||
) : CliException()
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
package com.infendro.cli.exception.build
|
||||
|
||||
class DuplicateExecute : BuildException()
|
||||
class DuplicateExecute : CliException()
|
||||
|
||||
@@ -2,4 +2,4 @@ package com.infendro.cli.exception.build
|
||||
|
||||
class DuplicateOption(
|
||||
val name: String,
|
||||
) : BuildException()
|
||||
) : CliException()
|
||||
|
||||
@@ -2,4 +2,4 @@ package com.infendro.cli.exception.build
|
||||
|
||||
class InvalidArgument(
|
||||
val name: String,
|
||||
) : BuildException()
|
||||
) : CliException()
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
package com.infendro.cli.exception.build
|
||||
|
||||
class InvalidArgumentOrder : BuildException()
|
||||
class InvalidArgumentOrder : CliException()
|
||||
|
||||
@@ -2,4 +2,4 @@ package com.infendro.cli.exception.build
|
||||
|
||||
class InvalidCommand(
|
||||
val name: String,
|
||||
) : BuildException()
|
||||
) : CliException()
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
package com.infendro.cli.exception.build
|
||||
|
||||
class InvalidCommandOrder : BuildException()
|
||||
class InvalidCommandOrder : CliException()
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
package com.infendro.cli.exception.build
|
||||
|
||||
class InvalidFallback : BuildException()
|
||||
class InvalidFallback : CliException()
|
||||
|
||||
@@ -2,4 +2,4 @@ package com.infendro.cli.exception.build
|
||||
|
||||
class InvalidOption(
|
||||
val name: String,
|
||||
) : BuildException()
|
||||
) : CliException()
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
package com.infendro.cli.exception.build
|
||||
|
||||
class InvalidRange : BuildException()
|
||||
class InvalidRange : CliException()
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
package com.infendro.cli.exception.build
|
||||
|
||||
class MissingOptionName : BuildException()
|
||||
class MissingOptionName : CliException()
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
package com.infendro.cli.exception.run
|
||||
|
||||
import com.infendro.cli.command.Argument
|
||||
import com.infendro.cli.command.argument.Argument
|
||||
|
||||
class InvalidArgumentCount(
|
||||
val argument: Argument<*>,
|
||||
val count: Int,
|
||||
) : RunException() {
|
||||
) : RuntimeError() {
|
||||
override val message: String
|
||||
get() {
|
||||
val expected = when {
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
package com.infendro.cli.exception.run
|
||||
|
||||
import com.infendro.cli.command.Option
|
||||
import com.infendro.cli.command.option.Option
|
||||
|
||||
class InvalidOptionCount(
|
||||
val option: Option<*>,
|
||||
val count: Int,
|
||||
) : RunException() {
|
||||
) : RuntimeError() {
|
||||
override val message: String
|
||||
get() {
|
||||
val expected = when {
|
||||
|
||||
@@ -5,7 +5,7 @@ import kotlin.reflect.KClass
|
||||
class InvalidValue(
|
||||
val value: String,
|
||||
val type: KClass<*>,
|
||||
) : RunException() {
|
||||
) : RuntimeError() {
|
||||
override val message: String
|
||||
get() = """"$value" cannot be converted to ${type.simpleName ?: "Unknown"}"""
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@ package com.infendro.cli.exception.run
|
||||
|
||||
class MalformedOption(
|
||||
val option: String,
|
||||
) : RunException() {
|
||||
) : RuntimeError() {
|
||||
override val message: String
|
||||
get() = """malformed option "$option""""
|
||||
}
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
package com.infendro.cli.exception.run
|
||||
|
||||
import com.infendro.cli.command.Option
|
||||
import com.infendro.cli.command.option.Option
|
||||
|
||||
class MissingOptionValue(
|
||||
val option: Option<*>,
|
||||
) : RunException() {
|
||||
) : RuntimeError() {
|
||||
override val message: String
|
||||
get() = """no value provided for option "${option.name}""""
|
||||
}
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
package com.infendro.cli.exception.run
|
||||
|
||||
import com.infendro.cli.exception.CliException
|
||||
|
||||
abstract class RunException : CliException()
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.infendro.cli.exception.run
|
||||
|
||||
abstract class RuntimeError {
|
||||
abstract val message: String
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
package com.infendro.cli.exception.run
|
||||
|
||||
class UnexpectedArgument : RunException() {
|
||||
class UnexpectedArgument : RuntimeError() {
|
||||
override val message: String
|
||||
get() = """unexpected argument"""
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@ package com.infendro.cli.exception.run
|
||||
|
||||
class UnknownCommand(
|
||||
val command: String,
|
||||
) : RunException() {
|
||||
) : RuntimeError() {
|
||||
override val message: String
|
||||
get() = """unknown command "$command""""
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@ package com.infendro.cli.exception.run
|
||||
|
||||
class UnknownOption(
|
||||
val option: String,
|
||||
) : RunException() {
|
||||
) : RuntimeError() {
|
||||
override val message: String
|
||||
get() = """unknown option "$option""""
|
||||
}
|
||||
|
||||
@@ -1,14 +1,10 @@
|
||||
package com.infendro.cli.parser
|
||||
|
||||
import kotlin.reflect.KClass
|
||||
|
||||
object BooleanParser : Parser<Boolean> {
|
||||
override val type: KClass<Boolean>
|
||||
get() = Boolean::class
|
||||
|
||||
override fun parse(text: String): Boolean = when (text) {
|
||||
"true", "t" -> true
|
||||
"false", "f" -> false
|
||||
else -> invalid(text)
|
||||
}
|
||||
object BooleanParser : Parser<Boolean>(Boolean::class) {
|
||||
override fun parse(text: String) =
|
||||
when (text) {
|
||||
"true", "t" -> success(true)
|
||||
"false", "f" -> success(false)
|
||||
else -> failure(text)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,11 +1,8 @@
|
||||
package com.infendro.cli.parser
|
||||
|
||||
import kotlin.reflect.KClass
|
||||
|
||||
object DoubleParser : Parser<Double> {
|
||||
override val type: KClass<Double>
|
||||
get() = Double::class
|
||||
|
||||
override fun parse(text: String): Double = text.toDoubleOrNull()
|
||||
?: invalid(text)
|
||||
object DoubleParser : Parser<Double>(Double::class) {
|
||||
override fun parse(text: String) =
|
||||
text.toDoubleOrNull()
|
||||
?.let { success(it) }
|
||||
?: failure(text)
|
||||
}
|
||||
|
||||
@@ -4,11 +4,13 @@ import kotlin.enums.enumEntries
|
||||
import kotlin.reflect.KClass
|
||||
|
||||
class EnumParser<T : Enum<T>>(
|
||||
override val type: KClass<T>,
|
||||
type: KClass<T>,
|
||||
private val values: List<T>,
|
||||
) : Parser<T> {
|
||||
override fun parse(text: String): T = values.firstOrNull { it.name == text }
|
||||
?: invalid(text)
|
||||
) : Parser<T>(type) {
|
||||
override fun parse(text: String) =
|
||||
values.firstOrNull { it.name == text }
|
||||
?.let { success(it) }
|
||||
?: failure(text)
|
||||
}
|
||||
|
||||
inline fun <reified T : Enum<T>> enumParser() = EnumParser(T::class, enumEntries<T>())
|
||||
|
||||
@@ -1,11 +1,8 @@
|
||||
package com.infendro.cli.parser
|
||||
|
||||
import kotlin.reflect.KClass
|
||||
|
||||
object FloatParser : Parser<Float> {
|
||||
override val type: KClass<Float>
|
||||
get() = Float::class
|
||||
|
||||
override fun parse(text: String): Float = text.toFloatOrNull()
|
||||
?: invalid(text)
|
||||
object FloatParser : Parser<Float>(Float::class) {
|
||||
override fun parse(text: String) =
|
||||
text.toFloatOrNull()
|
||||
?.let { success(it) }
|
||||
?: failure(text)
|
||||
}
|
||||
|
||||
@@ -1,11 +1,8 @@
|
||||
package com.infendro.cli.parser
|
||||
|
||||
import kotlin.reflect.KClass
|
||||
|
||||
object IntParser : Parser<Int> {
|
||||
override val type: KClass<Int>
|
||||
get() = Int::class
|
||||
|
||||
override fun parse(text: String): Int = text.toIntOrNull()
|
||||
?: invalid(text)
|
||||
object IntParser : Parser<Int>(Int::class) {
|
||||
override fun parse(text: String) =
|
||||
text.toIntOrNull()
|
||||
?.let { success(it) }
|
||||
?: failure(text)
|
||||
}
|
||||
|
||||
@@ -1,11 +1,8 @@
|
||||
package com.infendro.cli.parser
|
||||
|
||||
import kotlin.reflect.KClass
|
||||
|
||||
object LongParser : Parser<Long> {
|
||||
override val type: KClass<Long>
|
||||
get() = Long::class
|
||||
|
||||
override fun parse(text: String): Long = text.toLongOrNull()
|
||||
?: invalid(text)
|
||||
object LongParser : Parser<Long>(Long::class) {
|
||||
override fun parse(text: String) =
|
||||
text.toLongOrNull()
|
||||
?.let { success(it) }
|
||||
?: failure(text)
|
||||
}
|
||||
|
||||
@@ -1,12 +1,24 @@
|
||||
package com.infendro.cli.parser
|
||||
|
||||
import com.infendro.cli.exception.run.InvalidValue
|
||||
import com.infendro.cli.exception.run.RuntimeError
|
||||
import kotlin.reflect.KClass
|
||||
|
||||
interface Parser<T : Any> {
|
||||
val type: KClass<T>
|
||||
abstract class Parser<T : Any>(
|
||||
val type: KClass<T>,
|
||||
) {
|
||||
sealed class Result<T : Any> {
|
||||
data class Success<T : Any>(
|
||||
val value: T,
|
||||
) : Result<T>()
|
||||
|
||||
fun parse(text: String): T
|
||||
data class Failure<T : Any>(
|
||||
val error: RuntimeError,
|
||||
) : Result<T>()
|
||||
}
|
||||
|
||||
fun invalid(text: String): Nothing = throw InvalidValue(text, type)
|
||||
protected fun success(value: T) = Result.Success(value)
|
||||
protected fun failure(text: String) = Result.Failure<T>(InvalidValue(text, type))
|
||||
|
||||
abstract fun parse(text: String): Result<T>
|
||||
}
|
||||
|
||||
@@ -1,10 +1,6 @@
|
||||
package com.infendro.cli.parser
|
||||
|
||||
import kotlin.reflect.KClass
|
||||
|
||||
object StringParser : Parser<String> {
|
||||
override val type: KClass<String>
|
||||
get() = String::class
|
||||
|
||||
override fun parse(text: String) = text
|
||||
object StringParser : Parser<String>(String::class) {
|
||||
override fun parse(text: String) =
|
||||
success(text)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user