Compare commits
36 Commits
ebd698e611
...
develop
| Author | SHA1 | Date | |
|---|---|---|---|
|
736aa9ffbd
|
|||
|
90502d4ed4
|
|||
|
21769c20c4
|
|||
|
d5a66f6853
|
|||
|
f55869193e
|
|||
|
9ad2d2c5e0
|
|||
|
a5b578a47d
|
|||
|
dbd9d53050
|
|||
|
87e6e65809
|
|||
|
54972c36b6
|
|||
|
f90e960728
|
|||
|
562b9eb522
|
|||
|
ff87ae90f5
|
|||
|
47834c91d8
|
|||
|
fa5fa89bec
|
|||
|
c8e3902661
|
|||
|
7001b00f5f
|
|||
|
f33caa30c0
|
|||
|
6aa6c1b3c8
|
|||
|
2a9f086c9d
|
|||
|
921229aa5b
|
|||
|
ecd255479a
|
|||
|
4e9b358ef8
|
|||
|
8e491751f5
|
|||
|
0a8e51c7ab
|
|||
|
86409e9f72
|
|||
|
6779e28792
|
|||
|
7b9e39f9d0
|
|||
|
0dc064b8cf
|
|||
|
06a2d1bdce
|
|||
|
74a9324660
|
|||
|
5d363e0f43
|
|||
|
f1185886d4
|
|||
|
79629ae68d
|
|||
|
6be1957d82
|
|||
|
757011af85
|
@@ -1,36 +0,0 @@
|
|||||||
on:
|
|
||||||
push:
|
|
||||||
branches:
|
|
||||||
- main
|
|
||||||
|
|
||||||
env:
|
|
||||||
INFENDRO__TOKEN: ${{ secrets.TOKEN }}
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
publish:
|
|
||||||
runs-on: linux
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
|
|
||||||
- uses: actions/cache/restore@v4
|
|
||||||
with:
|
|
||||||
key: gradle
|
|
||||||
path: |
|
|
||||||
~/.gradle/caches/
|
|
||||||
~/.gradle/wrapper/
|
|
||||||
~/.konan/
|
|
||||||
|
|
||||||
- uses: actions/setup-java@v4
|
|
||||||
with:
|
|
||||||
java-version: '24'
|
|
||||||
distribution: 'temurin'
|
|
||||||
|
|
||||||
- run: ./gradlew publish
|
|
||||||
|
|
||||||
- uses: actions/cache/save@v4
|
|
||||||
with:
|
|
||||||
key: gradle
|
|
||||||
path: |
|
|
||||||
~/.gradle/caches/
|
|
||||||
~/.gradle/wrapper/
|
|
||||||
~/.konan/
|
|
||||||
47
.gitea/workflows/publish.yaml
Normal file
47
.gitea/workflows/publish.yaml
Normal file
@@ -0,0 +1,47 @@
|
|||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [ main ]
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
publish:
|
||||||
|
runs-on: linux
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Setup Java
|
||||||
|
uses: actions/setup-java@v4
|
||||||
|
with:
|
||||||
|
java-version: '24'
|
||||||
|
distribution: 'temurin'
|
||||||
|
|
||||||
|
- name: Cache Gradle
|
||||||
|
uses: actions/cache@v4
|
||||||
|
with:
|
||||||
|
key: gradle-${{ hashFiles('**/libs.versions.toml') }}
|
||||||
|
restore-keys: gradle
|
||||||
|
path: |
|
||||||
|
~/.gradle/caches/
|
||||||
|
~/.gradle/wrapper/
|
||||||
|
|
||||||
|
- name: Cache Konan
|
||||||
|
uses: actions/cache@v4
|
||||||
|
with:
|
||||||
|
key: konan-${{ hashFiles('**/libs.versions.toml') }}
|
||||||
|
restore-keys: konan
|
||||||
|
path: |
|
||||||
|
~/.konan/
|
||||||
|
|
||||||
|
- name: Cache Node
|
||||||
|
uses: actions/cache@v4
|
||||||
|
with:
|
||||||
|
key: node-${{ hashFiles('**/libs.versions.toml') }}
|
||||||
|
restore-keys: node
|
||||||
|
path: |
|
||||||
|
~/.gradle/nodejs
|
||||||
|
~/.gradle/yarn
|
||||||
|
|
||||||
|
- name: Publish
|
||||||
|
run: ./gradlew publish
|
||||||
|
env:
|
||||||
|
INFENDRO__TOKEN: ${{ secrets.TOKEN }}
|
||||||
64
README.md
64
README.md
@@ -1,16 +1,6 @@
|
|||||||
# Kotlin CLI
|
# cli.kt
|
||||||
|
|
||||||
This library implements a lightweight framework for implementing terminal applications.
|
`cli.kt` is a Kotlin Multiplatform framework for implementing terminal applications.
|
||||||
|
|
||||||
## Features
|
|
||||||
|
|
||||||
* Declare commands.
|
|
||||||
* Supports both named and wildcard commands.
|
|
||||||
* Declare and parse type-safe arguments.
|
|
||||||
* Multiplatform support
|
|
||||||
* JVM
|
|
||||||
* JavaScript
|
|
||||||
* Native (Linux)
|
|
||||||
|
|
||||||
## Installation
|
## Installation
|
||||||
|
|
||||||
@@ -22,50 +12,48 @@ repositories {
|
|||||||
}
|
}
|
||||||
|
|
||||||
dependencies {
|
dependencies {
|
||||||
implementation("com.infendro:cli:1.3.0")
|
implementation("com.infendro:cli:1.4.1")
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
## Usage
|
## Usage
|
||||||
|
|
||||||
```kotlin
|
```kotlin
|
||||||
import com.infendro.cli.argument.stringOrElse
|
fun main(args: Array<String>) = command("application", description = "example application") {
|
||||||
import com.infendro.cli.argument.stringOrNull
|
|
||||||
import com.infendro.cli.command.cli
|
|
||||||
|
|
||||||
fun main(args: Array<String>) {
|
|
||||||
// declare root command
|
|
||||||
cli {
|
|
||||||
execute {
|
execute {
|
||||||
// execution of root command (e.g., display help)
|
// define execution of command (e.g., display help)
|
||||||
|
help()
|
||||||
}
|
}
|
||||||
|
|
||||||
// declare command "test"
|
// register command "greet"
|
||||||
command("test") {
|
+command("greet", description = "greet someone") {
|
||||||
// declare arguments
|
// declare and register arguments
|
||||||
val greetingArg = stringOrElse("greeting", "Hello")
|
val speakersArg = +argument.string("speakers", description = "the greeters").variable(min = 1)
|
||||||
val nameArg = stringOrNull("name")
|
|
||||||
|
// declare and register options
|
||||||
|
val greetingOpt = +option.string("greeting", "greet", "g", description = "the greeting").orElse("Hello")
|
||||||
|
val nameOpt = +option.string("name", "n", description = "the greetee").orNull()
|
||||||
|
|
||||||
execute {
|
execute {
|
||||||
// retrieve the arguments
|
// retrieve the arguments and options
|
||||||
val greeting by greetingArg
|
val speakers by speakersArg
|
||||||
val name by nameArg
|
val greeting by greetingOpt
|
||||||
|
val name by nameOpt
|
||||||
|
|
||||||
println("$greeting ${name ?: "World"}!")
|
println("${speakers.joinToString()}: $greeting ${name ?: "World"}!")
|
||||||
}
|
}
|
||||||
|
|
||||||
// declare more commands...
|
// register more commands...
|
||||||
}
|
}
|
||||||
|
|
||||||
// declare wildcard command
|
// register fallback command "value"
|
||||||
command { wildcard ->
|
+command.fallback.string("value", description = "execute an arbitrary command") { valueArg ->
|
||||||
execute {
|
execute {
|
||||||
// retrieve the value used for the wildcard command
|
// retrieve the value used for the fallback command
|
||||||
val value by wildcard
|
val value by valueArg
|
||||||
|
|
||||||
println("command $value executed!")
|
println("""command "$value" executed!""")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}.run(args)
|
}.run(*args)
|
||||||
}
|
|
||||||
```
|
```
|
||||||
|
|||||||
@@ -1,8 +1,11 @@
|
|||||||
|
@file:OptIn(ExperimentalWasmDsl::class)
|
||||||
|
|
||||||
import com.infendro.plugin.infendro
|
import com.infendro.plugin.infendro
|
||||||
import com.infendro.plugin.token
|
import com.infendro.plugin.token
|
||||||
|
import org.jetbrains.kotlin.gradle.ExperimentalWasmDsl
|
||||||
|
|
||||||
group = "com.infendro"
|
group = "com.infendro"
|
||||||
version = "1.3.0"
|
version = "1.4.1"
|
||||||
|
|
||||||
plugins {
|
plugins {
|
||||||
alias(libs.plugins.infendro)
|
alias(libs.plugins.infendro)
|
||||||
@@ -12,10 +15,14 @@ plugins {
|
|||||||
|
|
||||||
kotlin {
|
kotlin {
|
||||||
jvm()
|
jvm()
|
||||||
js {
|
|
||||||
nodejs()
|
|
||||||
}
|
|
||||||
linuxX64()
|
linuxX64()
|
||||||
|
linuxArm64()
|
||||||
|
mingwX64()
|
||||||
|
macosX64()
|
||||||
|
macosArm64()
|
||||||
|
js { nodejs() }
|
||||||
|
wasmJs { nodejs() }
|
||||||
|
wasmWasi { nodejs() }
|
||||||
|
|
||||||
repositories {
|
repositories {
|
||||||
mavenCentral()
|
mavenCentral()
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[versions]
|
[versions]
|
||||||
infendro = "1.0.0"
|
infendro = "1.1.0"
|
||||||
kotlin = "2.2.21"
|
kotlin = "2.3.0"
|
||||||
|
|
||||||
[plugins]
|
[plugins]
|
||||||
infendro = { id = "com.infendro.plugin", version.ref = "infendro" }
|
infendro = { id = "com.infendro.plugin", version.ref = "infendro" }
|
||||||
|
|||||||
4
src/commonMain/kotlin/com/infendro/cli/Dsl.kt
Normal file
4
src/commonMain/kotlin/com/infendro/cli/Dsl.kt
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
package com.infendro.cli
|
||||||
|
|
||||||
|
@DslMarker
|
||||||
|
internal annotation class Dsl
|
||||||
@@ -1,51 +1,70 @@
|
|||||||
package com.infendro.cli.argument
|
package com.infendro.cli.argument
|
||||||
|
|
||||||
sealed class Argument<T> {
|
import com.infendro.cli.exception.InvalidArgumentName
|
||||||
abstract val name: String
|
import com.infendro.cli.exception.InvalidRange
|
||||||
abstract val min: Int
|
import com.infendro.cli.parser.Parser
|
||||||
abstract val max: Int
|
import com.infendro.cli.util.Regex.ARGUMENT
|
||||||
|
|
||||||
abstract class Single<T> : Argument<T>() {
|
sealed class Argument<T : Any>(
|
||||||
final override val min: Int
|
val parser: Parser<T>,
|
||||||
get() = 1
|
val name: String,
|
||||||
final override val max: Int
|
val description: String?,
|
||||||
get() = 1
|
val min: Int,
|
||||||
|
val max: Int?,
|
||||||
abstract val parser: Parser<T>
|
) {
|
||||||
}
|
init {
|
||||||
|
when {
|
||||||
abstract class SingleOrElse<T> : Argument<T>() {
|
!name.matches(ARGUMENT) -> throw InvalidArgumentName(name)
|
||||||
abstract val other: T
|
min !in 0..count || max == 0 -> throw InvalidRange()
|
||||||
|
|
||||||
final override val min: Int
|
|
||||||
get() = 0
|
|
||||||
final override val max: Int
|
|
||||||
get() = 1
|
|
||||||
|
|
||||||
abstract val parser: Parser<T>
|
|
||||||
}
|
|
||||||
|
|
||||||
abstract class SingleOrNull<T> : Argument<T>() {
|
|
||||||
final override val min: Int
|
|
||||||
get() = 0
|
|
||||||
final override val max: Int
|
|
||||||
get() = 1
|
|
||||||
|
|
||||||
abstract val parser: Parser<T>
|
|
||||||
}
|
|
||||||
|
|
||||||
abstract class Multiple<T> : Argument<List<T>>() {
|
|
||||||
override val min: Int
|
|
||||||
get() = 0
|
|
||||||
override val max: Int
|
|
||||||
get() = Int.MAX_VALUE
|
|
||||||
|
|
||||||
abstract val parser: Parser<T>
|
|
||||||
}
|
|
||||||
|
|
||||||
interface Parser<T> {
|
|
||||||
fun parse(
|
|
||||||
text: String?,
|
|
||||||
): T
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
val required: Boolean
|
||||||
|
get() = min > 0
|
||||||
|
val optional: Boolean
|
||||||
|
get() = !required
|
||||||
|
|
||||||
|
val bounded: Boolean
|
||||||
|
get() = max != null
|
||||||
|
val unbounded: Boolean
|
||||||
|
get() = !bounded
|
||||||
|
|
||||||
|
val count: Int
|
||||||
|
get() = max ?: Int.MAX_VALUE
|
||||||
|
|
||||||
|
class Required<T : Any>(
|
||||||
|
parser: Parser<T>,
|
||||||
|
name: String,
|
||||||
|
description: String?,
|
||||||
|
) : Argument<T>(parser, name, description, min = 1, max = 1) {
|
||||||
|
fun orElse(other: T) =
|
||||||
|
OrElse(parser, name, description, other)
|
||||||
|
|
||||||
|
fun orNull() =
|
||||||
|
OrNull(parser, name, description)
|
||||||
|
|
||||||
|
fun variable(min: Int = 0, max: Int? = null) =
|
||||||
|
Variable(parser, name, description, min, max)
|
||||||
|
}
|
||||||
|
|
||||||
|
class OrElse<T : Any>(
|
||||||
|
parser: Parser<T>,
|
||||||
|
name: String,
|
||||||
|
description: String?,
|
||||||
|
val other: T,
|
||||||
|
) : Argument<T>(parser, name, description, min = 0, max = 1)
|
||||||
|
|
||||||
|
class OrNull<T : Any>(
|
||||||
|
parser: Parser<T>,
|
||||||
|
name: String,
|
||||||
|
description: String?,
|
||||||
|
) : Argument<T>(parser, name, description, min = 0, max = 1)
|
||||||
|
|
||||||
|
class Variable<T : Any>(
|
||||||
|
parser: Parser<T>,
|
||||||
|
name: String,
|
||||||
|
description: String?,
|
||||||
|
min: Int,
|
||||||
|
max: Int?,
|
||||||
|
) : Argument<T>(parser, name, description, min, max)
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,31 @@
|
|||||||
|
package com.infendro.cli.argument
|
||||||
|
|
||||||
|
import com.infendro.cli.parser.*
|
||||||
|
|
||||||
|
object ArgumentFactory {
|
||||||
|
fun string(name: String, description: String? = null) =
|
||||||
|
argument(StringParser, name, description)
|
||||||
|
|
||||||
|
fun int(name: String, description: String? = null) =
|
||||||
|
argument(IntParser, name, description)
|
||||||
|
|
||||||
|
fun long(name: String, description: String? = null) =
|
||||||
|
argument(LongParser, name, description)
|
||||||
|
|
||||||
|
fun float(name: String, description: String? = null) =
|
||||||
|
argument(FloatParser, name, description)
|
||||||
|
|
||||||
|
fun double(name: String, description: String? = null) =
|
||||||
|
argument(DoubleParser, name, description)
|
||||||
|
|
||||||
|
fun boolean(name: String, description: String? = null) =
|
||||||
|
argument(BooleanParser, name, description)
|
||||||
|
|
||||||
|
inline fun <reified T : Enum<T>> enum(name: String, description: String? = null) =
|
||||||
|
argument(enumParser<T>(), name, description)
|
||||||
|
}
|
||||||
|
|
||||||
|
val argument = ArgumentFactory
|
||||||
|
|
||||||
|
fun <T : Any> argument(parser: Parser<T>, name: String, description: String? = null) =
|
||||||
|
Argument.Required(parser, name, description)
|
||||||
@@ -1,84 +0,0 @@
|
|||||||
package com.infendro.cli.argument
|
|
||||||
|
|
||||||
import com.infendro.cli.command.Command
|
|
||||||
|
|
||||||
private object BooleanParser : Argument.Parser<Boolean> {
|
|
||||||
override fun parse(
|
|
||||||
text: String?,
|
|
||||||
): Boolean {
|
|
||||||
return text == null || text.toBooleanStrict()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
class BooleanArgument(
|
|
||||||
override val name: String,
|
|
||||||
) : Argument.Single<Boolean>() {
|
|
||||||
override val parser: Parser<Boolean>
|
|
||||||
get() = BooleanParser
|
|
||||||
}
|
|
||||||
|
|
||||||
fun boolean(
|
|
||||||
name: String,
|
|
||||||
) = BooleanArgument(name)
|
|
||||||
|
|
||||||
fun Command.Builder.boolean(
|
|
||||||
name: String,
|
|
||||||
) = BooleanArgument(name)
|
|
||||||
.also { argument(it) }
|
|
||||||
|
|
||||||
class BooleanOrElseArgument(
|
|
||||||
override val name: String,
|
|
||||||
override val other: Boolean,
|
|
||||||
) : Argument.SingleOrElse<Boolean>() {
|
|
||||||
override val parser: Parser<Boolean>
|
|
||||||
get() = BooleanParser
|
|
||||||
}
|
|
||||||
|
|
||||||
fun booleanOrElse(
|
|
||||||
name: String,
|
|
||||||
other: Boolean,
|
|
||||||
) = BooleanOrElseArgument(name, other)
|
|
||||||
|
|
||||||
fun Command.Builder.booleanOrElse(
|
|
||||||
name: String,
|
|
||||||
other: Boolean,
|
|
||||||
) = BooleanOrElseArgument(name, other)
|
|
||||||
.also { argument(it) }
|
|
||||||
|
|
||||||
class BooleanOrNullArgument(
|
|
||||||
override val name: String,
|
|
||||||
) : Argument.SingleOrNull<Boolean>() {
|
|
||||||
override val parser: Parser<Boolean>
|
|
||||||
get() = BooleanParser
|
|
||||||
}
|
|
||||||
|
|
||||||
fun booleanOrNull(
|
|
||||||
name: String,
|
|
||||||
) = BooleanOrNullArgument(name)
|
|
||||||
|
|
||||||
fun Command.Builder.booleanOrNull(
|
|
||||||
name: String,
|
|
||||||
) = BooleanOrNullArgument(name)
|
|
||||||
.also { argument(it) }
|
|
||||||
|
|
||||||
class BooleansArgument(
|
|
||||||
override val name: String,
|
|
||||||
override val min: Int = 0,
|
|
||||||
override val max: Int = Int.MAX_VALUE,
|
|
||||||
) : Argument.Multiple<Boolean>() {
|
|
||||||
override val parser: Parser<Boolean>
|
|
||||||
get() = BooleanParser
|
|
||||||
}
|
|
||||||
|
|
||||||
fun booleans(
|
|
||||||
name: String,
|
|
||||||
min: Int = 0,
|
|
||||||
max: Int = Int.MAX_VALUE,
|
|
||||||
) = BooleansArgument(name, min, max)
|
|
||||||
|
|
||||||
fun Command.Builder.booleans(
|
|
||||||
name: String,
|
|
||||||
min: Int = 0,
|
|
||||||
max: Int = Int.MAX_VALUE,
|
|
||||||
) = BooleansArgument(name, min, max)
|
|
||||||
.also { argument(it) }
|
|
||||||
@@ -1,84 +0,0 @@
|
|||||||
package com.infendro.cli.argument
|
|
||||||
|
|
||||||
import com.infendro.cli.command.Command
|
|
||||||
|
|
||||||
private object IntParser : Argument.Parser<Int> {
|
|
||||||
override fun parse(
|
|
||||||
text: String?,
|
|
||||||
): Int {
|
|
||||||
return text!!.toInt()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
class IntArgument(
|
|
||||||
override val name: String,
|
|
||||||
) : Argument.Single<Int>() {
|
|
||||||
override val parser: Parser<Int>
|
|
||||||
get() = IntParser
|
|
||||||
}
|
|
||||||
|
|
||||||
fun int(
|
|
||||||
name: String,
|
|
||||||
) = IntArgument(name)
|
|
||||||
|
|
||||||
fun Command.Builder.int(
|
|
||||||
name: String,
|
|
||||||
) = IntArgument(name)
|
|
||||||
.also { argument(it) }
|
|
||||||
|
|
||||||
class IntOrElseArgument(
|
|
||||||
override val name: String,
|
|
||||||
override val other: Int,
|
|
||||||
) : Argument.SingleOrElse<Int>() {
|
|
||||||
override val parser: Parser<Int>
|
|
||||||
get() = IntParser
|
|
||||||
}
|
|
||||||
|
|
||||||
fun intOrElse(
|
|
||||||
name: String,
|
|
||||||
other: Int,
|
|
||||||
) = IntOrElseArgument(name, other)
|
|
||||||
|
|
||||||
fun Command.Builder.intOrElse(
|
|
||||||
name: String,
|
|
||||||
other: Int,
|
|
||||||
) = IntOrElseArgument(name, other)
|
|
||||||
.also { argument(it) }
|
|
||||||
|
|
||||||
class IntOrNullArgument(
|
|
||||||
override val name: String,
|
|
||||||
) : Argument.SingleOrNull<Int>() {
|
|
||||||
override val parser: Parser<Int>
|
|
||||||
get() = IntParser
|
|
||||||
}
|
|
||||||
|
|
||||||
fun intOrNull(
|
|
||||||
name: String,
|
|
||||||
) = IntOrNullArgument(name)
|
|
||||||
|
|
||||||
fun Command.Builder.intOrNull(
|
|
||||||
name: String,
|
|
||||||
) = IntOrNullArgument(name)
|
|
||||||
.also { argument(it) }
|
|
||||||
|
|
||||||
class IntsArgument(
|
|
||||||
override val name: String,
|
|
||||||
override val min: Int = 0,
|
|
||||||
override val max: Int = Int.MAX_VALUE,
|
|
||||||
) : Argument.Multiple<Int>() {
|
|
||||||
override val parser: Parser<Int>
|
|
||||||
get() = IntParser
|
|
||||||
}
|
|
||||||
|
|
||||||
fun ints(
|
|
||||||
name: String,
|
|
||||||
min: Int = 0,
|
|
||||||
max: Int = Int.MAX_VALUE,
|
|
||||||
) = IntsArgument(name, min, max)
|
|
||||||
|
|
||||||
fun Command.Builder.ints(
|
|
||||||
name: String,
|
|
||||||
min: Int = 0,
|
|
||||||
max: Int = Int.MAX_VALUE,
|
|
||||||
) = IntsArgument(name, min, max)
|
|
||||||
.also { argument(it) }
|
|
||||||
@@ -1,84 +0,0 @@
|
|||||||
package com.infendro.cli.argument
|
|
||||||
|
|
||||||
import com.infendro.cli.command.Command
|
|
||||||
|
|
||||||
private object StringParser : Argument.Parser<String> {
|
|
||||||
override fun parse(
|
|
||||||
text: String?,
|
|
||||||
): String {
|
|
||||||
return text!!
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
class StringArgument(
|
|
||||||
override val name: String,
|
|
||||||
) : Argument.Single<String>() {
|
|
||||||
override val parser: Parser<String>
|
|
||||||
get() = StringParser
|
|
||||||
}
|
|
||||||
|
|
||||||
fun string(
|
|
||||||
name: String,
|
|
||||||
) = StringArgument(name)
|
|
||||||
|
|
||||||
fun Command.Builder.string(
|
|
||||||
name: String,
|
|
||||||
) = StringArgument(name)
|
|
||||||
.also { argument(it) }
|
|
||||||
|
|
||||||
class StringOrElseArgument(
|
|
||||||
override val name: String,
|
|
||||||
override val other: String,
|
|
||||||
) : Argument.SingleOrElse<String>() {
|
|
||||||
override val parser: Parser<String>
|
|
||||||
get() = StringParser
|
|
||||||
}
|
|
||||||
|
|
||||||
fun stringOrElse(
|
|
||||||
name: String,
|
|
||||||
other: String,
|
|
||||||
) = StringOrElseArgument(name, other)
|
|
||||||
|
|
||||||
fun Command.Builder.stringOrElse(
|
|
||||||
name: String,
|
|
||||||
other: String,
|
|
||||||
) = StringOrElseArgument(name, other)
|
|
||||||
.also { argument(it) }
|
|
||||||
|
|
||||||
class StringOrNullArgument(
|
|
||||||
override val name: String,
|
|
||||||
) : Argument.SingleOrNull<String>() {
|
|
||||||
override val parser: Parser<String>
|
|
||||||
get() = StringParser
|
|
||||||
}
|
|
||||||
|
|
||||||
fun stringOrNull(
|
|
||||||
name: String,
|
|
||||||
) = StringOrNullArgument(name)
|
|
||||||
|
|
||||||
fun Command.Builder.stringOrNull(
|
|
||||||
name: String,
|
|
||||||
) = StringOrNullArgument(name)
|
|
||||||
.also { argument(it) }
|
|
||||||
|
|
||||||
class StringsArgument(
|
|
||||||
override val name: String,
|
|
||||||
override val min: Int = 0,
|
|
||||||
override val max: Int = Int.MAX_VALUE,
|
|
||||||
) : Argument.Multiple<String>() {
|
|
||||||
override val parser: Parser<String>
|
|
||||||
get() = StringParser
|
|
||||||
}
|
|
||||||
|
|
||||||
fun strings(
|
|
||||||
name: String,
|
|
||||||
min: Int = 0,
|
|
||||||
max: Int = Int.MAX_VALUE,
|
|
||||||
) = StringsArgument(name, min, max)
|
|
||||||
|
|
||||||
fun Command.Builder.strings(
|
|
||||||
name: String,
|
|
||||||
min: Int = 0,
|
|
||||||
max: Int = Int.MAX_VALUE,
|
|
||||||
) = StringsArgument(name, min, max)
|
|
||||||
.also { argument(it) }
|
|
||||||
@@ -1,178 +1,184 @@
|
|||||||
package com.infendro.cli.command
|
package com.infendro.cli.command
|
||||||
|
|
||||||
import com.infendro.cli.command.Execution
|
import com.infendro.cli.Dsl
|
||||||
import com.infendro.cli.argument.Argument
|
import com.infendro.cli.argument.Argument
|
||||||
import com.infendro.cli.exception.build.*
|
import com.infendro.cli.command.context.Context
|
||||||
import com.infendro.cli.exception.run.ArgumentCountException
|
import com.infendro.cli.command.context.ContextParser
|
||||||
import com.infendro.cli.exception.run.InvalidArgumentException
|
import com.infendro.cli.command.help.DefaultHelpRenderer
|
||||||
import com.infendro.cli.exception.run.UnknownArgumentException
|
import com.infendro.cli.command.help.HelpRenderer
|
||||||
import com.infendro.cli.exception.run.UnknownCommandException
|
import com.infendro.cli.exception.*
|
||||||
import com.infendro.cli.util.Regex.ARGUMENT
|
import com.infendro.cli.option.Option
|
||||||
import com.infendro.cli.util.Regex.ARGUMENT_NAME
|
import com.infendro.cli.parser.Parser
|
||||||
import com.infendro.cli.util.Regex.COMMAND_NAME
|
import com.infendro.cli.util.Regex
|
||||||
|
|
||||||
class Command private constructor(
|
sealed class Command private constructor(
|
||||||
private val index: Int,
|
val name: String,
|
||||||
private val name: String?,
|
val description: String?,
|
||||||
private val commands: List<Command>,
|
val commands: List<Command>,
|
||||||
private val arguments: List<Argument<*>>,
|
val arguments: List<Argument<*>>,
|
||||||
private val block: Execution.() -> Unit,
|
val options: List<Option<*>>,
|
||||||
|
internal val execute: Context.() -> Unit,
|
||||||
|
internal val renderer: HelpRenderer,
|
||||||
) {
|
) {
|
||||||
private val nextIndex: Int
|
init {
|
||||||
get() = index + 1
|
if (!name.matches(Regex.COMMAND)) throw InvalidCommandName(name)
|
||||||
|
}
|
||||||
|
|
||||||
fun run(
|
fun run(vararg args: String) {
|
||||||
args: Array<String>,
|
when (val result = ContextParser(this, arrayOf(*args)).parse()) {
|
||||||
|
is ContextParser.Result.Success -> result.context.execute()
|
||||||
|
is ContextParser.Result.Help -> {
|
||||||
|
val command = result.path.last()
|
||||||
|
val help = command.renderer.render(result.path)
|
||||||
|
if (help != null) print(help)
|
||||||
|
}
|
||||||
|
is ContextParser.Result.Failure -> {
|
||||||
|
println("error: ${result.error.message}")
|
||||||
|
val command = result.path.last()
|
||||||
|
val help = command.renderer.render(result.path)
|
||||||
|
if (help != null) print("\n$help")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class Named(
|
||||||
|
name: String,
|
||||||
|
description: String?,
|
||||||
|
commands: List<Command>,
|
||||||
|
arguments: List<Argument<*>>,
|
||||||
|
options: List<Option<*>>,
|
||||||
|
execute: Context.() -> Unit,
|
||||||
|
renderer: HelpRenderer,
|
||||||
|
) : Command(name, description, commands, arguments, options, execute, renderer) {
|
||||||
|
class Builder(
|
||||||
|
name: String,
|
||||||
|
description: String?,
|
||||||
|
) : Command.Builder<Named>(name, description) {
|
||||||
|
override fun create() =
|
||||||
|
Named(name, description, commands, arguments, options, execute, renderer)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class Fallback<T : Any>(
|
||||||
|
val key: Key<T>,
|
||||||
|
val parser: Parser<T>,
|
||||||
|
name: String,
|
||||||
|
description: String?,
|
||||||
|
commands: List<Command>,
|
||||||
|
arguments: List<Argument<*>>,
|
||||||
|
options: List<Option<*>>,
|
||||||
|
execute: Context.() -> Unit,
|
||||||
|
renderer: HelpRenderer,
|
||||||
|
) : Command(name, description, commands, arguments, options, execute, renderer) {
|
||||||
|
class Builder<T : Any>(
|
||||||
|
val parser: Parser<T>,
|
||||||
|
name: String,
|
||||||
|
description: String?,
|
||||||
|
) : Command.Builder<Fallback<T>>(name, description) {
|
||||||
|
internal val key = Key<T>()
|
||||||
|
|
||||||
|
override fun create() =
|
||||||
|
Fallback(key, parser, name, description, commands, arguments, options, execute, renderer)
|
||||||
|
}
|
||||||
|
|
||||||
|
class Key<T>
|
||||||
|
}
|
||||||
|
|
||||||
|
@Dsl
|
||||||
|
sealed class Builder<COMMAND : Command>(
|
||||||
|
protected val name: String,
|
||||||
|
protected val description: String?,
|
||||||
) {
|
) {
|
||||||
val index = args
|
protected val commands = mutableListOf<Command>()
|
||||||
.withIndex()
|
protected val arguments = mutableListOf<Argument<*>>()
|
||||||
.find { (_, value) -> value.startsWith("--") }
|
protected val options = mutableListOf<Option<*>>()
|
||||||
?.index ?: args.size
|
private var _execute: (Context.() -> Unit)? = null
|
||||||
|
private var _renderer: HelpRenderer? = null
|
||||||
|
|
||||||
val cmd = args.slice(0..<index)
|
protected val execute: Context.() -> Unit
|
||||||
val arg = args.slice(index..<args.size)
|
get() = _execute!!
|
||||||
|
protected val renderer: HelpRenderer
|
||||||
|
get() = _renderer!!
|
||||||
|
|
||||||
try {
|
fun register(command: Command) {
|
||||||
run(cmd, arg)
|
validateCommand(command)
|
||||||
} catch (e: UnknownCommandException) {
|
commands += command
|
||||||
println("""unknown command "${e.command}"""")
|
}
|
||||||
} catch (e: InvalidArgumentException) {
|
|
||||||
println("""invalid argument "${e.argument}"""")
|
fun register(vararg commands: Command) = commands.forEach(::register)
|
||||||
} catch (e: UnknownArgumentException) {
|
operator fun <T : Command> T.unaryPlus() = also(::register)
|
||||||
println("""unknown argument "${e.argument}"""")
|
|
||||||
} catch (e: ArgumentCountException) {
|
fun register(argument: Argument<*>) {
|
||||||
|
validateArgument(argument)
|
||||||
|
arguments += argument
|
||||||
|
}
|
||||||
|
|
||||||
|
fun register(vararg arguments: Argument<*>) = arguments.forEach(::register)
|
||||||
|
operator fun <T : Argument<*>> T.unaryPlus() = also(::register)
|
||||||
|
|
||||||
|
fun register(option: Option<*>) {
|
||||||
|
validateOption(option)
|
||||||
|
options += option
|
||||||
|
}
|
||||||
|
|
||||||
|
fun register(vararg options: Option<*>) = options.forEach(::register)
|
||||||
|
operator fun <T : Option<*>> T.unaryPlus() = also(::register)
|
||||||
|
|
||||||
|
fun execute(block: Context.() -> Unit) {
|
||||||
|
validateExecute()
|
||||||
|
_execute = block
|
||||||
|
}
|
||||||
|
|
||||||
|
fun renderer(renderer: HelpRenderer) {
|
||||||
|
validateRenderer()
|
||||||
|
_renderer = renderer
|
||||||
|
}
|
||||||
|
|
||||||
|
internal abstract fun create(): COMMAND
|
||||||
|
|
||||||
|
internal fun build(): Command {
|
||||||
|
if (_execute == null) _execute = {}
|
||||||
|
if (_renderer == null) _renderer = DefaultHelpRenderer
|
||||||
|
|
||||||
|
validate()
|
||||||
|
return create()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun validateCommand(command: Command) {
|
||||||
|
if (commands.isNotEmpty()) {
|
||||||
|
val last = commands.last()
|
||||||
|
if (last is Fallback<*>) throw InvalidCommandOrder()
|
||||||
|
}
|
||||||
|
if (commands.any { it.name == command.name }) throw DuplicateCommand(command)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun validateArgument(argument: Argument<*>) {
|
||||||
|
if (arguments.isNotEmpty()) {
|
||||||
|
val last = arguments.last()
|
||||||
when {
|
when {
|
||||||
e.min == e.max -> println("""argument "${e.argument}" must appear ${e.min} times""")
|
last.unbounded -> throw InvalidArgumentOrder()
|
||||||
e.max == Int.MAX_VALUE -> println("""argument "${e.argument}" must appear at least ${e.min} times""")
|
argument.required && last.optional -> throw InvalidArgumentOrder()
|
||||||
else -> println("""argument "${e.argument}" must appear between ${e.min} and ${e.max} times""")
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if (arguments.any { it.name == argument.name }) throw DuplicateArgument(argument)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun run(
|
private fun validateOption(option: Option<*>) {
|
||||||
cmd: List<String>,
|
for (name in option.names) {
|
||||||
arg: List<String>,
|
if (options.any { name in it.names }) throw DuplicateOption(option)
|
||||||
) {
|
|
||||||
if (index == cmd.lastIndex) {
|
|
||||||
Execution(
|
|
||||||
parseCmd(cmd),
|
|
||||||
parseArg(arg),
|
|
||||||
).block()
|
|
||||||
} else {
|
|
||||||
val command = commands.firstOrNull() { it.name == cmd[nextIndex] || it.name == null }
|
|
||||||
?: throw UnknownCommandException(cmd[nextIndex])
|
|
||||||
command.run(cmd, arg)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun parseCmd(
|
private fun validateExecute() {
|
||||||
cmd: List<String>,
|
if (_execute != null) throw DuplicateExecute()
|
||||||
): List<Execution.Cmd> {
|
|
||||||
return cmd.map { Execution.Cmd(it) }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun parseArg(
|
private fun validateRenderer() {
|
||||||
arg: List<String>,
|
if (_renderer != null) throw DuplicateRenderer()
|
||||||
): List<Execution.Arg> {
|
|
||||||
val result = mutableListOf<Execution.Arg>()
|
|
||||||
|
|
||||||
for (argument in arg) {
|
|
||||||
val match = ARGUMENT.matchEntire(argument)
|
|
||||||
?: throw InvalidArgumentException(argument)
|
|
||||||
|
|
||||||
val name = match.groups["name"]!!.value
|
|
||||||
val value = match.groups["value"]?.value
|
|
||||||
|
|
||||||
if (arguments.none { it.name == name })
|
|
||||||
throw UnknownArgumentException(name)
|
|
||||||
|
|
||||||
result += Execution.Arg(name, value)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
arguments
|
private fun validate() {
|
||||||
.forEach { argument ->
|
if (commands.any { it is Fallback<*> } && arguments.isNotEmpty()) throw InvalidFallback()
|
||||||
val count = result.count { it.name == argument.name }
|
|
||||||
if (count !in argument.min..argument.max)
|
|
||||||
throw ArgumentCountException(argument.name, argument.min, argument.max)
|
|
||||||
}
|
|
||||||
|
|
||||||
return result
|
|
||||||
}
|
|
||||||
|
|
||||||
class Builder internal constructor(
|
|
||||||
private val index: Int,
|
|
||||||
private val name: String?,
|
|
||||||
) {
|
|
||||||
private val commands = mutableListOf<Command>()
|
|
||||||
private val arguments = mutableListOf<Argument<*>>()
|
|
||||||
private lateinit var block: Execution.() -> Unit
|
|
||||||
|
|
||||||
private val nextIndex: Int
|
|
||||||
get() = index + 1
|
|
||||||
|
|
||||||
fun command(
|
|
||||||
name: String? = null,
|
|
||||||
block: Builder.(Key) -> Unit,
|
|
||||||
) {
|
|
||||||
if (name != null && !COMMAND_NAME.matches(name))
|
|
||||||
throw IllegalCommandNameException(name)
|
|
||||||
|
|
||||||
if (commands.any { it.name == name })
|
|
||||||
throw DuplicateCommandException(name)
|
|
||||||
|
|
||||||
val builder = Builder(nextIndex, name)
|
|
||||||
builder.block(Key(nextIndex))
|
|
||||||
val command = builder.build()
|
|
||||||
|
|
||||||
commands.add(command)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun argument(
|
|
||||||
argument: Argument<*>,
|
|
||||||
) {
|
|
||||||
if (!ARGUMENT_NAME.matches(argument.name))
|
|
||||||
throw IllegalArgumentNameException(argument.name)
|
|
||||||
|
|
||||||
if (arguments.any { it.name == argument.name })
|
|
||||||
throw DuplicateArgumentException(argument.name)
|
|
||||||
|
|
||||||
arguments.add(argument)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun arguments(
|
|
||||||
vararg arguments: Argument<*>,
|
|
||||||
) {
|
|
||||||
for (argument in arguments) {
|
|
||||||
argument(argument)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun execute(
|
|
||||||
block: Execution.() -> Unit,
|
|
||||||
) {
|
|
||||||
if (this::block.isInitialized)
|
|
||||||
throw DuplicateExecuteException()
|
|
||||||
|
|
||||||
this.block = block
|
|
||||||
}
|
|
||||||
|
|
||||||
fun build(): Command {
|
|
||||||
if (!this::block.isInitialized)
|
|
||||||
throw NoExecuteException()
|
|
||||||
|
|
||||||
return Command(index, name, commands, arguments, block)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
class Key(
|
|
||||||
internal val index: Int,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun cli(
|
|
||||||
block: Command.Builder.() -> Unit,
|
|
||||||
): Command {
|
|
||||||
val builder = Command.Builder(-1, null)
|
|
||||||
builder.block()
|
|
||||||
return builder.build()
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,50 @@
|
|||||||
|
package com.infendro.cli.command
|
||||||
|
|
||||||
|
import com.infendro.cli.command.Command.*
|
||||||
|
import com.infendro.cli.parser.*
|
||||||
|
|
||||||
|
class CommandFactory internal constructor() {
|
||||||
|
inner class FallbackFactory internal constructor() {
|
||||||
|
fun string(name: String, description: String? = null, block: Builder<*>.(Fallback.Key<String>) -> Unit) =
|
||||||
|
fallback(StringParser, name, description, block)
|
||||||
|
|
||||||
|
fun int(name: String, description: String? = null, block: Builder<*>.(Fallback.Key<Int>) -> Unit) =
|
||||||
|
fallback(IntParser, name, description, block)
|
||||||
|
|
||||||
|
fun long(name: String, description: String? = null, block: Builder<*>.(Fallback.Key<Long>) -> Unit) =
|
||||||
|
fallback(LongParser, name, description, block)
|
||||||
|
|
||||||
|
fun float(name: String, description: String? = null, block: Builder<*>.(Fallback.Key<Float>) -> Unit) =
|
||||||
|
fallback(FloatParser, name, description, block)
|
||||||
|
|
||||||
|
fun double(name: String, description: String? = null, block: Builder<*>.(Fallback.Key<Double>) -> Unit) =
|
||||||
|
fallback(DoubleParser, name, description, block)
|
||||||
|
|
||||||
|
fun boolean(name: String, description: String? = null, block: Builder<*>.(Fallback.Key<Boolean>) -> Unit) =
|
||||||
|
fallback(BooleanParser, name, description, block)
|
||||||
|
|
||||||
|
inline fun <reified T : Enum<T>> enum(
|
||||||
|
name: String,
|
||||||
|
description: String,
|
||||||
|
noinline block: Builder<*>.(Fallback.Key<T>) -> Unit,
|
||||||
|
) =
|
||||||
|
fallback(enumParser<T>(), name, description, block)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun <T : Any> fallback(
|
||||||
|
parser: Parser<T>,
|
||||||
|
name: String,
|
||||||
|
description: String? = null,
|
||||||
|
block: Fallback.Builder<T>.(Fallback.Key<T>) -> Unit,
|
||||||
|
) = Fallback.Builder(parser, name, description).apply { block(key) }.build()
|
||||||
|
|
||||||
|
val fallback = FallbackFactory()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun command(
|
||||||
|
name: String,
|
||||||
|
description: String? = null,
|
||||||
|
block: Builder<*>.() -> Unit,
|
||||||
|
) = Named.Builder(name, description).apply(block).build()
|
||||||
|
|
||||||
|
val command = CommandFactory()
|
||||||
@@ -1,63 +0,0 @@
|
|||||||
package com.infendro.cli.command
|
|
||||||
|
|
||||||
import com.infendro.cli.argument.Argument
|
|
||||||
import kotlin.reflect.KProperty
|
|
||||||
|
|
||||||
class Execution(
|
|
||||||
val commands: List<Cmd>,
|
|
||||||
val arguments: List<Arg>,
|
|
||||||
) {
|
|
||||||
class Cmd(
|
|
||||||
val name: String,
|
|
||||||
)
|
|
||||||
|
|
||||||
class Arg(
|
|
||||||
val name: String,
|
|
||||||
val value: String?,
|
|
||||||
)
|
|
||||||
|
|
||||||
operator fun Command.Key.getValue(
|
|
||||||
thisRef: Any?,
|
|
||||||
property: KProperty<*>,
|
|
||||||
): String {
|
|
||||||
return commands[index]
|
|
||||||
.name
|
|
||||||
}
|
|
||||||
|
|
||||||
operator fun <T> Argument.Single<T>.getValue(
|
|
||||||
thisRef: Any?,
|
|
||||||
property: KProperty<*>,
|
|
||||||
): T {
|
|
||||||
return arguments
|
|
||||||
.single { it.name == name }
|
|
||||||
.let { parser.parse(it.value) }
|
|
||||||
}
|
|
||||||
|
|
||||||
operator fun <T> Argument.SingleOrElse<T>.getValue(
|
|
||||||
thisRef: Any?,
|
|
||||||
property: KProperty<*>,
|
|
||||||
): T {
|
|
||||||
return arguments
|
|
||||||
.singleOrNull { it.name == name }
|
|
||||||
?.let { parser.parse(it.value) }
|
|
||||||
?: other
|
|
||||||
}
|
|
||||||
|
|
||||||
operator fun <T> Argument.SingleOrNull<T>.getValue(
|
|
||||||
thisRef: Any?,
|
|
||||||
property: KProperty<*>,
|
|
||||||
): T? {
|
|
||||||
return arguments
|
|
||||||
.singleOrNull { it.name == name }
|
|
||||||
?.let { parser.parse(it.value) }
|
|
||||||
}
|
|
||||||
|
|
||||||
operator fun <T> Argument.Multiple<T>.getValue(
|
|
||||||
thisRef: Any?,
|
|
||||||
property: KProperty<*>,
|
|
||||||
): List<T> {
|
|
||||||
return arguments
|
|
||||||
.filter { it.name == name }
|
|
||||||
.map { parser.parse(it.value) }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
package com.infendro.cli.command.context
|
||||||
|
|
||||||
|
import com.infendro.cli.Dsl
|
||||||
|
import com.infendro.cli.command.Command
|
||||||
|
import com.infendro.cli.argument.Argument
|
||||||
|
import com.infendro.cli.option.Option
|
||||||
|
import kotlin.reflect.KProperty
|
||||||
|
|
||||||
|
@Dsl
|
||||||
|
class Context internal constructor(
|
||||||
|
private val path: List<Command>,
|
||||||
|
private val commands: Map<Command.Fallback.Key<*>, Any>,
|
||||||
|
private val arguments: Map<Argument<*>, List<Any>>,
|
||||||
|
private val options: Map<Option<*>, List<Any>>,
|
||||||
|
) {
|
||||||
|
val command: Command
|
||||||
|
get() = path.last()
|
||||||
|
|
||||||
|
internal fun execute() = (command.execute)()
|
||||||
|
|
||||||
|
fun help() {
|
||||||
|
command.renderer.render(path)?.let { print(it) }
|
||||||
|
}
|
||||||
|
|
||||||
|
@Suppress("UNCHECKED_CAST")
|
||||||
|
private val <T : Any> Command.Fallback.Key<T>.value: T
|
||||||
|
get() = commands[this] as T
|
||||||
|
|
||||||
|
operator fun <T : Any> Command.Fallback.Key<T>.getValue(thisRef: Any?, property: KProperty<*>): T =
|
||||||
|
value
|
||||||
|
|
||||||
|
@Suppress("UNCHECKED_CAST")
|
||||||
|
private val <T : Any> Argument<T>.values: List<T>
|
||||||
|
get() = arguments[this] as List<T>
|
||||||
|
|
||||||
|
operator fun <T : Any> Argument.Required<T>.getValue(thisRef: Any?, property: KProperty<*>): T =
|
||||||
|
values.first()
|
||||||
|
|
||||||
|
operator fun <T : Any> Argument.OrElse<T>.getValue(thisRef: Any?, property: KProperty<*>): T =
|
||||||
|
values.firstOrNull() ?: other
|
||||||
|
|
||||||
|
operator fun <T : Any> Argument.OrNull<T>.getValue(thisRef: Any?, property: KProperty<*>): T? =
|
||||||
|
values.firstOrNull()
|
||||||
|
|
||||||
|
operator fun <T : Any> Argument.Variable<T>.getValue(thisRef: Any?, property: KProperty<*>): List<T> =
|
||||||
|
values
|
||||||
|
|
||||||
|
@Suppress("UNCHECKED_CAST")
|
||||||
|
private val <T : Any> Option<T>.values: List<T>
|
||||||
|
get() = options[this] as List<T>
|
||||||
|
|
||||||
|
operator fun <T : Any> Option.Required<T>.getValue(thisRef: Any?, property: KProperty<*>): T =
|
||||||
|
values.first()
|
||||||
|
|
||||||
|
operator fun <T : Any> Option.OrElse<T>.getValue(thisRef: Any?, property: KProperty<*>): T =
|
||||||
|
values.firstOrNull() ?: other
|
||||||
|
|
||||||
|
operator fun <T : Any> Option.OrNull<T>.getValue(thisRef: Any?, property: KProperty<*>): T? =
|
||||||
|
values.firstOrNull()
|
||||||
|
|
||||||
|
operator fun <T : Any> Option.Variable<T>.getValue(thisRef: Any?, property: KProperty<*>): List<T> =
|
||||||
|
values
|
||||||
|
}
|
||||||
@@ -0,0 +1,183 @@
|
|||||||
|
package com.infendro.cli.command.context
|
||||||
|
|
||||||
|
import com.infendro.cli.command.Command
|
||||||
|
import com.infendro.cli.error.*
|
||||||
|
import com.infendro.cli.parser.Parser
|
||||||
|
|
||||||
|
internal class ContextParser(
|
||||||
|
private val root: Command,
|
||||||
|
private val args: Array<String>,
|
||||||
|
) {
|
||||||
|
sealed class Result {
|
||||||
|
data class Success(
|
||||||
|
val context: Context,
|
||||||
|
) : Result()
|
||||||
|
|
||||||
|
data class Help(
|
||||||
|
val path: List<Command>,
|
||||||
|
) : Result()
|
||||||
|
|
||||||
|
data class Failure(
|
||||||
|
val path: List<Command>,
|
||||||
|
val error: Error,
|
||||||
|
) : Result()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun success(context: Context) = Result.Success(context)
|
||||||
|
private fun help(path: List<Command>) = Result.Help(path)
|
||||||
|
private fun failure(path: List<Command>, error: Error) = Result.Failure(path, error)
|
||||||
|
|
||||||
|
private var index = 0
|
||||||
|
private val current: String
|
||||||
|
get() = args[index]
|
||||||
|
private val next: String?
|
||||||
|
get() = args.getOrNull(index + 1)
|
||||||
|
|
||||||
|
private fun hasNext() = index < args.size
|
||||||
|
private fun consume() {
|
||||||
|
index++
|
||||||
|
}
|
||||||
|
|
||||||
|
fun parse(): Result {
|
||||||
|
// command
|
||||||
|
var command = root
|
||||||
|
val path = mutableListOf(root)
|
||||||
|
val commands = mutableMapOf<Command.Fallback.Key<*>, Any>()
|
||||||
|
|
||||||
|
while (hasNext()) {
|
||||||
|
if (current.startsWith("-"))
|
||||||
|
break
|
||||||
|
|
||||||
|
val cmd = command.commands.firstOrNull {
|
||||||
|
(it is Command.Named && it.name == current) || it is Command.Fallback<*>
|
||||||
|
}
|
||||||
|
if (cmd == null) {
|
||||||
|
when {
|
||||||
|
command.arguments.isEmpty() -> return failure(path, UnknownCommand(command, current))
|
||||||
|
else -> break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
command = cmd
|
||||||
|
path += cmd
|
||||||
|
if (cmd is Command.Fallback<*>) {
|
||||||
|
val value = when (val result = cmd.parser.parse(current)) {
|
||||||
|
is Parser.Result.Success<*> -> result.value
|
||||||
|
is Parser.Result.Failure<*> -> return failure(path, result.error)
|
||||||
|
}
|
||||||
|
commands[cmd.key] = value
|
||||||
|
}
|
||||||
|
|
||||||
|
consume()
|
||||||
|
}
|
||||||
|
|
||||||
|
// arguments and options
|
||||||
|
val arguments = command.arguments.associateWith { mutableListOf<Any>() }
|
||||||
|
val options = command.options.associateWith { mutableListOf<Any>() }
|
||||||
|
|
||||||
|
var endOfOptions = false
|
||||||
|
var argumentIndex = 0
|
||||||
|
var argumentCount = 0
|
||||||
|
|
||||||
|
while (hasNext()) {
|
||||||
|
val dashes = current.takeWhile { it == '-' }.count()
|
||||||
|
val trimmed = current.drop(dashes)
|
||||||
|
|
||||||
|
when {
|
||||||
|
// argument
|
||||||
|
endOfOptions || dashes == 0 -> {
|
||||||
|
val argument = command.arguments.getOrNull(argumentIndex)
|
||||||
|
?: return failure(path, UnexpectedArgument(current))
|
||||||
|
|
||||||
|
val value = when (val result = argument.parser.parse(current)) {
|
||||||
|
is Parser.Result.Success<*> -> result.value
|
||||||
|
is Parser.Result.Failure<*> -> return failure(path, result.error)
|
||||||
|
}
|
||||||
|
arguments[argument]!! += value
|
||||||
|
argumentCount++
|
||||||
|
|
||||||
|
if (argumentCount == argument.count) {
|
||||||
|
argumentCount = 0
|
||||||
|
argumentIndex++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// option
|
||||||
|
dashes in 1..2 -> {
|
||||||
|
if (dashes == 2 && trimmed.isEmpty()) {
|
||||||
|
endOfOptions = true
|
||||||
|
consume()
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
if (dashes == 2 && trimmed == "help")
|
||||||
|
return help(path)
|
||||||
|
|
||||||
|
val (name, text) = when {
|
||||||
|
trimmed.contains('=') -> {
|
||||||
|
val (name, value) = trimmed.split('=', limit = 2)
|
||||||
|
name to value
|
||||||
|
}
|
||||||
|
else -> {
|
||||||
|
if (next?.startsWith('-') == false) {
|
||||||
|
consume()
|
||||||
|
trimmed to current
|
||||||
|
} else {
|
||||||
|
trimmed to null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val names = when {
|
||||||
|
dashes == 1 -> name.map { "$it" }
|
||||||
|
else -> listOf(name)
|
||||||
|
}
|
||||||
|
|
||||||
|
for (name in names) {
|
||||||
|
val option = command.options.firstOrNull { name in it.names }
|
||||||
|
?: return failure(path, UnknownOption(command, name))
|
||||||
|
|
||||||
|
val value = when {
|
||||||
|
text != null ->
|
||||||
|
when (val result = option.parser.parse(text)) {
|
||||||
|
is Parser.Result.Success<*> -> result.value
|
||||||
|
is Parser.Result.Failure<*> -> return failure(path, result.error)
|
||||||
|
}
|
||||||
|
option.flag -> option.fallback!!
|
||||||
|
else -> return failure(path, MissingOptionValue(option))
|
||||||
|
}
|
||||||
|
options[option]!! += value
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// malformed option
|
||||||
|
else -> {
|
||||||
|
when {
|
||||||
|
current.contains('=') -> {
|
||||||
|
val (option) = current.split('=', limit = 2)
|
||||||
|
return failure(path, MalformedOption(option))
|
||||||
|
}
|
||||||
|
else -> return failure(path, MalformedOption(current))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
consume()
|
||||||
|
}
|
||||||
|
|
||||||
|
// validate arguments
|
||||||
|
for (argument in command.arguments) {
|
||||||
|
val count = arguments[argument]!!.count()
|
||||||
|
if (count !in argument.min..argument.count) return failure(path, InvalidArgumentCount(argument, count))
|
||||||
|
}
|
||||||
|
|
||||||
|
// validate options
|
||||||
|
for (option in command.options) {
|
||||||
|
val count = options[option]!!.count()
|
||||||
|
if (count !in option.min..option.count) return failure(path, InvalidOptionCount(option, count))
|
||||||
|
}
|
||||||
|
|
||||||
|
val context = Context(path, commands, arguments, options)
|
||||||
|
return success(context)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,189 @@
|
|||||||
|
package com.infendro.cli.command.help
|
||||||
|
|
||||||
|
import com.infendro.cli.command.Command
|
||||||
|
import com.infendro.cli.argument.Argument
|
||||||
|
import com.infendro.cli.option.Option
|
||||||
|
import kotlin.reflect.KClass
|
||||||
|
|
||||||
|
object DefaultHelpRenderer : HelpRenderer {
|
||||||
|
override fun render(path: List<Command>) = buildString {
|
||||||
|
val command = path.last()
|
||||||
|
|
||||||
|
usage(path)
|
||||||
|
if (command.description != null) {
|
||||||
|
appendLine()
|
||||||
|
appendLine(command.description)
|
||||||
|
}
|
||||||
|
if (command.commands.isNotEmpty()) {
|
||||||
|
appendLine()
|
||||||
|
commands(command.commands)
|
||||||
|
}
|
||||||
|
if (command.arguments.isNotEmpty()) {
|
||||||
|
appendLine()
|
||||||
|
arguments(command.arguments)
|
||||||
|
}
|
||||||
|
if (command.options.isNotEmpty()) {
|
||||||
|
appendLine()
|
||||||
|
options(command.options)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun StringBuilder.usage(path: List<Command>) {
|
||||||
|
val command = path.last()
|
||||||
|
|
||||||
|
append("Usage:")
|
||||||
|
for (command in path) {
|
||||||
|
append(" ")
|
||||||
|
when {
|
||||||
|
command is Command.Fallback<*> -> append("<${command.name}>")
|
||||||
|
else -> append(command.name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (argument in command.arguments) {
|
||||||
|
append(" ")
|
||||||
|
when {
|
||||||
|
argument.min == 1 && argument.max == 1 -> append("<${argument.name}>")
|
||||||
|
argument.min == 0 && argument.max == 1 -> append("[<${argument.name}>]")
|
||||||
|
else -> {
|
||||||
|
val range = renderRange(argument.min, argument.max)
|
||||||
|
append("<${argument.name}>$range")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (option in command.options) {
|
||||||
|
append(" ")
|
||||||
|
val text = buildString {
|
||||||
|
val names = option.names.joinToString("|") { it.withPrefix() }
|
||||||
|
append(names)
|
||||||
|
append(" ")
|
||||||
|
when {
|
||||||
|
option.flag -> append("[<value>]")
|
||||||
|
else -> append("<value>")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
when {
|
||||||
|
option.min == 1 && option.max == 1 -> append("($text)")
|
||||||
|
option.min == 0 && option.max == 1 -> append("[$text]")
|
||||||
|
else -> {
|
||||||
|
val range = renderRange(option.min, option.max)
|
||||||
|
append("($text)$range")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
appendLine()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun StringBuilder.commands(commands: List<Command>) {
|
||||||
|
val rows = commands.map { command ->
|
||||||
|
val name = when {
|
||||||
|
command is Command.Fallback<*> -> "<${command.name}>"
|
||||||
|
else -> command.name
|
||||||
|
}
|
||||||
|
val type = when {
|
||||||
|
command is Command.Fallback<*> -> command.parser.type.name
|
||||||
|
else -> null
|
||||||
|
}
|
||||||
|
val description = command.description
|
||||||
|
CommandRow(name, type, description)
|
||||||
|
}
|
||||||
|
val nameWidth = rows.maxOf { it.name.length }
|
||||||
|
|
||||||
|
appendLine("Commands:")
|
||||||
|
when {
|
||||||
|
rows.any { it.type != null } -> {
|
||||||
|
val typeWidth = rows.maxOf { it.type?.length ?: 0 }
|
||||||
|
|
||||||
|
rows.forEach { row ->
|
||||||
|
appendLine(" ${row.name.padEnd(nameWidth)} ${(row.type ?: "").padEnd(typeWidth)} ${row.description ?: ""}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else -> rows.forEach { row ->
|
||||||
|
appendLine(" ${row.name.padEnd(nameWidth)} ${row.description ?: ""}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun StringBuilder.arguments(arguments: List<Argument<*>>) {
|
||||||
|
val rows = arguments.map { argument ->
|
||||||
|
val name = argument.name
|
||||||
|
val type = argument.parser.type.name
|
||||||
|
val range = renderRange(argument.min, argument.max)
|
||||||
|
val description = argument.description
|
||||||
|
ArgumentRow(name, type, range, description)
|
||||||
|
}
|
||||||
|
val nameWidth = rows.maxOf { it.name.length }
|
||||||
|
val constraintsWidth = rows.maxOf { it.constraints.length }
|
||||||
|
|
||||||
|
appendLine("Arguments:")
|
||||||
|
for (row in rows) {
|
||||||
|
appendLine(" ${row.name.padEnd(nameWidth)} ${row.constraints.padEnd(constraintsWidth)} ${row.description ?: ""}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun StringBuilder.options(options: List<Option<*>>) {
|
||||||
|
val rows = options.map { option ->
|
||||||
|
val name = option.names.joinToString(" | ") { it.withPrefix() }
|
||||||
|
val type = option.parser.type.name
|
||||||
|
val range = renderRange(option.min, option.max)
|
||||||
|
val description = option.description
|
||||||
|
OptionRow(name, type, range, description)
|
||||||
|
}
|
||||||
|
val nameWidth = rows.maxOf { it.name.length }
|
||||||
|
val constraintsWidth = rows.maxOf { it.constraints.length }
|
||||||
|
|
||||||
|
appendLine("Options:")
|
||||||
|
for (row in rows) {
|
||||||
|
appendLine(" ${row.name.padEnd(nameWidth)} ${row.constraints.padEnd(constraintsWidth)} ${row.description ?: ""}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun String.withPrefix() = when {
|
||||||
|
length == 1 -> "-$this"
|
||||||
|
else -> "--$this"
|
||||||
|
}
|
||||||
|
|
||||||
|
private val KClass<*>.name: String
|
||||||
|
get() = simpleName ?: "Unknown"
|
||||||
|
|
||||||
|
private fun renderRange(min: Int, max: Int?) = when {
|
||||||
|
max == null -> "{$min,}"
|
||||||
|
min == max -> "{$min}"
|
||||||
|
else -> "{$min,$max}"
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun renderRangeFull(min: Int, max: Int?) = when {
|
||||||
|
min == 1 && max == 1 -> "required"
|
||||||
|
min == 0 && max == 1 -> "optional"
|
||||||
|
else -> when {
|
||||||
|
max == null -> "at least $min"
|
||||||
|
min == max -> "exactly $min"
|
||||||
|
else -> "between $min and $max"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
data class CommandRow(
|
||||||
|
val name: String,
|
||||||
|
val type: String?,
|
||||||
|
val description: String?,
|
||||||
|
)
|
||||||
|
|
||||||
|
data class ArgumentRow(
|
||||||
|
val name: String,
|
||||||
|
val type: String,
|
||||||
|
val range: String,
|
||||||
|
val description: String?,
|
||||||
|
) {
|
||||||
|
val constraints: String
|
||||||
|
get() = "$type$range"
|
||||||
|
}
|
||||||
|
|
||||||
|
data class OptionRow(
|
||||||
|
val name: String,
|
||||||
|
val type: String,
|
||||||
|
val range: String,
|
||||||
|
val description: String?,
|
||||||
|
) {
|
||||||
|
val constraints: String
|
||||||
|
get() = "$type$range"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
package com.infendro.cli.command.help
|
||||||
|
|
||||||
|
import com.infendro.cli.command.Command
|
||||||
|
|
||||||
|
interface HelpRenderer {
|
||||||
|
fun render(path: List<Command>): String?
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
package com.infendro.cli.command.help
|
||||||
|
|
||||||
|
import com.infendro.cli.command.Command
|
||||||
|
|
||||||
|
object NoOpHelpRenderer : HelpRenderer {
|
||||||
|
override fun render(path: List<Command>) = null
|
||||||
|
}
|
||||||
5
src/commonMain/kotlin/com/infendro/cli/error/Error.kt
Normal file
5
src/commonMain/kotlin/com/infendro/cli/error/Error.kt
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
package com.infendro.cli.error
|
||||||
|
|
||||||
|
abstract class Error {
|
||||||
|
abstract val message: String
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
package com.infendro.cli.error
|
||||||
|
|
||||||
|
import com.infendro.cli.argument.Argument
|
||||||
|
|
||||||
|
class InvalidArgumentCount(
|
||||||
|
val argument: Argument<*>,
|
||||||
|
val count: Int,
|
||||||
|
) : Error() {
|
||||||
|
override val message: String
|
||||||
|
get() {
|
||||||
|
val expected = when {
|
||||||
|
argument.min == argument.max -> "${argument.min}"
|
||||||
|
argument.unbounded -> "at least ${argument.min}"
|
||||||
|
else -> "${argument.min} to ${argument.max}"
|
||||||
|
}
|
||||||
|
return """Invalid number of values for argument "${argument.name}". Expected $expected but found $count."""
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
package com.infendro.cli.error
|
||||||
|
|
||||||
|
import com.infendro.cli.option.Option
|
||||||
|
|
||||||
|
class InvalidOptionCount(
|
||||||
|
val option: Option<*>,
|
||||||
|
val count: Int,
|
||||||
|
) : Error() {
|
||||||
|
override val message: String
|
||||||
|
get() {
|
||||||
|
val expected = when {
|
||||||
|
option.min == option.max -> "${option.min}"
|
||||||
|
option.unbounded -> "at least ${option.min}"
|
||||||
|
else -> "${option.min} to ${option.max}"
|
||||||
|
}
|
||||||
|
return """Invalid number of values passed for option "${option.name}". Expected $expected but found $count."""
|
||||||
|
}
|
||||||
|
}
|
||||||
11
src/commonMain/kotlin/com/infendro/cli/error/InvalidValue.kt
Normal file
11
src/commonMain/kotlin/com/infendro/cli/error/InvalidValue.kt
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
package com.infendro.cli.error
|
||||||
|
|
||||||
|
import kotlin.reflect.KClass
|
||||||
|
|
||||||
|
class InvalidValue(
|
||||||
|
val value: String,
|
||||||
|
val type: KClass<*>,
|
||||||
|
) : Error() {
|
||||||
|
override val message: String
|
||||||
|
get() = """"$value" cannot be converted to ${type.simpleName ?: "Unknown"}."""
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
package com.infendro.cli.error
|
||||||
|
|
||||||
|
class MalformedOption(
|
||||||
|
val option: String,
|
||||||
|
) : Error() {
|
||||||
|
override val message: String
|
||||||
|
get() = """Malformed option "$option"."""
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
package com.infendro.cli.error
|
||||||
|
|
||||||
|
import com.infendro.cli.option.Option
|
||||||
|
|
||||||
|
class MissingOptionValue(
|
||||||
|
val option: Option<*>,
|
||||||
|
) : Error() {
|
||||||
|
override val message: String
|
||||||
|
get() = """No value provided for option "${option.name}"."""
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
package com.infendro.cli.error
|
||||||
|
|
||||||
|
class UnexpectedArgument(
|
||||||
|
val argument: String,
|
||||||
|
) : Error() {
|
||||||
|
override val message: String
|
||||||
|
get() = """Unexpected argument "$argument"."""
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
package com.infendro.cli.error
|
||||||
|
|
||||||
|
import com.infendro.cli.command.Command
|
||||||
|
import com.infendro.cli.util.distance
|
||||||
|
import com.infendro.cli.util.threshold
|
||||||
|
import kotlin.math.min
|
||||||
|
|
||||||
|
class UnknownCommand(
|
||||||
|
val command: Command,
|
||||||
|
val name: String,
|
||||||
|
) : Error() {
|
||||||
|
override val message: String
|
||||||
|
get() = buildString {
|
||||||
|
val suggestion = command.commands
|
||||||
|
.map { it.name }
|
||||||
|
.associateWith { distance(name, it) }
|
||||||
|
.filter { it.value <= min(it.key.length - 1, threshold) }
|
||||||
|
.minByOrNull { it.value }
|
||||||
|
?.key
|
||||||
|
|
||||||
|
append("""Unknown command "$name".""")
|
||||||
|
if (suggestion != null) append(""" Did you mean "$suggestion"?""")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
package com.infendro.cli.error
|
||||||
|
|
||||||
|
import com.infendro.cli.command.Command
|
||||||
|
import com.infendro.cli.util.distance
|
||||||
|
import com.infendro.cli.util.threshold
|
||||||
|
import kotlin.math.min
|
||||||
|
|
||||||
|
class UnknownOption(
|
||||||
|
val command: Command,
|
||||||
|
val name: String,
|
||||||
|
) : Error() {
|
||||||
|
override val message: String
|
||||||
|
get() = buildString {
|
||||||
|
val suggestion = command.options
|
||||||
|
.flatMap { it.names }
|
||||||
|
.associateWith { distance(name, it) }
|
||||||
|
.filter { it.value <= min(it.key.length - 1, threshold) }
|
||||||
|
.minByOrNull { it.value }
|
||||||
|
?.key
|
||||||
|
|
||||||
|
append("""Unknown option "$name".""")
|
||||||
|
if (suggestion != null) append(""" Did you mean "$suggestion"?""")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
package com.infendro.cli.exception
|
||||||
|
|
||||||
|
abstract class BuildException : Exception() {
|
||||||
|
abstract override val message: String
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
package com.infendro.cli.exception
|
||||||
|
|
||||||
|
import com.infendro.cli.argument.Argument
|
||||||
|
|
||||||
|
class DuplicateArgument(
|
||||||
|
val argument: Argument<*>,
|
||||||
|
) : BuildException() {
|
||||||
|
override val message: String
|
||||||
|
get() = """duplicate argument "${argument.name}""""
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
package com.infendro.cli.exception
|
||||||
|
|
||||||
|
import com.infendro.cli.command.Command
|
||||||
|
|
||||||
|
class DuplicateCommand(
|
||||||
|
val command: Command,
|
||||||
|
) : BuildException() {
|
||||||
|
override val message: String
|
||||||
|
get() = """duplicate command "${command.name}""""
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
package com.infendro.cli.exception
|
||||||
|
|
||||||
|
class DuplicateExecute : BuildException() {
|
||||||
|
override val message: String
|
||||||
|
get() = """duplicate execute block"""
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
package com.infendro.cli.exception
|
||||||
|
|
||||||
|
import com.infendro.cli.option.Option
|
||||||
|
|
||||||
|
class DuplicateOption(
|
||||||
|
val option: Option<*>,
|
||||||
|
) : BuildException() {
|
||||||
|
override val message: String
|
||||||
|
get() = """duplicate option "${option.name}""""
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
package com.infendro.cli.exception
|
||||||
|
|
||||||
|
class DuplicateRenderer : BuildException() {
|
||||||
|
override val message: String
|
||||||
|
get() = """duplicate renderer"""
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
package com.infendro.cli.exception
|
||||||
|
|
||||||
|
class InvalidArgumentName(
|
||||||
|
val name: String,
|
||||||
|
) : BuildException() {
|
||||||
|
override val message: String
|
||||||
|
get() = """invalid argument name "$name""""
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
package com.infendro.cli.exception
|
||||||
|
|
||||||
|
class InvalidArgumentOrder : BuildException() {
|
||||||
|
override val message: String
|
||||||
|
get() = """invalid argument order"""
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
package com.infendro.cli.exception
|
||||||
|
|
||||||
|
class InvalidCommandName(
|
||||||
|
val name: String,
|
||||||
|
) : BuildException() {
|
||||||
|
override val message: String
|
||||||
|
get() = """invalid command name "$name""""
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
package com.infendro.cli.exception
|
||||||
|
|
||||||
|
class InvalidCommandOrder : BuildException() {
|
||||||
|
override val message: String
|
||||||
|
get() = """invalid command order"""
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
package com.infendro.cli.exception
|
||||||
|
|
||||||
|
class InvalidFallback : BuildException() {
|
||||||
|
override val message: String
|
||||||
|
get() = """invalid fallback"""
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
package com.infendro.cli.exception
|
||||||
|
|
||||||
|
class InvalidOptionName(
|
||||||
|
val name: String,
|
||||||
|
) : BuildException() {
|
||||||
|
override val message: String
|
||||||
|
get() = """invalid option name "$name""""
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
package com.infendro.cli.exception
|
||||||
|
|
||||||
|
class InvalidRange : BuildException() {
|
||||||
|
override val message: String
|
||||||
|
get() = """invalid range"""
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
package com.infendro.cli.exception
|
||||||
|
|
||||||
|
class MissingOptionName : BuildException() {
|
||||||
|
override val message: String
|
||||||
|
get() = """missing option name"""
|
||||||
|
}
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
package com.infendro.cli.exception.build
|
|
||||||
|
|
||||||
class DuplicateArgumentException(
|
|
||||||
val argument: String,
|
|
||||||
) : Exception()
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
package com.infendro.cli.exception.build
|
|
||||||
|
|
||||||
class DuplicateCommandException(
|
|
||||||
val command: String?,
|
|
||||||
) : Exception()
|
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
package com.infendro.cli.exception.build
|
|
||||||
|
|
||||||
class DuplicateExecuteException : Exception()
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
package com.infendro.cli.exception.build
|
|
||||||
|
|
||||||
class IllegalArgumentNameException(
|
|
||||||
val name: String,
|
|
||||||
) : Exception()
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
package com.infendro.cli.exception.build
|
|
||||||
|
|
||||||
class IllegalCommandNameException(
|
|
||||||
val name: String,
|
|
||||||
) : Exception()
|
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
package com.infendro.cli.exception.build
|
|
||||||
|
|
||||||
class NoExecuteException : Exception()
|
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
package com.infendro.cli.exception.run
|
|
||||||
|
|
||||||
class ArgumentCountException(
|
|
||||||
val argument: String,
|
|
||||||
val min: Int,
|
|
||||||
val max: Int,
|
|
||||||
) : Exception()
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
package com.infendro.cli.exception.run
|
|
||||||
|
|
||||||
class InvalidArgumentException(
|
|
||||||
val argument: String,
|
|
||||||
) : Exception()
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
package com.infendro.cli.exception.run
|
|
||||||
|
|
||||||
class UnknownArgumentException(
|
|
||||||
val argument: String,
|
|
||||||
) : Exception()
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
package com.infendro.cli.exception.run
|
|
||||||
|
|
||||||
class UnknownCommandException(
|
|
||||||
val command: String,
|
|
||||||
) : Exception()
|
|
||||||
83
src/commonMain/kotlin/com/infendro/cli/option/Option.kt
Normal file
83
src/commonMain/kotlin/com/infendro/cli/option/Option.kt
Normal file
@@ -0,0 +1,83 @@
|
|||||||
|
package com.infendro.cli.option
|
||||||
|
|
||||||
|
import com.infendro.cli.exception.InvalidOptionName
|
||||||
|
import com.infendro.cli.exception.InvalidRange
|
||||||
|
import com.infendro.cli.exception.MissingOptionName
|
||||||
|
import com.infendro.cli.parser.Parser
|
||||||
|
import com.infendro.cli.util.Regex.OPTION
|
||||||
|
|
||||||
|
sealed class Option<T : Any>(
|
||||||
|
val parser: Parser<T>,
|
||||||
|
val fallback: T?,
|
||||||
|
val names: List<String>,
|
||||||
|
val description: String?,
|
||||||
|
val min: Int,
|
||||||
|
val max: Int?,
|
||||||
|
) {
|
||||||
|
val name: String
|
||||||
|
get() = names.maxBy { it.length }
|
||||||
|
|
||||||
|
val flag: Boolean
|
||||||
|
get() = fallback != null
|
||||||
|
|
||||||
|
val required: Boolean
|
||||||
|
get() = min > 0
|
||||||
|
val optional: Boolean
|
||||||
|
get() = !required
|
||||||
|
|
||||||
|
val bounded: Boolean
|
||||||
|
get() = max != null
|
||||||
|
val unbounded: Boolean
|
||||||
|
get() = !bounded
|
||||||
|
|
||||||
|
val count: Int
|
||||||
|
get() = max ?: Int.MAX_VALUE
|
||||||
|
|
||||||
|
init {
|
||||||
|
when {
|
||||||
|
names.isEmpty() -> throw MissingOptionName()
|
||||||
|
names.any { !it.matches(OPTION) } -> throw InvalidOptionName(name)
|
||||||
|
min !in 0..count || max == 0 -> throw InvalidRange()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class Required<T : Any>(
|
||||||
|
parser: Parser<T>,
|
||||||
|
fallback: T?,
|
||||||
|
names: List<String>,
|
||||||
|
description: String?,
|
||||||
|
) : Option<T>(parser, fallback, names, description, min = 1, max = 1) {
|
||||||
|
fun orElse(other: T) =
|
||||||
|
OrElse(parser, fallback, names, description, other)
|
||||||
|
|
||||||
|
fun orNull() =
|
||||||
|
OrNull(parser, fallback, names, description)
|
||||||
|
|
||||||
|
fun variable(min: Int = 0, max: Int? = null) =
|
||||||
|
Variable(parser, fallback, names, description, min, max)
|
||||||
|
}
|
||||||
|
|
||||||
|
class OrElse<T : Any>(
|
||||||
|
parser: Parser<T>,
|
||||||
|
fallback: T?,
|
||||||
|
names: List<String>,
|
||||||
|
description: String?,
|
||||||
|
val other: T,
|
||||||
|
) : Option<T>(parser, fallback, names, description, min = 0, max = 1)
|
||||||
|
|
||||||
|
class OrNull<T : Any>(
|
||||||
|
parser: Parser<T>,
|
||||||
|
fallback: T?,
|
||||||
|
names: List<String>,
|
||||||
|
description: String?,
|
||||||
|
) : Option<T>(parser, fallback, names, description, min = 0, max = 1)
|
||||||
|
|
||||||
|
class Variable<T : Any>(
|
||||||
|
parser: Parser<T>,
|
||||||
|
fallback: T?,
|
||||||
|
names: List<String>,
|
||||||
|
description: String?,
|
||||||
|
min: Int,
|
||||||
|
max: Int?,
|
||||||
|
) : Option<T>(parser, fallback, names, description, min, max)
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
package com.infendro.cli.option
|
||||||
|
|
||||||
|
import com.infendro.cli.parser.*
|
||||||
|
|
||||||
|
object OptionFactory {
|
||||||
|
fun string(vararg names: String, description: String? = null) =
|
||||||
|
option(StringParser, *names, description = description)
|
||||||
|
|
||||||
|
fun int(vararg names: String, description: String? = null) =
|
||||||
|
option(IntParser, *names, description = description)
|
||||||
|
|
||||||
|
fun long(vararg names: String, description: String? = null) =
|
||||||
|
option(LongParser, *names, description = description)
|
||||||
|
|
||||||
|
fun float(vararg names: String, description: String? = null) =
|
||||||
|
option(FloatParser, *names, description = description)
|
||||||
|
|
||||||
|
fun double(vararg names: String, description: String? = null) =
|
||||||
|
option(DoubleParser, *names, description = description)
|
||||||
|
|
||||||
|
fun boolean(vararg names: String, description: String? = null) =
|
||||||
|
option(BooleanParser, fallback = true, *names, description = description)
|
||||||
|
|
||||||
|
inline fun <reified T : Enum<T>> enum(vararg names: String, description: String? = null) =
|
||||||
|
option(enumParser<T>(), *names, description = description)
|
||||||
|
}
|
||||||
|
|
||||||
|
val option = OptionFactory
|
||||||
|
|
||||||
|
fun <T : Any> option(parser: Parser<T>, vararg names: String, description: String? = null) =
|
||||||
|
Option.Required(parser, fallback = null, names.asList(), description)
|
||||||
|
|
||||||
|
fun <T : Any> option(parser: Parser<T>, fallback: T, vararg names: String, description: String? = null) =
|
||||||
|
Option.Required(parser, fallback, names.asList(), description)
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
package com.infendro.cli.parser
|
||||||
|
|
||||||
|
object BooleanParser : Parser<Boolean>(Boolean::class) {
|
||||||
|
override fun parse(text: String) =
|
||||||
|
when (text) {
|
||||||
|
"true", "t" -> success(true)
|
||||||
|
"false", "f" -> success(false)
|
||||||
|
else -> failure(text)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
package com.infendro.cli.parser
|
||||||
|
|
||||||
|
object DoubleParser : Parser<Double>(Double::class) {
|
||||||
|
override fun parse(text: String) =
|
||||||
|
text.toDoubleOrNull()
|
||||||
|
?.let { success(it) }
|
||||||
|
?: failure(text)
|
||||||
|
}
|
||||||
16
src/commonMain/kotlin/com/infendro/cli/parser/EnumParser.kt
Normal file
16
src/commonMain/kotlin/com/infendro/cli/parser/EnumParser.kt
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
package com.infendro.cli.parser
|
||||||
|
|
||||||
|
import kotlin.enums.enumEntries
|
||||||
|
import kotlin.reflect.KClass
|
||||||
|
|
||||||
|
class EnumParser<T : Enum<T>>(
|
||||||
|
type: KClass<T>,
|
||||||
|
private val values: List<T>,
|
||||||
|
) : Parser<T>(type) {
|
||||||
|
override fun parse(text: String) =
|
||||||
|
values.firstOrNull { it.name == text }
|
||||||
|
?.let { success(it) }
|
||||||
|
?: failure(text)
|
||||||
|
}
|
||||||
|
|
||||||
|
inline fun <reified T : Enum<T>> enumParser() = EnumParser(T::class, enumEntries<T>())
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
package com.infendro.cli.parser
|
||||||
|
|
||||||
|
object FloatParser : Parser<Float>(Float::class) {
|
||||||
|
override fun parse(text: String) =
|
||||||
|
text.toFloatOrNull()
|
||||||
|
?.let { success(it) }
|
||||||
|
?: failure(text)
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
package com.infendro.cli.parser
|
||||||
|
|
||||||
|
object IntParser : Parser<Int>(Int::class) {
|
||||||
|
override fun parse(text: String) =
|
||||||
|
text.toIntOrNull()
|
||||||
|
?.let { success(it) }
|
||||||
|
?: failure(text)
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
package com.infendro.cli.parser
|
||||||
|
|
||||||
|
object LongParser : Parser<Long>(Long::class) {
|
||||||
|
override fun parse(text: String) =
|
||||||
|
text.toLongOrNull()
|
||||||
|
?.let { success(it) }
|
||||||
|
?: failure(text)
|
||||||
|
}
|
||||||
24
src/commonMain/kotlin/com/infendro/cli/parser/Parser.kt
Normal file
24
src/commonMain/kotlin/com/infendro/cli/parser/Parser.kt
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
package com.infendro.cli.parser
|
||||||
|
|
||||||
|
import com.infendro.cli.error.Error
|
||||||
|
import com.infendro.cli.error.InvalidValue
|
||||||
|
import kotlin.reflect.KClass
|
||||||
|
|
||||||
|
abstract class Parser<T : Any>(
|
||||||
|
val type: KClass<T>,
|
||||||
|
) {
|
||||||
|
sealed class Result<T : Any> {
|
||||||
|
data class Success<T : Any>(
|
||||||
|
val value: T,
|
||||||
|
) : Result<T>()
|
||||||
|
|
||||||
|
data class Failure<T : Any>(
|
||||||
|
val error: Error,
|
||||||
|
) : Result<T>()
|
||||||
|
}
|
||||||
|
|
||||||
|
protected fun success(value: T) = Result.Success(value)
|
||||||
|
protected fun failure(text: String) = Result.Failure<T>(InvalidValue(text, type))
|
||||||
|
|
||||||
|
abstract fun parse(text: String): Result<T>
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
package com.infendro.cli.parser
|
||||||
|
|
||||||
|
object StringParser : Parser<String>(String::class) {
|
||||||
|
override fun parse(text: String) =
|
||||||
|
success(text)
|
||||||
|
}
|
||||||
54
src/commonMain/kotlin/com/infendro/cli/util/Distance.kt
Normal file
54
src/commonMain/kotlin/com/infendro/cli/util/Distance.kt
Normal file
@@ -0,0 +1,54 @@
|
|||||||
|
package com.infendro.cli.util
|
||||||
|
|
||||||
|
internal const val threshold = 2
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Calculates the Damerau-Levenshtein distance between two strings.
|
||||||
|
*
|
||||||
|
* The distance is the minimum number of operations (insertion, deletion, substitution, and transposition) required to transform one string into another.
|
||||||
|
*
|
||||||
|
* @param a The source string.
|
||||||
|
* @param b The target string.
|
||||||
|
* @return The minimum number of operations to transform [a] into [b].
|
||||||
|
*/
|
||||||
|
internal fun distance(a: String, b: String): Int {
|
||||||
|
if (a == b) return 0
|
||||||
|
|
||||||
|
val n = a.length
|
||||||
|
val m = b.length
|
||||||
|
|
||||||
|
if (n == 0) return m
|
||||||
|
if (m == 0) return n
|
||||||
|
|
||||||
|
var prev2 = IntArray(m + 1)
|
||||||
|
var prev1 = IntArray(m + 1) { it }
|
||||||
|
var curr = IntArray(m + 1)
|
||||||
|
|
||||||
|
for (i in 1..n) {
|
||||||
|
curr[0] = i
|
||||||
|
for (j in 1..m) {
|
||||||
|
val cost = if (a[i - 1] == b[j - 1]) 0 else 1
|
||||||
|
|
||||||
|
curr[j] = minOf(
|
||||||
|
prev1[j] + 1, // deletion
|
||||||
|
curr[j - 1] + 1, // insertion
|
||||||
|
prev1[j - 1] + cost, // substitution
|
||||||
|
)
|
||||||
|
|
||||||
|
// transposition
|
||||||
|
if (i > 1 && j > 1 && a[i - 1] == b[j - 2] && a[i - 2] == b[j - 1]) {
|
||||||
|
curr[j] = minOf(
|
||||||
|
curr[j],
|
||||||
|
prev2[j - 2] + 1,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val tmp = prev2
|
||||||
|
prev2 = prev1
|
||||||
|
prev1 = curr
|
||||||
|
curr = tmp
|
||||||
|
}
|
||||||
|
|
||||||
|
return prev1[m]
|
||||||
|
}
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
package com.infendro.cli.util
|
package com.infendro.cli.util
|
||||||
|
|
||||||
internal object Regex {
|
internal object Regex {
|
||||||
val COMMAND_NAME = """[a-z]+(?:-[a-z]+)*""".toRegex()
|
val COMMAND = Regex("""[a-zA-Z][a-zA-Z0-9]*(?:-[a-zA-Z0-9]+)*""")
|
||||||
val ARGUMENT_NAME = """[a-z]+(?:[\-.][a-z]+)*""".toRegex()
|
val ARGUMENT = Regex("""[a-zA-Z][a-zA-Z0-9]*(?:[\-.][a-zA-Z0-9]+)*""")
|
||||||
val ARGUMENT = """--(?<name>[a-z]+(?:[\-.][a-z]+)*)(?:=(?<value>.*))?""".toRegex()
|
val OPTION = Regex("""[a-zA-Z][a-zA-Z0-9]*(?:[\-.][a-zA-Z0-9]+)*""")
|
||||||
}
|
}
|
||||||
Reference in New Issue
Block a user