Compare commits
2 Commits
4e9b358ef8
...
921229aa5b
| Author | SHA1 | Date | |
|---|---|---|---|
|
921229aa5b
|
|||
|
ecd255479a
|
10
README.md
10
README.md
@@ -31,17 +31,17 @@ dependencies {
|
||||
fun main(args: Array<String>) = cli("application") {
|
||||
execute {
|
||||
// define execution of command (e.g., display help)
|
||||
println("Usage: application <command> [arguments] [options]")
|
||||
help()
|
||||
}
|
||||
|
||||
// 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,71 +1,162 @@
|
||||
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.exception.run.RunException
|
||||
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<*>>,
|
||||
internal val execute: Context.() -> Unit,
|
||||
internal val renderer: HelpRenderer,
|
||||
) {
|
||||
fun run(args: Array<String>) = try {
|
||||
Parser.parse(this, args).execute()
|
||||
} catch (e: RunException) {
|
||||
println(e.message)
|
||||
val path: List<Command>
|
||||
get() = when {
|
||||
parent == null -> listOf(this)
|
||||
else -> parent.path + this
|
||||
}
|
||||
|
||||
val help: String?
|
||||
get() = renderer.render(this)
|
||||
|
||||
fun run(args: Array<String>) {
|
||||
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,
|
||||
sealed class Builder<COMMAND : Command>(
|
||||
protected val name: String,
|
||||
) {
|
||||
private val commands = mutableListOf<Command>()
|
||||
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)
|
||||
commands += Builder(level + 1, name, fallback = false).apply(block).build()
|
||||
builders += Named.Builder(name).apply(block)
|
||||
}
|
||||
|
||||
fun fallback(name: String, block: Builder.(Key) -> Unit) {
|
||||
validateCommand(name)
|
||||
commands += Builder(level + 1, name, fallback = true).apply { block(key) }.build()
|
||||
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) {
|
||||
@@ -73,24 +164,36 @@ 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()
|
||||
return Command(name, fallback, commands, arguments, options, _execute)
|
||||
val command = create()
|
||||
|
||||
for (builder in builders) {
|
||||
builder.parent = command
|
||||
commands += builder.build()
|
||||
}
|
||||
|
||||
return command
|
||||
}
|
||||
|
||||
internal abstract fun create(): COMMAND
|
||||
|
||||
private fun validateCommand(name: String) {
|
||||
if (commands.isNotEmpty()) {
|
||||
val last = commands.last()
|
||||
when {
|
||||
last.fallback -> throw InvalidCommandOrder()
|
||||
}
|
||||
if (builders.isNotEmpty()) {
|
||||
val last = builders.last()
|
||||
if (last is Fallback.Builder<*>) throw InvalidCommandOrder()
|
||||
}
|
||||
when {
|
||||
!name.matches(COMMAND) -> throw InvalidCommand(name)
|
||||
commands.any { it.name == name } -> throw DuplicateCommand(name)
|
||||
!name.matches(Regex.COMMAND) -> throw InvalidCommand(name)
|
||||
builders.any { it.name == name } -> throw DuplicateCommand(name)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -102,9 +205,7 @@ class Command private constructor(
|
||||
argument.required && last.optional -> throw InvalidArgumentOrder()
|
||||
}
|
||||
}
|
||||
when {
|
||||
!argument.name.matches(ARGUMENT) -> throw InvalidArgument(argument.name)
|
||||
}
|
||||
if (!argument.name.matches(ARGUMENT)) throw InvalidArgument(argument.name)
|
||||
}
|
||||
|
||||
private fun validateOption(option: Option<*>) {
|
||||
@@ -117,21 +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 (commands.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).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>,
|
||||
@@ -10,9 +10,7 @@ sealed class Argument<T : Any>(
|
||||
val max: Int?,
|
||||
) {
|
||||
init {
|
||||
when {
|
||||
min !in 0..count -> throw InvalidRange()
|
||||
}
|
||||
if (min !in 0..count || max == 0) throw InvalidRange()
|
||||
}
|
||||
|
||||
val required: Boolean
|
||||
@@ -54,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,61 +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 options: List<Opt>,
|
||||
val arguments: List<Arg>,
|
||||
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)()
|
||||
|
||||
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
|
||||
fun help() {
|
||||
command.help?.let { print(it) }
|
||||
}
|
||||
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
private val <T : Any> Command.Fallback.Key<T>.value: T
|
||||
get() = commands[this] as T
|
||||
|
||||
operator fun <T : Any> Command.Fallback.Key<T>.getValue(thisRef: Any?, property: KProperty<*>): T =
|
||||
value
|
||||
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
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> Option<T>.values: List<T>
|
||||
get() = options[this] as List<T>
|
||||
|
||||
operator fun <T : Any> Option.Required<T>.getValue(thisRef: Any?, property: KProperty<*>): T =
|
||||
values.first()
|
||||
|
||||
operator fun <T : Any> Option.OrElse<T>.getValue(thisRef: Any?, property: KProperty<*>): T =
|
||||
values.firstOrNull() ?: other
|
||||
|
||||
operator fun <T : Any> Option.OrNull<T>.getValue(thisRef: Any?, property: KProperty<*>): T? =
|
||||
values.firstOrNull()
|
||||
|
||||
operator fun <T : Any> Option.Variable<T>.getValue(thisRef: Any?, property: KProperty<*>): List<T> =
|
||||
values
|
||||
}
|
||||
|
||||
@@ -0,0 +1,181 @@
|
||||
package com.infendro.cli.command.context
|
||||
|
||||
import com.infendro.cli.command.Command
|
||||
import com.infendro.cli.exception.run.*
|
||||
import com.infendro.cli.parser.Parser
|
||||
|
||||
internal class ContextParser(
|
||||
private val root: Command,
|
||||
private val args: Array<String>,
|
||||
) {
|
||||
sealed class Result {
|
||||
data class Success(
|
||||
val context: Context,
|
||||
) : Result()
|
||||
|
||||
data class Help(
|
||||
val command: Command,
|
||||
) : Result()
|
||||
|
||||
data class Failure(
|
||||
val command: Command,
|
||||
val error: RuntimeError,
|
||||
) : Result()
|
||||
}
|
||||
|
||||
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 {
|
||||
// command
|
||||
var command = root
|
||||
val commands = mutableMapOf<Command.Fallback.Key<*>, Any>()
|
||||
|
||||
while (hasNext()) {
|
||||
if (current.startsWith("-"))
|
||||
break
|
||||
|
||||
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 = 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
|
||||
|
||||
while (hasNext()) {
|
||||
val dashes = current.takeWhile { it == '-' }.count()
|
||||
val trimmed = current.drop(dashes)
|
||||
|
||||
when {
|
||||
// argument
|
||||
endOfOptions || dashes == 0 -> {
|
||||
val argument = command.arguments.getOrNull(argumentIndex)
|
||||
?: return failure(command, UnexpectedArgument())
|
||||
|
||||
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) {
|
||||
argumentCount = 0
|
||||
argumentIndex++
|
||||
}
|
||||
}
|
||||
|
||||
// option
|
||||
dashes in 1..2 -> {
|
||||
if (dashes == 2 && trimmed.isEmpty()) {
|
||||
endOfOptions = true
|
||||
consume()
|
||||
continue
|
||||
}
|
||||
|
||||
if (dashes == 2 && trimmed == "help")
|
||||
return help(command)
|
||||
|
||||
val (name, text) = when {
|
||||
trimmed.contains('=') -> {
|
||||
val (name, value) = trimmed.split('=', limit = 2)
|
||||
name to value
|
||||
}
|
||||
else -> {
|
||||
if (next?.startsWith('-') == false) {
|
||||
consume()
|
||||
trimmed to next
|
||||
} else {
|
||||
trimmed to null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val names = when {
|
||||
dashes == 1 -> name.map { "$it" }
|
||||
else -> listOf(name)
|
||||
}
|
||||
|
||||
for (name in names) {
|
||||
val option = command.options.firstOrNull { name in it.names }
|
||||
?: return failure(command, UnknownOption(name))
|
||||
|
||||
val value = when {
|
||||
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))
|
||||
}
|
||||
options[option]!! += value
|
||||
}
|
||||
}
|
||||
|
||||
// malformed option
|
||||
else -> {
|
||||
when {
|
||||
current.contains('=') -> {
|
||||
val (option) = current.split('=', limit = 2)
|
||||
return failure(command, MalformedOption(option))
|
||||
}
|
||||
else -> return failure(command, MalformedOption(current))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
consume()
|
||||
}
|
||||
|
||||
// validate arguments
|
||||
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 = options[option]!!.count()
|
||||
if (count !in option.min..option.count) return failure(command, InvalidOptionCount(option, count))
|
||||
}
|
||||
|
||||
val context = Context(command, commands, arguments, options)
|
||||
return success(context)
|
||||
}
|
||||
}
|
||||
@@ -1,143 +0,0 @@
|
||||
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.*
|
||||
|
||||
internal object Parser {
|
||||
fun parse(root: Command, args: Array<String>): Context {
|
||||
var command = root
|
||||
val cmd = mutableListOf<Cmd>()
|
||||
val arg = mutableListOf<Arg>()
|
||||
val opt = mutableListOf<Opt>()
|
||||
|
||||
var i = 0
|
||||
|
||||
// commands
|
||||
while (i < args.size) {
|
||||
val current = args[i]
|
||||
|
||||
if (current.startsWith("-"))
|
||||
break
|
||||
|
||||
val c = command.commands.firstOrNull { it.name == current || it.fallback }
|
||||
if (c == null) {
|
||||
when {
|
||||
command.arguments.isEmpty() -> throw UnknownCommand(current)
|
||||
else -> break
|
||||
}
|
||||
}
|
||||
|
||||
command = c
|
||||
cmd += Cmd(current)
|
||||
|
||||
i++
|
||||
}
|
||||
|
||||
// arguments and options
|
||||
var endOfOptions = false
|
||||
var argumentIndex = 0
|
||||
var argumentCount = 0
|
||||
while (i < args.size) {
|
||||
val dashes = args[i].takeWhile { it == '-' }.count()
|
||||
val current = args[i].drop(dashes)
|
||||
|
||||
when {
|
||||
// argument
|
||||
endOfOptions || dashes == 0 -> {
|
||||
val argument = command.arguments.getOrNull(argumentIndex)
|
||||
?: throw UnexpectedArgument()
|
||||
|
||||
val value = argument.parser.parse(current)
|
||||
arg += Arg(value)
|
||||
argumentCount++
|
||||
|
||||
if (argumentCount == argument.count) {
|
||||
argumentCount = 0
|
||||
argumentIndex++
|
||||
}
|
||||
}
|
||||
|
||||
// option
|
||||
dashes in 1..2 -> {
|
||||
if (dashes == 2 && current.isEmpty()) {
|
||||
endOfOptions = true
|
||||
i++
|
||||
continue
|
||||
}
|
||||
|
||||
val (name, text) = when {
|
||||
current.contains('=') -> {
|
||||
val (name, value) = current.split('=', limit = 2)
|
||||
name to value
|
||||
}
|
||||
|
||||
else -> {
|
||||
val next = args.getOrNull(i + 1)
|
||||
if (next != null && !next.startsWith('-')) {
|
||||
i++
|
||||
current to next
|
||||
} else {
|
||||
current to null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val names = when {
|
||||
dashes == 1 -> name.map { "$it" }
|
||||
else -> listOf(name)
|
||||
}
|
||||
|
||||
for (name in names) {
|
||||
val option = command.options.firstOrNull { name in it.names }
|
||||
?: throw UnknownOption(name)
|
||||
|
||||
val value = when {
|
||||
text != null -> option.parser.parse(text)
|
||||
option.flag -> option.fallback!!
|
||||
else -> throw MissingOptionValue(option)
|
||||
}
|
||||
opt += Opt(name, value)
|
||||
}
|
||||
}
|
||||
|
||||
// malformed option
|
||||
else -> {
|
||||
when {
|
||||
args[i].contains('=') -> {
|
||||
val (option) = args[i].split('=', limit = 2)
|
||||
throw MalformedOption(option)
|
||||
}
|
||||
else -> throw MalformedOption(args[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
i++
|
||||
}
|
||||
|
||||
validateArguments(command, arg)
|
||||
validateOptions(command, opt)
|
||||
|
||||
return Context(command, cmd, opt, arg)
|
||||
}
|
||||
|
||||
private fun validateArguments(command: Command, arg: List<Arg>) {
|
||||
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) throw InvalidArgumentCount(argument, delta)
|
||||
|
||||
consumed += needed
|
||||
}
|
||||
}
|
||||
|
||||
private fun validateOptions(command: Command, opt: List<Opt>) {
|
||||
for (option in command.options) {
|
||||
val count = opt.count { it.name in option.names }
|
||||
if (count !in option.min..option.count) throw InvalidOptionCount(option, count)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package com.infendro.cli.command.help
|
||||
|
||||
import com.infendro.cli.command.Command
|
||||
import com.infendro.cli.command.argument.Argument
|
||||
import com.infendro.cli.command.option.Option
|
||||
|
||||
object DefaultHelpRenderer : HelpRenderer {
|
||||
override fun render(command: Command) = buildString {
|
||||
usage(command)
|
||||
if (command.commands.isNotEmpty()) {
|
||||
appendLine()
|
||||
commands(command.commands)
|
||||
}
|
||||
if (command.arguments.isNotEmpty()) {
|
||||
appendLine()
|
||||
arguments(command.arguments)
|
||||
}
|
||||
if (command.options.isNotEmpty()) {
|
||||
appendLine()
|
||||
options(command.options)
|
||||
}
|
||||
}
|
||||
|
||||
private fun StringBuilder.usage(command: Command) {
|
||||
append("Usage:")
|
||||
for (command in command.path) {
|
||||
append(" ")
|
||||
when {
|
||||
command is Command.Fallback<*> -> append("<${command.name}>")
|
||||
else -> append(command.name)
|
||||
}
|
||||
}
|
||||
for (argument in command.arguments) {
|
||||
append(" ")
|
||||
when {
|
||||
argument.min == 1 && argument.max == 1 -> append("<${argument.name}>")
|
||||
argument.min == 0 && argument.max == 1 -> append("[<${argument.name}>]")
|
||||
else -> {
|
||||
val range = when {
|
||||
argument.unbounded -> "{${argument.min},}"
|
||||
argument.min == argument.max -> "{${argument.min}}"
|
||||
else -> "{${argument.min},${argument.max}}"
|
||||
}
|
||||
append("<${argument.name}>$range")
|
||||
}
|
||||
}
|
||||
}
|
||||
for (option in command.options) {
|
||||
append(" ")
|
||||
val text = buildString {
|
||||
val names = option.names.joinToString("|") { it.withPrefix() }
|
||||
append(names)
|
||||
append(" ")
|
||||
when {
|
||||
option.flag -> append("[<value>]")
|
||||
else -> append("<value>")
|
||||
}
|
||||
}
|
||||
when {
|
||||
option.min == 1 && option.max == 1 -> append("($text)")
|
||||
option.min == 0 && option.max == 1 -> append("[$text]")
|
||||
else -> {
|
||||
val range = when {
|
||||
option.unbounded -> "{${option.min},}"
|
||||
option.min == option.max -> "{${option.min}}"
|
||||
else -> "{${option.min},${option.max}}"
|
||||
}
|
||||
append("($text)$range")
|
||||
}
|
||||
}
|
||||
}
|
||||
appendLine()
|
||||
}
|
||||
|
||||
private fun StringBuilder.commands(commands: List<Command>) {
|
||||
appendLine("Commands:")
|
||||
for (command in commands) {
|
||||
appendLine(" * ${command.name}")
|
||||
}
|
||||
}
|
||||
|
||||
private fun StringBuilder.arguments(arguments: List<Argument<*>>) {
|
||||
appendLine("Arguments:")
|
||||
for (argument in arguments) {
|
||||
appendLine(" * ${argument.name}")
|
||||
}
|
||||
}
|
||||
|
||||
private fun StringBuilder.options(options: List<Option<*>>) {
|
||||
appendLine("Options:")
|
||||
for (option in options) {
|
||||
val name = option.names.joinToString(" | ") { it.withPrefix() }
|
||||
appendLine(" * $name")
|
||||
}
|
||||
}
|
||||
|
||||
private fun String.withPrefix() = when {
|
||||
length == 1 -> "-$this"
|
||||
else -> "--$this"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.infendro.cli.command.help
|
||||
|
||||
import com.infendro.cli.command.Command
|
||||
|
||||
interface HelpRenderer {
|
||||
fun render(command: Command): String?
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.infendro.cli.command.help
|
||||
|
||||
import com.infendro.cli.command.Command
|
||||
|
||||
object NoopHelpRenderer : HelpRenderer {
|
||||
override fun render(command: Command) = null
|
||||
}
|
||||
@@ -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>,
|
||||
@@ -33,7 +33,7 @@ sealed class Option<T : Any>(
|
||||
init {
|
||||
when {
|
||||
names.isEmpty() -> throw MissingOptionName()
|
||||
min !in 0..count -> throw InvalidRange()
|
||||
min !in 0..count || max == 0 -> throw InvalidRange()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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}"""
|
||||
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,11 +1,10 @@
|
||||
package com.infendro.cli.parser
|
||||
|
||||
import com.infendro.cli.exception.run.InvalidValue
|
||||
|
||||
object BooleanParser : Parser<Boolean> {
|
||||
override fun parse(text: String): Boolean = when (text) {
|
||||
"true", "t" -> true
|
||||
"false", "f" -> false
|
||||
else -> throw InvalidValue(text, Boolean::class)
|
||||
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,8 +1,8 @@
|
||||
package com.infendro.cli.parser
|
||||
|
||||
import com.infendro.cli.exception.run.InvalidValue
|
||||
|
||||
object DoubleParser : Parser<Double> {
|
||||
override fun parse(text: String): Double = text.toDoubleOrNull()
|
||||
?: throw InvalidValue(text, Double::class)
|
||||
object DoubleParser : Parser<Double>(Double::class) {
|
||||
override fun parse(text: String) =
|
||||
text.toDoubleOrNull()
|
||||
?.let { success(it) }
|
||||
?: failure(text)
|
||||
}
|
||||
|
||||
@@ -1,15 +1,16 @@
|
||||
package com.infendro.cli.parser
|
||||
|
||||
import com.infendro.cli.exception.run.InvalidValue
|
||||
import kotlin.enums.enumEntries
|
||||
import kotlin.reflect.KClass
|
||||
|
||||
class EnumParser<T : Enum<T>>(
|
||||
private 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 }
|
||||
?: throw InvalidValue(text, type)
|
||||
) : 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,8 +1,8 @@
|
||||
package com.infendro.cli.parser
|
||||
|
||||
import com.infendro.cli.exception.run.InvalidValue
|
||||
|
||||
object FloatParser : Parser<Float> {
|
||||
override fun parse(text: String): Float = text.toFloatOrNull()
|
||||
?: throw InvalidValue(text, Float::class)
|
||||
object FloatParser : Parser<Float>(Float::class) {
|
||||
override fun parse(text: String) =
|
||||
text.toFloatOrNull()
|
||||
?.let { success(it) }
|
||||
?: failure(text)
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
package com.infendro.cli.parser
|
||||
|
||||
import com.infendro.cli.exception.run.InvalidValue
|
||||
|
||||
object IntParser : Parser<Int> {
|
||||
override fun parse(text: String): Int = text.toIntOrNull()
|
||||
?: throw InvalidValue(text, Int::class)
|
||||
object IntParser : Parser<Int>(Int::class) {
|
||||
override fun parse(text: String) =
|
||||
text.toIntOrNull()
|
||||
?.let { success(it) }
|
||||
?: failure(text)
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
package com.infendro.cli.parser
|
||||
|
||||
import com.infendro.cli.exception.run.InvalidValue
|
||||
|
||||
object LongParser : Parser<Long> {
|
||||
override fun parse(text: String): Long = text.toLongOrNull()
|
||||
?: throw InvalidValue(text, Long::class)
|
||||
object LongParser : Parser<Long>(Long::class) {
|
||||
override fun parse(text: String) =
|
||||
text.toLongOrNull()
|
||||
?.let { success(it) }
|
||||
?: failure(text)
|
||||
}
|
||||
|
||||
@@ -1,5 +1,24 @@
|
||||
package com.infendro.cli.parser
|
||||
|
||||
interface Parser<T> {
|
||||
fun parse(text: String): T
|
||||
import com.infendro.cli.exception.run.InvalidValue
|
||||
import com.infendro.cli.exception.run.RuntimeError
|
||||
import kotlin.reflect.KClass
|
||||
|
||||
abstract class Parser<T : Any>(
|
||||
val type: KClass<T>,
|
||||
) {
|
||||
sealed class Result<T : Any> {
|
||||
data class Success<T : Any>(
|
||||
val value: T,
|
||||
) : Result<T>()
|
||||
|
||||
data class Failure<T : Any>(
|
||||
val error: RuntimeError,
|
||||
) : Result<T>()
|
||||
}
|
||||
|
||||
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,5 +1,6 @@
|
||||
package com.infendro.cli.parser
|
||||
|
||||
object StringParser : Parser<String> {
|
||||
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