Skip to content

Allow ArgType.Choice for Enums to limit list of values #96

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion core/commonMain/src/ArgParser.kt
Original file line number Diff line number Diff line change
Expand Up @@ -531,7 +531,7 @@ open class ArgParser(

protected fun parse(args: List<String>): ArgParserResult {
check(parsingState == null) { "Parsing of command line options can be called only once." }

// Add help option.
val helpDescriptor = if (useDefaultHelpShortName) OptionDescriptor<Boolean, Boolean>(
optionFullFormPrefix,
Expand Down
7 changes: 4 additions & 3 deletions core/commonMain/src/ArgType.kt
Original file line number Diff line number Diff line change
Expand Up @@ -75,14 +75,15 @@ abstract class ArgType<T : Any>(val hasParameter: kotlin.Boolean) {
* Helper for arguments that have limited set of possible values represented as enumeration constants.
*/
inline fun <reified T : Enum<T>> Choice(
choices: List<T> = enumValues<T>().toList(),
noinline toVariant: ((kotlin.String) -> T)? = null,
noinline toString: (T) -> kotlin.String = { it.toString().lowercase() }
): Choice<T> {
return Choice(
enumValues<T>().toList(),
choices,
toVariant ?: {
enumValues<T>().find { e -> toString(e).equals(it, ignoreCase = true) }
?: throw IllegalArgumentException("No enum constant $it")
choices.find { e -> toString(e).equals(it, ignoreCase = true) }
?: throw IllegalArgumentException("Not a valid enum constant choice $it")
},
toString
)
Expand Down