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