diff --git a/CHANGELOG.md b/CHANGELOG.md index f4d6d9a..865953e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,9 @@ +# 0.3.0 + +## Additions + +* Added `Argument#flatten` to flatten an `Argument, CONTEXT>` into a `Argument`. + # 0.2.1 ## Fixes @@ -8,7 +14,6 @@ * CommandProcessor will run commands in parallel. - # 0.2.0 ## Changes diff --git a/kordx-commands-runtime/src/main/kotlin/com/gitlab/kordlib/kordx/commands/argument/extension/Either.kt b/kordx-commands-runtime/src/main/kotlin/com/gitlab/kordlib/kordx/commands/argument/extension/Either.kt index 03fb173..99dff71 100644 --- a/kordx-commands-runtime/src/main/kotlin/com/gitlab/kordlib/kordx/commands/argument/extension/Either.kt +++ b/kordx-commands-runtime/src/main/kotlin/com/gitlab/kordlib/kordx/commands/argument/extension/Either.kt @@ -21,7 +21,19 @@ import com.gitlab.kordlib.kordx.commands.argument.result.extension.switchOnFail */ infix fun Argument.or( other: Argument -): Argument, CONTEXT> = EitherArgument(this, other) +): Argument, CONTEXT> = EitherArgument(this, other) + +fun Argument, CONTEXT>.flatten(): Argument = object : Argument { + override val example: String + get() = this@flatten.example + + override val name: String + get() = this@flatten.name + + override suspend fun parse(words: List, fromIndex: Int, context: CONTEXT): ArgumentResult { + return this@flatten.parse(words, fromIndex, context).map { (it.left ?: it.right)!! } + } +} /** * Represents one of two possible values, [left] or [right]. @@ -73,10 +85,11 @@ sealed class Either { /** * Gets the present value in either left or right. */ -val Either.value get() = when(this) { - is Either.Left -> left - is Either.Right -> right -} +val Either.value + get() = when (this) { + is Either.Left -> left + is Either.Right -> right + } private class EitherArgument( private val left: Argument, @@ -88,8 +101,8 @@ private class EitherArgument( @Suppress("RemoveExplicitTypeArguments") override suspend fun parse(words: List, fromIndex: Int, context: CONTEXT): ArgumentResult> { - val left: ArgumentResult> = left.parse(words, fromIndex, context).map { Either.Left(it) } - return left.switchOnFail { right.parse(words, fromIndex, context).map { Either.Right(it) } } + val left: ArgumentResult> = left.parse(words, fromIndex, context).map { Either.Left(it) } + return left.switchOnFail { right.parse(words, fromIndex, context).map { Either.Right(it) } } } }