Skip to content

Extend the optional delegate to accept a list of hardcoded acceptable values #78

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 3 commits into
base: master
Choose a base branch
from
Open
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
40 changes: 40 additions & 0 deletions src/main/kotlin/com/xenomachina/argparser/ArgParser.kt
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,46 @@ class ArgParser(
return delegate
}

/**
* Creates a Delegate for an option with a list of hardcoded acceptable values
* @param names names of options, with leading "-" or "--"
* @param errorName name to use when talking about this option in error messages, or null to base it upon the
* option names
* @param help the help text for this option
* @param values the valid values the argument can have
* @param transform transforms the value after parsing
*/
fun <T> option(
vararg names: String,
help: String,
errorName: String? = null,
values: List<String>,
transform: String.() -> T): Delegate<T> {

val nonNullArgName = optionNameToArgName(selectRepresentativeOptionName(names))

return option(
*names,
errorName = errorName,
argNames = listOf(nonNullArgName),
help = help
) {
if (!values.contains(arguments.first()))
throw SystemExitException("Invalid option '${arguments.first()}', valid options are: $values", -1)

transform(arguments.first())
}
}

/**
* Creates a Delegate for an optional with hardcoded acceptable values, which returns the argument's value
*/
fun option(
vararg names: String,
errorName: String? = null,
values: List<String>,
help: String): Delegate<String> = option(*names, errorName = errorName, values = values, help = help) { this }

/**
* Creates a Delegate for a single positional argument which returns the argument's value.
*/
Expand Down