-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
d6dd618
commit cc207b1
Showing
1 changed file
with
75 additions
and
0 deletions.
There are no files selected for viewing
75 changes: 75 additions & 0 deletions
75
common/src/main/kotlin/me/blueamethyst/bluecloud/common/terminal/prompts/MemoryPrompt.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,75 @@ | ||
package me.blueamethyst.bluecloud.common.terminal.prompts | ||
|
||
import com.github.ajalt.mordant.terminal.ConversionResult | ||
import com.github.ajalt.mordant.terminal.Prompt | ||
import com.github.ajalt.mordant.terminal.Terminal | ||
import java.util.regex.Matcher | ||
import java.util.regex.Pattern | ||
|
||
class MemoryPrompt( | ||
prompt: String, | ||
terminal: Terminal, | ||
default: Int?, | ||
private val uppercaseDefault: Boolean = true, | ||
showChoices: Boolean = true, | ||
choices: Collection<Int> = emptySet(), | ||
private val choiceStrings: List<String> = listOf("1024M", "4G"), | ||
promptSuffix: String = ": ", | ||
invalidChoiceMessage: String = "Invalid value, choose from " | ||
) : Prompt<Int>( | ||
prompt, | ||
terminal, | ||
default, | ||
false, | ||
showChoices, | ||
false, | ||
choices, | ||
promptSuffix, | ||
invalidChoiceMessage | ||
) { | ||
|
||
val ends = listOf("M", "G") | ||
|
||
override fun convert(input: String): ConversionResult<Int> { | ||
var validEnd: String? = null | ||
|
||
if (input.isBlank()) { | ||
return ConversionResult.Invalid("empty input") | ||
} | ||
|
||
ends.forEach { | ||
if (it.endsWith(it)) { | ||
validEnd = it | ||
} | ||
} | ||
|
||
if (validEnd == null) { | ||
return ConversionResult.Invalid("invalid end") | ||
} | ||
|
||
val split = splitStringAndNumber(input) ?: return ConversionResult.Invalid("invalid") | ||
val final = calculate(split.second, split.first) ?: return ConversionResult.Invalid("invalid") | ||
|
||
return ConversionResult.Valid(final) | ||
} | ||
|
||
private fun calculate(suffix: String, value: Int): Int? { | ||
return when(suffix) { | ||
"M" -> value | ||
"G" -> value * 1024 | ||
else -> null | ||
} | ||
} | ||
|
||
// https://stackoverflow.com/questions/3720012/regular-expression-to-split-string-and-number | ||
private fun splitStringAndNumber(string: String?): Pair<Int, String>? { | ||
val pattern = "(?<Numeric>[0-9]*)(?<Alpha>[a-zA-Z]*)" | ||
|
||
val p: Pattern = Pattern.compile(pattern) | ||
val m: Matcher = p.matcher(string) | ||
if (m.find()) { | ||
return Pair(m.group(1).toInt(), m.group(2).toString()) | ||
} | ||
return null | ||
} | ||
} |