Skip to content
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