All Downloads are FREE. Search and download functionalities are using the official Maven repository.

me.jakejmattson.kutils.api.arguments.EitherArg.kt Maven / Gradle / Ivy

There is a newer version: 0.18.1
Show newest version
@file:Suppress("unused")

package me.jakejmattson.kutils.api.arguments

import me.jakejmattson.kutils.api.dsl.arguments.*
import me.jakejmattson.kutils.api.dsl.command.CommandEvent

internal data class Left(val data: L) : Either()
internal data class Right(val data: R) : Either()

sealed class Either {
    fun  getData(left: (L) -> T, right: (R) -> T) =
        when (this) {
            is Left -> left.invoke(data)
            is Right -> right.invoke(data)
        }
}

// Either accept the left argument or the right argument type. Left is tried first.
class EitherArg(val left: ArgumentType, val right: ArgumentType, name: String = "") : ArgumentType>() {
    override val name = if (name.isNotBlank()) name else "${left.name} | ${right.name}"

    override fun convert(arg: String, args: List, event: CommandEvent<*>): ArgumentResult> {
        val leftResult = left.convert(arg, args, event)
        val rightResult = right.convert(arg, args, event)

        return when {
            leftResult is ArgumentResult.Success -> ArgumentResult.Success(Left(leftResult.result), leftResult.consumed)
            rightResult is ArgumentResult.Success -> ArgumentResult.Success(Right(rightResult.result), rightResult.consumed)
            else -> ArgumentResult.Error("Could not match input with either expected argument.")
        }
    }

    override fun generateExamples(event: CommandEvent<*>): List {
        val leftExample = left.generateExamples(event).takeIf { it.isNotEmpty() }?.random() ?: ""
        val rightExample = right.generateExamples(event).takeIf { it.isNotEmpty() }?.random() ?: ""

        return listOf("$leftExample | $rightExample")
    }
}

infix fun  ArgumentType.or(right: ArgumentType) = EitherArg(this, right)




© 2015 - 2024 Weber Informatics LLC | Privacy Policy