improve command handling, change argument/option registration
This commit is contained in:
@@ -8,12 +8,10 @@ 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.error.build.*
|
||||
import com.infendro.cli.parser.*
|
||||
import com.infendro.cli.parser.Parser
|
||||
import com.infendro.cli.util.Regex
|
||||
import kotlin.reflect.KProperty
|
||||
|
||||
sealed class Command private constructor(
|
||||
val parent: Command?,
|
||||
val name: String,
|
||||
val commands: List<Command>,
|
||||
val arguments: List<Argument<*>>,
|
||||
@@ -21,22 +19,21 @@ sealed class Command private constructor(
|
||||
internal val execute: Context.() -> Unit,
|
||||
internal val renderer: HelpRenderer,
|
||||
) {
|
||||
val path: List<Command>
|
||||
get() = when {
|
||||
parent == null -> listOf(this)
|
||||
else -> parent.path + this
|
||||
}
|
||||
|
||||
val help: String?
|
||||
get() = renderer.render(this)
|
||||
init {
|
||||
if (!name.matches(Regex.COMMAND)) throw InvalidCommand(name)
|
||||
}
|
||||
|
||||
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.Help -> {
|
||||
val command = result.path.last()
|
||||
command.renderer.render(result.path)?.let { print(it) }
|
||||
}
|
||||
is ContextParser.Result.Failure -> {
|
||||
println("error: ${result.error.message}")
|
||||
result.command.help?.let {
|
||||
val command = result.path.last()
|
||||
command.renderer.render(result.path)?.let {
|
||||
println()
|
||||
print(it)
|
||||
}
|
||||
@@ -45,24 +42,22 @@ sealed class Command private constructor(
|
||||
}
|
||||
|
||||
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) {
|
||||
) : Command(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)
|
||||
Named(name, commands, arguments, options, execute, renderer)
|
||||
}
|
||||
}
|
||||
|
||||
class Fallback<T : Any>(
|
||||
parent: Command?,
|
||||
val key: Key<T>,
|
||||
val parser: Parser<T>,
|
||||
name: String,
|
||||
@@ -71,7 +66,7 @@ sealed class Command private constructor(
|
||||
options: List<Option<*>>,
|
||||
execute: Context.() -> Unit,
|
||||
renderer: HelpRenderer,
|
||||
) : Command(parent, name, commands, arguments, options, execute, renderer) {
|
||||
) : Command(name, commands, arguments, options, execute, renderer) {
|
||||
class Builder<T : Any>(
|
||||
val parser: Parser<T>,
|
||||
name: String,
|
||||
@@ -79,7 +74,7 @@ sealed class Command private constructor(
|
||||
internal val key = Key<T>()
|
||||
|
||||
override fun create() =
|
||||
Fallback(parent, key, parser, name, commands, arguments, options, execute, renderer)
|
||||
Fallback(key, parser, name, commands, arguments, options, execute, renderer)
|
||||
}
|
||||
|
||||
class Key<T>
|
||||
@@ -89,8 +84,6 @@ sealed class Command private constructor(
|
||||
sealed class Builder<COMMAND : Command>(
|
||||
protected val name: String,
|
||||
) {
|
||||
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<*>>()
|
||||
@@ -102,40 +95,13 @@ sealed class Command private constructor(
|
||||
protected val renderer: HelpRenderer
|
||||
get() = _renderer!!
|
||||
|
||||
fun command(name: String, block: Builder<*>.() -> Unit) {
|
||||
validateCommand(name)
|
||||
builders += Named.Builder(name).apply(block)
|
||||
fun register(command: Command) {
|
||||
validateCommand(command)
|
||||
commands += command
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
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(vararg commands: Command) = commands.forEach(::register)
|
||||
operator fun <T : Command> T.unaryPlus() = also(::register)
|
||||
|
||||
fun register(argument: Argument<*>) {
|
||||
validateArgument(argument)
|
||||
@@ -143,9 +109,7 @@ sealed class Command private constructor(
|
||||
}
|
||||
|
||||
fun register(vararg arguments: Argument<*>) = arguments.forEach(::register)
|
||||
|
||||
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.unaryPlus() = also(::register)
|
||||
|
||||
fun register(option: Option<*>) {
|
||||
validateOption(option)
|
||||
@@ -153,9 +117,7 @@ sealed class Command private constructor(
|
||||
}
|
||||
|
||||
fun register(vararg options: Option<*>) = options.forEach(::register)
|
||||
|
||||
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.unaryPlus() = also(::register)
|
||||
|
||||
fun execute(block: Context.() -> Unit) {
|
||||
validateExecute()
|
||||
@@ -167,32 +129,22 @@ sealed class Command private constructor(
|
||||
_renderer = renderer
|
||||
}
|
||||
|
||||
internal abstract fun create(): COMMAND
|
||||
|
||||
internal fun build(): Command {
|
||||
if (_execute == null) _execute = {}
|
||||
if (_renderer == null) _renderer = DefaultHelpRenderer
|
||||
|
||||
validate()
|
||||
val command = create()
|
||||
|
||||
for (builder in builders) {
|
||||
builder.parent = command
|
||||
commands += builder.build()
|
||||
}
|
||||
|
||||
return command
|
||||
return create()
|
||||
}
|
||||
|
||||
internal abstract fun create(): COMMAND
|
||||
|
||||
private fun validateCommand(name: String) {
|
||||
if (builders.isNotEmpty()) {
|
||||
val last = builders.last()
|
||||
if (last is Fallback.Builder<*>) throw InvalidCommandOrder()
|
||||
}
|
||||
when {
|
||||
!name.matches(Regex.COMMAND) -> throw InvalidCommand(name)
|
||||
builders.any { it.name == name } -> throw DuplicateCommand(name)
|
||||
private fun validateCommand(command: Command) {
|
||||
if (commands.isNotEmpty()) {
|
||||
val last = commands.last()
|
||||
if (last is Fallback<*>) throw InvalidCommandOrder()
|
||||
}
|
||||
if (commands.any { it.name == command.name }) throw DuplicateCommand(command.name)
|
||||
}
|
||||
|
||||
private fun validateArgument(argument: Argument<*>) {
|
||||
@@ -203,6 +155,7 @@ sealed class Command private constructor(
|
||||
argument.required && last.optional -> throw InvalidArgumentOrder()
|
||||
}
|
||||
}
|
||||
if (arguments.any { it.name == argument.name }) throw DuplicateArgument(argument.name)
|
||||
}
|
||||
|
||||
private fun validateOption(option: Option<*>) {
|
||||
@@ -220,10 +173,7 @@ sealed class Command private constructor(
|
||||
}
|
||||
|
||||
private fun validate() {
|
||||
if (builders.any { it is Fallback.Builder<*> } && arguments.isNotEmpty()) throw InvalidFallback()
|
||||
if (commands.any { it is Fallback<*> } && arguments.isNotEmpty()) throw InvalidFallback()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun cli(name: String, block: Command.Builder<*>.() -> Unit) =
|
||||
Command.Named.Builder(name).apply(block).build()
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
package com.infendro.cli.command
|
||||
|
||||
import com.infendro.cli.command.Command.*
|
||||
import com.infendro.cli.parser.*
|
||||
|
||||
class CommandFactory internal constructor() {
|
||||
inner class FallbackFactory internal constructor() {
|
||||
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 <T : Any> fallback(parser: Parser<T>, name: String, block: Fallback.Builder<T>.(Fallback.Key<T>) -> Unit) =
|
||||
Fallback.Builder(parser, name).apply { block(key) }.build()
|
||||
|
||||
val fallback = FallbackFactory()
|
||||
}
|
||||
|
||||
fun command(name: String, block: Builder<*>.() -> Unit) =
|
||||
Named.Builder(name).apply(block).build()
|
||||
|
||||
val command = CommandFactory()
|
||||
@@ -8,15 +8,18 @@ import kotlin.reflect.KProperty
|
||||
|
||||
@Dsl
|
||||
class Context internal constructor(
|
||||
val command: Command,
|
||||
private val path: List<Command>,
|
||||
private val commands: Map<Command.Fallback.Key<*>, Any>,
|
||||
private val arguments: Map<Argument<*>, List<Any>>,
|
||||
private val options: Map<Option<*>, List<Any>>,
|
||||
) {
|
||||
val command: Command
|
||||
get() = path.last()
|
||||
|
||||
internal fun execute() = (command.execute)()
|
||||
|
||||
fun help() {
|
||||
command.help?.let { print(it) }
|
||||
command.renderer.render(path)?.let { print(it) }
|
||||
}
|
||||
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
|
||||
@@ -14,18 +14,18 @@ internal class ContextParser(
|
||||
) : Result()
|
||||
|
||||
data class Help(
|
||||
val command: Command,
|
||||
val path: List<Command>,
|
||||
) : Result()
|
||||
|
||||
data class Failure(
|
||||
val command: Command,
|
||||
val path: List<Command>,
|
||||
val error: RunError,
|
||||
) : Result()
|
||||
}
|
||||
|
||||
private fun success(context: Context) = Result.Success(context)
|
||||
private fun help(command: Command) = Result.Help(command)
|
||||
private fun failure(command: Command, exception: RunError) = Result.Failure(command, exception)
|
||||
private fun help(path: List<Command>) = Result.Help(path)
|
||||
private fun failure(path: List<Command>, exception: RunError) = Result.Failure(path, exception)
|
||||
|
||||
private var index = 0
|
||||
private val current: String
|
||||
@@ -41,6 +41,7 @@ internal class ContextParser(
|
||||
fun parse(): Result {
|
||||
// command
|
||||
var command = root
|
||||
val path = mutableListOf(root)
|
||||
val commands = mutableMapOf<Command.Fallback.Key<*>, Any>()
|
||||
|
||||
while (hasNext()) {
|
||||
@@ -52,16 +53,17 @@ internal class ContextParser(
|
||||
}
|
||||
if (cmd == null) {
|
||||
when {
|
||||
command.arguments.isEmpty() -> return failure(command, UnknownCommand(current))
|
||||
command.arguments.isEmpty() -> return failure(path, UnknownCommand(current))
|
||||
else -> break
|
||||
}
|
||||
}
|
||||
|
||||
command = cmd
|
||||
path += 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)
|
||||
is Parser.Result.Failure<*> -> return failure(path, result.error)
|
||||
}
|
||||
commands[cmd.key] = value
|
||||
}
|
||||
@@ -85,11 +87,11 @@ internal class ContextParser(
|
||||
// argument
|
||||
endOfOptions || dashes == 0 -> {
|
||||
val argument = command.arguments.getOrNull(argumentIndex)
|
||||
?: return failure(command, UnexpectedArgument())
|
||||
?: return failure(path, 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)
|
||||
is Parser.Result.Failure<*> -> return failure(path, result.error)
|
||||
}
|
||||
arguments[argument]!! += value
|
||||
argumentCount++
|
||||
@@ -109,7 +111,7 @@ internal class ContextParser(
|
||||
}
|
||||
|
||||
if (dashes == 2 && trimmed == "help")
|
||||
return help(command)
|
||||
return help(path)
|
||||
|
||||
val (name, text) = when {
|
||||
trimmed.contains('=') -> {
|
||||
@@ -133,16 +135,16 @@ internal class ContextParser(
|
||||
|
||||
for (name in names) {
|
||||
val option = command.options.firstOrNull { name in it.names }
|
||||
?: return failure(command, UnknownOption(name))
|
||||
?: return failure(path, 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)
|
||||
is Parser.Result.Failure<*> -> return failure(path, result.error)
|
||||
}
|
||||
option.flag -> option.fallback!!
|
||||
else -> return failure(command, MissingOptionValue(option))
|
||||
else -> return failure(path, MissingOptionValue(option))
|
||||
}
|
||||
options[option]!! += value
|
||||
}
|
||||
@@ -153,9 +155,9 @@ internal class ContextParser(
|
||||
when {
|
||||
current.contains('=') -> {
|
||||
val (option) = current.split('=', limit = 2)
|
||||
return failure(command, MalformedOption(option))
|
||||
return failure(path, MalformedOption(option))
|
||||
}
|
||||
else -> return failure(command, MalformedOption(current))
|
||||
else -> return failure(path, MalformedOption(current))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -166,16 +168,16 @@ internal class ContextParser(
|
||||
// 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))
|
||||
if (count !in argument.min..argument.count) return failure(path, 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))
|
||||
if (count !in option.min..option.count) return failure(path, InvalidOptionCount(option, count))
|
||||
}
|
||||
|
||||
val context = Context(command, commands, arguments, options)
|
||||
val context = Context(path, commands, arguments, options)
|
||||
return success(context)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,8 +5,10 @@ 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)
|
||||
override fun render(path: List<Command>) = buildString {
|
||||
val command = path.last()
|
||||
|
||||
usage(path)
|
||||
if (command.commands.isNotEmpty()) {
|
||||
appendLine()
|
||||
commands(command.commands)
|
||||
@@ -21,9 +23,11 @@ object DefaultHelpRenderer : HelpRenderer {
|
||||
}
|
||||
}
|
||||
|
||||
private fun StringBuilder.usage(command: Command) {
|
||||
private fun StringBuilder.usage(path: List<Command>) {
|
||||
val command = path.last()
|
||||
|
||||
append("Usage:")
|
||||
for (command in command.path) {
|
||||
for (command in path) {
|
||||
append(" ")
|
||||
when {
|
||||
command is Command.Fallback<*> -> append("<${command.name}>")
|
||||
|
||||
@@ -3,5 +3,5 @@ package com.infendro.cli.command.help
|
||||
import com.infendro.cli.command.Command
|
||||
|
||||
interface HelpRenderer {
|
||||
fun render(command: Command): String?
|
||||
fun render(path: List<Command>): String?
|
||||
}
|
||||
|
||||
@@ -3,5 +3,5 @@ package com.infendro.cli.command.help
|
||||
import com.infendro.cli.command.Command
|
||||
|
||||
object NoopHelpRenderer : HelpRenderer {
|
||||
override fun render(command: Command) = null
|
||||
override fun render(path: List<Command>) = null
|
||||
}
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
package com.infendro.cli.error.build
|
||||
|
||||
class DuplicateArgument(
|
||||
val name: String,
|
||||
) : BuildException() {
|
||||
override val message: String
|
||||
get() = """duplicate argument "$name""""
|
||||
}
|
||||
Reference in New Issue
Block a user