implement automatic help
This commit is contained in:
@@ -31,7 +31,7 @@ dependencies {
|
|||||||
fun main(args: Array<String>) = cli("application") {
|
fun main(args: Array<String>) = cli("application") {
|
||||||
execute {
|
execute {
|
||||||
// define execution of command (e.g., display help)
|
// define execution of command (e.g., display help)
|
||||||
println("Usage: application <command> [arguments] [options]")
|
help()
|
||||||
}
|
}
|
||||||
|
|
||||||
// declare command "greet"
|
// declare command "greet"
|
||||||
|
|||||||
@@ -10,9 +10,7 @@ sealed class Argument<T : Any>(
|
|||||||
val max: Int?,
|
val max: Int?,
|
||||||
) {
|
) {
|
||||||
init {
|
init {
|
||||||
when {
|
if (min !in 0..count || max == 0) throw InvalidRange()
|
||||||
min !in 0..count -> throw InvalidRange()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
val required: Boolean
|
val required: Boolean
|
||||||
|
|||||||
@@ -3,25 +3,42 @@ package com.infendro.cli.command
|
|||||||
import com.infendro.cli.Dsl
|
import com.infendro.cli.Dsl
|
||||||
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.Parser
|
||||||
|
import com.infendro.cli.command.help.DefaultHelpRenderer
|
||||||
|
import com.infendro.cli.command.help.HelpRenderer
|
||||||
import com.infendro.cli.exception.build.*
|
import com.infendro.cli.exception.build.*
|
||||||
import com.infendro.cli.exception.run.RunException
|
|
||||||
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.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(
|
class Command private constructor(
|
||||||
|
val parent: Command?,
|
||||||
val name: String,
|
val name: String,
|
||||||
val fallback: Boolean,
|
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<*>>,
|
||||||
internal val execute: Context.() -> Unit,
|
internal val execute: Context.() -> Unit,
|
||||||
|
internal val renderer: HelpRenderer,
|
||||||
) {
|
) {
|
||||||
fun run(args: Array<String>) = try {
|
val path: List<Command>
|
||||||
Parser.parse(this, args).execute()
|
get() = when {
|
||||||
} catch (e: RunException) {
|
parent == null -> listOf(this)
|
||||||
println(e.message)
|
else -> parent.path + this
|
||||||
|
}
|
||||||
|
|
||||||
|
val help: String?
|
||||||
|
get() = renderer.render(this)
|
||||||
|
|
||||||
|
fun run(args: Array<String>) {
|
||||||
|
when (val result = Parser(this, args).parse()) {
|
||||||
|
is Parser.Result.Success -> result.context.execute()
|
||||||
|
is Parser.Result.Help -> result.command.help?.let { println(it) }
|
||||||
|
is Parser.Result.Failure -> {
|
||||||
|
println("error: ${result.exception.message}")
|
||||||
|
result.command.help?.let { println("\n$it") }
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Dsl
|
@Dsl
|
||||||
@@ -29,8 +46,10 @@ class Command private constructor(
|
|||||||
private val level: Int,
|
private val level: Int,
|
||||||
private val name: String,
|
private val name: String,
|
||||||
private val fallback: Boolean,
|
private val fallback: Boolean,
|
||||||
|
var renderer: HelpRenderer,
|
||||||
) {
|
) {
|
||||||
private val commands = mutableListOf<Command>()
|
private var parent: Command? = null
|
||||||
|
private val builders = mutableListOf<Builder>()
|
||||||
private val arguments = mutableListOf<Argument<*>>()
|
private val arguments = mutableListOf<Argument<*>>()
|
||||||
private val options = mutableListOf<Option<*>>()
|
private val options = mutableListOf<Option<*>>()
|
||||||
private lateinit var _execute: Context.() -> Unit
|
private lateinit var _execute: Context.() -> Unit
|
||||||
@@ -40,12 +59,12 @@ class Command private constructor(
|
|||||||
|
|
||||||
fun command(name: String, block: Builder.() -> Unit) {
|
fun command(name: String, block: Builder.() -> Unit) {
|
||||||
validateCommand(name)
|
validateCommand(name)
|
||||||
commands += Builder(level + 1, name, fallback = false).apply(block).build()
|
builders += Builder(level + 1, name, fallback = false, renderer).apply(block)
|
||||||
}
|
}
|
||||||
|
|
||||||
fun fallback(name: String, block: Builder.(Key) -> Unit) {
|
fun fallback(name: String, block: Builder.(Key) -> Unit) {
|
||||||
validateCommand(name)
|
validateCommand(name)
|
||||||
commands += Builder(level + 1, name, fallback = true).apply { block(key) }.build()
|
builders += Builder(level + 1, name, fallback = true, renderer).apply { block(key) }
|
||||||
}
|
}
|
||||||
|
|
||||||
fun argument(argument: Argument<*>) {
|
fun argument(argument: Argument<*>) {
|
||||||
@@ -78,19 +97,24 @@ class Command private constructor(
|
|||||||
_execute = {}
|
_execute = {}
|
||||||
|
|
||||||
validate()
|
validate()
|
||||||
return Command(name, fallback, commands, arguments, options, _execute)
|
|
||||||
|
val commands = mutableListOf<Command>()
|
||||||
|
val command = Command(parent, name, fallback, commands, arguments, options, _execute, renderer)
|
||||||
|
for (builder in builders) {
|
||||||
|
builder.parent = command
|
||||||
|
commands += builder.build()
|
||||||
|
}
|
||||||
|
return command
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun validateCommand(name: String) {
|
private fun validateCommand(name: String) {
|
||||||
if (commands.isNotEmpty()) {
|
if (builders.isNotEmpty()) {
|
||||||
val last = commands.last()
|
val last = builders.last()
|
||||||
when {
|
if (last.fallback) throw InvalidCommandOrder()
|
||||||
last.fallback -> throw InvalidCommandOrder()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
when {
|
when {
|
||||||
!name.matches(COMMAND) -> throw InvalidCommand(name)
|
!name.matches(COMMAND) -> throw InvalidCommand(name)
|
||||||
commands.any { it.name == name } -> throw DuplicateCommand(name)
|
builders.any { it.name == name } -> throw DuplicateCommand(name)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -102,9 +126,7 @@ class Command private constructor(
|
|||||||
argument.required && last.optional -> throw InvalidArgumentOrder()
|
argument.required && last.optional -> throw InvalidArgumentOrder()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
when {
|
if (!argument.name.matches(ARGUMENT)) throw InvalidArgument(argument.name)
|
||||||
!argument.name.matches(ARGUMENT) -> throw InvalidArgument(argument.name)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun validateOption(option: Option<*>) {
|
private fun validateOption(option: Option<*>) {
|
||||||
@@ -117,14 +139,11 @@ class Command private constructor(
|
|||||||
}
|
}
|
||||||
|
|
||||||
private fun validateExecute() {
|
private fun validateExecute() {
|
||||||
if (::_execute.isInitialized)
|
if (::_execute.isInitialized) throw DuplicateExecute()
|
||||||
throw DuplicateExecute()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun validate() {
|
private fun validate() {
|
||||||
if (commands.any { it.fallback } && arguments.isNotEmpty()) {
|
if (builders.any { it.fallback } && arguments.isNotEmpty()) throw InvalidFallback()
|
||||||
throw InvalidFallback()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -134,4 +153,4 @@ class Command private constructor(
|
|||||||
}
|
}
|
||||||
|
|
||||||
fun cli(name: String, block: Command.Builder.() -> Unit) =
|
fun cli(name: String, block: Command.Builder.() -> Unit) =
|
||||||
Command.Builder(-1, name, fallback = false).apply(block).build()
|
Command.Builder(-1, name, fallback = false, DefaultHelpRenderer).apply(block).build()
|
||||||
|
|||||||
@@ -33,7 +33,7 @@ sealed class Option<T : Any>(
|
|||||||
init {
|
init {
|
||||||
when {
|
when {
|
||||||
names.isEmpty() -> throw MissingOptionName()
|
names.isEmpty() -> throw MissingOptionName()
|
||||||
min !in 0..count -> throw InvalidRange()
|
min !in 0..count || max == 0 -> throw InvalidRange()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -10,8 +10,8 @@ import kotlin.reflect.KProperty
|
|||||||
class Context internal constructor(
|
class Context internal constructor(
|
||||||
val command: Command,
|
val command: Command,
|
||||||
val commands: List<Cmd>,
|
val commands: List<Cmd>,
|
||||||
val options: List<Opt>,
|
|
||||||
val arguments: List<Arg>,
|
val arguments: List<Arg>,
|
||||||
|
val options: List<Opt>,
|
||||||
) {
|
) {
|
||||||
class Cmd(
|
class Cmd(
|
||||||
val name: String,
|
val name: String,
|
||||||
@@ -28,6 +28,10 @@ class Context internal constructor(
|
|||||||
|
|
||||||
internal fun execute() = (command.execute)()
|
internal fun execute() = (command.execute)()
|
||||||
|
|
||||||
|
fun help() {
|
||||||
|
command.help?.let { println(it) }
|
||||||
|
}
|
||||||
|
|
||||||
operator fun Command.Key.getValue(thisRef: Any?, property: KProperty<*>): String = commands[index].name
|
operator fun Command.Key.getValue(thisRef: Any?, property: KProperty<*>): String = commands[index].name
|
||||||
|
|
||||||
private val <T : Any> Argument<T>.index: Int
|
private val <T : Any> Argument<T>.index: Int
|
||||||
|
|||||||
@@ -4,26 +4,55 @@ import com.infendro.cli.command.Command
|
|||||||
import com.infendro.cli.command.context.Context.*
|
import com.infendro.cli.command.context.Context.*
|
||||||
import com.infendro.cli.exception.run.*
|
import com.infendro.cli.exception.run.*
|
||||||
|
|
||||||
internal object Parser {
|
internal class Parser(
|
||||||
fun parse(root: Command, args: Array<String>): Context {
|
private val root: Command,
|
||||||
|
private val args: Array<String>,
|
||||||
|
) {
|
||||||
|
private var index = 0
|
||||||
|
private val current: String
|
||||||
|
get() = args[index]
|
||||||
|
private val next: String?
|
||||||
|
get() = args.getOrNull(index)
|
||||||
|
|
||||||
|
private fun hasNext() = index < args.size
|
||||||
|
private fun consume() {
|
||||||
|
index++
|
||||||
|
}
|
||||||
|
|
||||||
|
sealed class Result {
|
||||||
|
data class Success(
|
||||||
|
val context: Context,
|
||||||
|
) : Result()
|
||||||
|
|
||||||
|
data class Help(
|
||||||
|
val command: Command,
|
||||||
|
) : Result()
|
||||||
|
|
||||||
|
data class Failure(
|
||||||
|
val command: Command,
|
||||||
|
val exception: RunException,
|
||||||
|
) : Result()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun success(context: Context) = Result.Success(context)
|
||||||
|
fun help(command: Command) = Result.Help(command)
|
||||||
|
fun failure(command: Command, exception: RunException) = Result.Failure(command, exception)
|
||||||
|
|
||||||
|
fun parse(): Result {
|
||||||
var command = root
|
var command = root
|
||||||
val cmd = mutableListOf<Cmd>()
|
val cmd = mutableListOf<Cmd>()
|
||||||
val arg = mutableListOf<Arg>()
|
val arg = mutableListOf<Arg>()
|
||||||
val opt = mutableListOf<Opt>()
|
val opt = mutableListOf<Opt>()
|
||||||
|
|
||||||
var i = 0
|
// command
|
||||||
|
while (hasNext()) {
|
||||||
// commands
|
|
||||||
while (i < args.size) {
|
|
||||||
val current = args[i]
|
|
||||||
|
|
||||||
if (current.startsWith("-"))
|
if (current.startsWith("-"))
|
||||||
break
|
break
|
||||||
|
|
||||||
val c = command.commands.firstOrNull { it.name == current || it.fallback }
|
val c = command.commands.firstOrNull { it.name == current || it.fallback }
|
||||||
if (c == null) {
|
if (c == null) {
|
||||||
when {
|
when {
|
||||||
command.arguments.isEmpty() -> throw UnknownCommand(current)
|
command.arguments.isEmpty() -> return failure(command, UnknownCommand(current))
|
||||||
else -> break
|
else -> break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -31,24 +60,25 @@ internal object Parser {
|
|||||||
command = c
|
command = c
|
||||||
cmd += Cmd(current)
|
cmd += Cmd(current)
|
||||||
|
|
||||||
i++
|
consume()
|
||||||
}
|
}
|
||||||
|
|
||||||
// arguments and options
|
// arguments and options
|
||||||
var endOfOptions = false
|
var endOfOptions = false
|
||||||
var argumentIndex = 0
|
var argumentIndex = 0
|
||||||
var argumentCount = 0
|
var argumentCount = 0
|
||||||
while (i < args.size) {
|
|
||||||
val dashes = args[i].takeWhile { it == '-' }.count()
|
while (hasNext()) {
|
||||||
val current = args[i].drop(dashes)
|
val dashes = current.takeWhile { it == '-' }.count()
|
||||||
|
val trimmed = current.drop(dashes)
|
||||||
|
|
||||||
when {
|
when {
|
||||||
// argument
|
// argument
|
||||||
endOfOptions || dashes == 0 -> {
|
endOfOptions || dashes == 0 -> {
|
||||||
val argument = command.arguments.getOrNull(argumentIndex)
|
val argument = command.arguments.getOrNull(argumentIndex)
|
||||||
?: throw UnexpectedArgument()
|
?: return failure(command, UnexpectedArgument())
|
||||||
|
|
||||||
val value = argument.parser.parse(current)
|
val value = argument.parser.parse(trimmed)
|
||||||
arg += Arg(value)
|
arg += Arg(value)
|
||||||
argumentCount++
|
argumentCount++
|
||||||
|
|
||||||
@@ -60,25 +90,26 @@ internal object Parser {
|
|||||||
|
|
||||||
// option
|
// option
|
||||||
dashes in 1..2 -> {
|
dashes in 1..2 -> {
|
||||||
if (dashes == 2 && current.isEmpty()) {
|
if (dashes == 2 && trimmed.isEmpty()) {
|
||||||
endOfOptions = true
|
endOfOptions = true
|
||||||
i++
|
consume()
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (dashes == 2 && trimmed == "help")
|
||||||
|
return help(command)
|
||||||
|
|
||||||
val (name, text) = when {
|
val (name, text) = when {
|
||||||
current.contains('=') -> {
|
trimmed.contains('=') -> {
|
||||||
val (name, value) = current.split('=', limit = 2)
|
val (name, value) = trimmed.split('=', limit = 2)
|
||||||
name to value
|
name to value
|
||||||
}
|
}
|
||||||
|
|
||||||
else -> {
|
else -> {
|
||||||
val next = args.getOrNull(i + 1)
|
if (next?.startsWith('-') == false) {
|
||||||
if (next != null && !next.startsWith('-')) {
|
consume()
|
||||||
i++
|
trimmed to next
|
||||||
current to next
|
|
||||||
} else {
|
} else {
|
||||||
current to null
|
trimmed to null
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -90,12 +121,12 @@ internal object Parser {
|
|||||||
|
|
||||||
for (name in names) {
|
for (name in names) {
|
||||||
val option = command.options.firstOrNull { name in it.names }
|
val option = command.options.firstOrNull { name in it.names }
|
||||||
?: throw UnknownOption(name)
|
?: return failure(command, UnknownOption(name))
|
||||||
|
|
||||||
val value = when {
|
val value = when {
|
||||||
text != null -> option.parser.parse(text)
|
text != null -> option.parser.parse(text)
|
||||||
option.flag -> option.fallback!!
|
option.flag -> option.fallback!!
|
||||||
else -> throw MissingOptionValue(option)
|
else -> return failure(command, MissingOptionValue(option))
|
||||||
}
|
}
|
||||||
opt += Opt(name, value)
|
opt += Opt(name, value)
|
||||||
}
|
}
|
||||||
@@ -104,40 +135,36 @@ internal object Parser {
|
|||||||
// malformed option
|
// malformed option
|
||||||
else -> {
|
else -> {
|
||||||
when {
|
when {
|
||||||
args[i].contains('=') -> {
|
current.contains('=') -> {
|
||||||
val (option) = args[i].split('=', limit = 2)
|
val (option) = current.split('=', limit = 2)
|
||||||
throw MalformedOption(option)
|
return failure(command, MalformedOption(option))
|
||||||
}
|
}
|
||||||
else -> throw MalformedOption(args[i])
|
else -> return failure(command, MalformedOption(current))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
i++
|
consume()
|
||||||
}
|
}
|
||||||
|
|
||||||
validateArguments(command, arg)
|
// validate arguments
|
||||||
validateOptions(command, opt)
|
|
||||||
|
|
||||||
return Context(command, cmd, opt, arg)
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun validateArguments(command: Command, arg: List<Arg>) {
|
|
||||||
val required = command.arguments.filter { it.required }
|
val required = command.arguments.filter { it.required }
|
||||||
var consumed = 0
|
var consumed = 0
|
||||||
for (argument in required) {
|
for (argument in required) {
|
||||||
val needed = if (argument === required.last()) argument.min else argument.count
|
val needed = if (argument === required.last()) argument.min else argument.count
|
||||||
val delta = arg.size - consumed
|
val delta = arg.size - consumed
|
||||||
if (delta < needed) throw InvalidArgumentCount(argument, delta)
|
if (delta < needed) return failure(command, InvalidArgumentCount(argument, delta))
|
||||||
|
|
||||||
consumed += needed
|
consumed += needed
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
private fun validateOptions(command: Command, opt: List<Opt>) {
|
// validate options
|
||||||
for (option in command.options) {
|
for (option in command.options) {
|
||||||
val count = opt.count { it.name in option.names }
|
val count = opt.count { it.name in option.names }
|
||||||
if (count !in option.min..option.count) throw InvalidOptionCount(option, count)
|
if (count !in option.min..option.count) return failure(command, InvalidOptionCount(option, count))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
val context = Context(command, cmd, arg, opt)
|
||||||
|
return success(context)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,101 @@
|
|||||||
|
package com.infendro.cli.command.help
|
||||||
|
|
||||||
|
import com.infendro.cli.command.Argument
|
||||||
|
import com.infendro.cli.command.Command
|
||||||
|
import com.infendro.cli.command.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.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
|
||||||
|
}
|
||||||
@@ -7,5 +7,5 @@ class InvalidValue(
|
|||||||
val type: KClass<*>,
|
val type: KClass<*>,
|
||||||
) : RunException() {
|
) : RunException() {
|
||||||
override val message: String
|
override val message: String
|
||||||
get() = """"$value" cannot be converted to ${type.simpleName}"""
|
get() = """"$value" cannot be converted to ${type.simpleName ?: "Unknown"}"""
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,11 +1,14 @@
|
|||||||
package com.infendro.cli.parser
|
package com.infendro.cli.parser
|
||||||
|
|
||||||
import com.infendro.cli.exception.run.InvalidValue
|
import kotlin.reflect.KClass
|
||||||
|
|
||||||
object BooleanParser : Parser<Boolean> {
|
object BooleanParser : Parser<Boolean> {
|
||||||
|
override val type: KClass<Boolean>
|
||||||
|
get() = Boolean::class
|
||||||
|
|
||||||
override fun parse(text: String): Boolean = when (text) {
|
override fun parse(text: String): Boolean = when (text) {
|
||||||
"true", "t" -> true
|
"true", "t" -> true
|
||||||
"false", "f" -> false
|
"false", "f" -> false
|
||||||
else -> throw InvalidValue(text, Boolean::class)
|
else -> invalid(text)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,8 +1,11 @@
|
|||||||
package com.infendro.cli.parser
|
package com.infendro.cli.parser
|
||||||
|
|
||||||
import com.infendro.cli.exception.run.InvalidValue
|
import kotlin.reflect.KClass
|
||||||
|
|
||||||
object DoubleParser : Parser<Double> {
|
object DoubleParser : Parser<Double> {
|
||||||
|
override val type: KClass<Double>
|
||||||
|
get() = Double::class
|
||||||
|
|
||||||
override fun parse(text: String): Double = text.toDoubleOrNull()
|
override fun parse(text: String): Double = text.toDoubleOrNull()
|
||||||
?: throw InvalidValue(text, Double::class)
|
?: invalid(text)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,15 +1,14 @@
|
|||||||
package com.infendro.cli.parser
|
package com.infendro.cli.parser
|
||||||
|
|
||||||
import com.infendro.cli.exception.run.InvalidValue
|
|
||||||
import kotlin.enums.enumEntries
|
import kotlin.enums.enumEntries
|
||||||
import kotlin.reflect.KClass
|
import kotlin.reflect.KClass
|
||||||
|
|
||||||
class EnumParser<T : Enum<T>>(
|
class EnumParser<T : Enum<T>>(
|
||||||
private val type: KClass<T>,
|
override val type: KClass<T>,
|
||||||
private val values: List<T>,
|
private val values: List<T>,
|
||||||
) : Parser<T> {
|
) : Parser<T> {
|
||||||
override fun parse(text: String): T = values.firstOrNull { it.name == text }
|
override fun parse(text: String): T = values.firstOrNull { it.name == text }
|
||||||
?: throw InvalidValue(text, type)
|
?: invalid(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,8 +1,11 @@
|
|||||||
package com.infendro.cli.parser
|
package com.infendro.cli.parser
|
||||||
|
|
||||||
import com.infendro.cli.exception.run.InvalidValue
|
import kotlin.reflect.KClass
|
||||||
|
|
||||||
object FloatParser : Parser<Float> {
|
object FloatParser : Parser<Float> {
|
||||||
|
override val type: KClass<Float>
|
||||||
|
get() = Float::class
|
||||||
|
|
||||||
override fun parse(text: String): Float = text.toFloatOrNull()
|
override fun parse(text: String): Float = text.toFloatOrNull()
|
||||||
?: throw InvalidValue(text, Float::class)
|
?: invalid(text)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,8 +1,11 @@
|
|||||||
package com.infendro.cli.parser
|
package com.infendro.cli.parser
|
||||||
|
|
||||||
import com.infendro.cli.exception.run.InvalidValue
|
import kotlin.reflect.KClass
|
||||||
|
|
||||||
object IntParser : Parser<Int> {
|
object IntParser : Parser<Int> {
|
||||||
|
override val type: KClass<Int>
|
||||||
|
get() = Int::class
|
||||||
|
|
||||||
override fun parse(text: String): Int = text.toIntOrNull()
|
override fun parse(text: String): Int = text.toIntOrNull()
|
||||||
?: throw InvalidValue(text, Int::class)
|
?: invalid(text)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,8 +1,11 @@
|
|||||||
package com.infendro.cli.parser
|
package com.infendro.cli.parser
|
||||||
|
|
||||||
import com.infendro.cli.exception.run.InvalidValue
|
import kotlin.reflect.KClass
|
||||||
|
|
||||||
object LongParser : Parser<Long> {
|
object LongParser : Parser<Long> {
|
||||||
|
override val type: KClass<Long>
|
||||||
|
get() = Long::class
|
||||||
|
|
||||||
override fun parse(text: String): Long = text.toLongOrNull()
|
override fun parse(text: String): Long = text.toLongOrNull()
|
||||||
?: throw InvalidValue(text, Long::class)
|
?: invalid(text)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,12 @@
|
|||||||
package com.infendro.cli.parser
|
package com.infendro.cli.parser
|
||||||
|
|
||||||
interface Parser<T> {
|
import com.infendro.cli.exception.run.InvalidValue
|
||||||
|
import kotlin.reflect.KClass
|
||||||
|
|
||||||
|
interface Parser<T : Any> {
|
||||||
|
val type: KClass<T>
|
||||||
|
|
||||||
fun parse(text: String): T
|
fun parse(text: String): T
|
||||||
|
|
||||||
|
fun invalid(text: String): Nothing = throw InvalidValue(text, type)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,10 @@
|
|||||||
package com.infendro.cli.parser
|
package com.infendro.cli.parser
|
||||||
|
|
||||||
|
import kotlin.reflect.KClass
|
||||||
|
|
||||||
object StringParser : Parser<String> {
|
object StringParser : Parser<String> {
|
||||||
|
override val type: KClass<String>
|
||||||
|
get() = String::class
|
||||||
|
|
||||||
override fun parse(text: String) = text
|
override fun parse(text: String) = text
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user