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

Better support for enum types #84

Merged
merged 2 commits into from
Aug 30, 2019
Merged
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 .travis.yml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
language: java

jdk:
- oraclejdk8
- openjdk8
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If this is a problem, I'll revert this, but it fixed the travis build (see https://travis-ci.community/t/install-of-oracle-jdk-8-failing/3038/3)

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for fixing this!


script: ./gradlew :clikt:check --info --stacktrace --console=plain --max-workers=1 --no-daemon -Dkotlin.compiler.execution.strategy="in-process" -Dkotlin.colors.enabled=false

Expand Down
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
## [Unreleased]
### Changed
- There are now several ways of [preventing @-file expansion](https://ajalt.github.io/clikt/arguments/#preventing-file-expansion)
- added `enum<MyEnum>()` type for parameter values to simplify enum handling

## [2.1.0] - 2019-05-23
### Added
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package com.github.ajalt.clikt.parameters.types

import com.github.ajalt.clikt.completion.CompletionCandidates
import com.github.ajalt.clikt.core.BadParameterValue
import com.github.ajalt.clikt.parameters.arguments.RawArgument
import com.github.ajalt.clikt.parameters.arguments.convert
import com.github.ajalt.clikt.parameters.options.RawOption
import com.github.ajalt.clikt.parameters.options.convert

// this function needs to be accessible, because `enum()` needs to be inlined for the reified type.
// see also https://stackoverflow.com/a/41905907
@PublishedApi
internal fun <T> completions(values: Array<T>) =
CompletionCandidates.Fixed(values.map { it.toString() }.toSet())

// this function needs to be accessible, because `enum()` needs to be inlined for the reified type.
// see also https://stackoverflow.com/a/41905907
@PublishedApi
internal inline fun <reified T : Enum<T>> valueToEnum(value: String): T {
return try {
enumValueOf(value.toUpperCase())
} catch (ex: IllegalArgumentException) {
// workaround to avoid T::class.simpleName which would require kotlin-reflections.jar
throw BadParameterValue("Unknown enum constant ${T::class.java.simpleName}.$value")
}
}

inline fun <reified T : Enum<T>> RawArgument.enum() =
convert<T>(completionCandidates = completions<T>(enumValues())) { valueToEnum(it) }

inline fun <reified T : Enum<T>> RawOption.enum() =
convert<T>(completionCandidates = completions<T>(enumValues())) { valueToEnum(it) }

Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
package com.github.ajalt.clikt.parameters.types

import com.github.ajalt.clikt.core.BadParameterValue
import com.github.ajalt.clikt.parameters.arguments.argument
import com.github.ajalt.clikt.parameters.arguments.multiple
import com.github.ajalt.clikt.parameters.arguments.optional
import com.github.ajalt.clikt.parameters.options.default
import com.github.ajalt.clikt.parameters.options.option
import com.github.ajalt.clikt.testing.TestCommand
import io.kotlintest.data.forall
import io.kotlintest.shouldBe
import io.kotlintest.shouldThrow
import io.kotlintest.tables.row
import org.junit.Test

@Suppress("unused")
class EnumTest {
enum class TestEnum { A, B }

@Test
fun `enum option`() = forall(
row("", null),
row("--xx A", TestEnum.A),
row("--xx=A", TestEnum.A),
row("-xB", TestEnum.B)) { argv, expected ->
class C : TestCommand() {
val x by option("-x", "--xx").enum<TestEnum>()
override fun run_() {
x shouldBe expected
}
}

C().parse(argv)
}

@Test
fun `enum option error`() {
class C : TestCommand() {
val foo by option().enum<TestEnum>()
}

shouldThrow<BadParameterValue> { C().parse("--foo bar") }
.message shouldBe "Invalid value for \"--foo\": Unknown enum constant TestEnum.bar"
}

@Test
fun `enum option with default`() = forall(
row("", TestEnum.B),
row("--xx A", TestEnum.A),
row("--xx=A", TestEnum.A),
row("-xA", TestEnum.A)) { argv, expected ->
class C : TestCommand() {
val x by option("-x", "--xx").enum<TestEnum>().default(TestEnum.B)
override fun run_() {
x shouldBe expected
}
}
C().parse(argv)
}

@Test
fun `enum argument`() = forall(
row("", null, emptyList()),
row("A", TestEnum.A, emptyList()),
row("A A B", TestEnum.A, listOf(TestEnum.A, TestEnum.B))) { argv, ex, ey ->
class C : TestCommand() {
val x by argument().enum<TestEnum>().optional()
val y by argument().enum<TestEnum>().multiple()
override fun run_() {
x shouldBe ex
y shouldBe ey
}
}

C().parse(argv)
}
}
8 changes: 4 additions & 4 deletions docs/parameters.md
Original file line number Diff line number Diff line change
Expand Up @@ -95,16 +95,15 @@ arguments.
val opt: String? by option().choice("A", "B")
```

To create an argument that requires the user to choose from the values
of an enum:
You can convert the values on the fly by using a map:

```kotlin
enum class Color { RED, GREEN }
val color: Color by argument().choice("RED" to Color.RED, "GREEN" to Color.GREEN)
val color: Int by argument().choice("RED" to 1, "GREEN" to 2)
```

* `File`: [`option().file()` and `argument().file()`][file]
* `Path`: [`option().path()` and `argument().path()`][path]
* `Enum`: [`option().enum<MyEnum>()` and `argument().enum<MyEnum>()`][enum]

These conversion functions take extra parameters that allow you to
require that values are file paths that have certain attributes, such
Expand Down Expand Up @@ -226,5 +225,6 @@ Error: --bigger-number must be bigger than --number
[choice]: api/clikt/com.github.ajalt.clikt.parameters.types/choice.md
[file]: api/clikt/com.github.ajalt.clikt.parameters.types/file.md
[path]: api/clikt/com.github.ajalt.clikt.parameters.types/path.md
[enum]: api/clikt/com.github.ajalt.clikt.parameters.types/enum.md
[convert]: api/clikt/com.github.ajalt.clikt.parameters.options/convert.md
[validate]: api/clikt/com.github.ajalt.clikt.parameters.options/validate.md