Compare commits

..

7 Commits

Author SHA1 Message Date
889f5ddb6c add README
All checks were successful
/ publish (push) Successful in 4m3s
2025-10-04 11:44:02 +02:00
d02fdfa53d bump version to 1.3.0 2025-10-04 11:36:11 +02:00
52b4fd8fcb minor refactor 2025-08-18 00:25:02 +02:00
aedcb9c68a move class 2025-08-18 00:12:41 +02:00
fc416d3bbb major refactor 2025-08-18 00:11:20 +02:00
fee1c346a3 remove main 2025-08-17 21:40:20 +02:00
ca98a1e0d4 upgrade gradle wrapper 2025-08-17 21:34:42 +02:00
18 changed files with 226 additions and 170 deletions

71
README.md Normal file
View File

@@ -0,0 +1,71 @@
# Kotlin CLI
This library implements a lightweight 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
Add the following to your `build.gradle.kts`.
```kotlin
repositories {
maven("https://git.infendro.com/api/packages/Infendro/maven")
}
dependencies {
implementation("com.infendro:cli:1.3.0")
}
```
## Usage
```kotlin
import com.infendro.cli.argument.stringOrElse
import com.infendro.cli.argument.stringOrNull
import com.infendro.cli.command.cli
fun main(args: Array<String>) {
// declare root command
cli {
execute {
// execution of root command (e.g., display help)
}
// declare command "test"
command("test") {
// declare arguments
val greetingArg = stringOrElse("greeting", "Hello")
val nameArg = stringOrNull("name")
execute {
// retrieve the arguments
val greeting by greetingArg
val name by nameArg
println("$greeting ${name ?: "World"}!")
}
// declare more commands...
}
// declare wildcard command
command { wildcard ->
execute {
// retrieve the value used for the wildcard command
val value by wildcard
println("command $value executed!")
}
}
}.run(args)
}
```

View File

@@ -1,5 +1,5 @@
group = "com.infendro" group = "com.infendro"
version = "1.2.2" version = "1.3.0"
repositories { repositories {
mavenCentral() mavenCentral()

View File

@@ -1,5 +1,5 @@
[versions] [versions]
kotlin = "2.1.20" kotlin = "2.2.10"
[plugins] [plugins]
multiplatform = { id = "org.jetbrains.kotlin.multiplatform", version.ref = "kotlin" } multiplatform = { id = "org.jetbrains.kotlin.multiplatform", version.ref = "kotlin" }

Binary file not shown.

View File

@@ -1,6 +1,6 @@
distributionBase=GRADLE_USER_HOME distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip distributionUrl=https\://services.gradle.org/distributions/gradle-8.14-bin.zip
networkTimeout=10000 networkTimeout=10000
validateDistributionUrl=true validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME zipStoreBase=GRADLE_USER_HOME

12
gradlew vendored
View File

@@ -15,6 +15,8 @@
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
# #
# SPDX-License-Identifier: Apache-2.0
#
############################################################################## ##############################################################################
# #
@@ -55,7 +57,7 @@
# Darwin, MinGW, and NonStop. # Darwin, MinGW, and NonStop.
# #
# (3) This script is generated from the Groovy template # (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt # https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project. # within the Gradle project.
# #
# You can find Gradle at https://github.com/gradle/gradle/. # You can find Gradle at https://github.com/gradle/gradle/.
@@ -84,7 +86,7 @@ done
# shellcheck disable=SC2034 # shellcheck disable=SC2034
APP_BASE_NAME=${0##*/} APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value. # Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum MAX_FD=maximum
@@ -112,7 +114,7 @@ case "$( uname )" in #(
NONSTOP* ) nonstop=true ;; NONSTOP* ) nonstop=true ;;
esac esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar CLASSPATH="\\\"\\\""
# Determine the Java command to use to start the JVM. # Determine the Java command to use to start the JVM.
@@ -203,7 +205,7 @@ fi
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command: # Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, # * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped. # and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line. # treated as '${Hostname}' itself on the command line.
@@ -211,7 +213,7 @@ DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
set -- \ set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \ "-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \ -classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \ -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
"$@" "$@"
# Stop when "xargs" is not available. # Stop when "xargs" is not available.

26
gradlew.bat vendored
View File

@@ -13,6 +13,8 @@
@rem See the License for the specific language governing permissions and @rem See the License for the specific language governing permissions and
@rem limitations under the License. @rem limitations under the License.
@rem @rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off @if "%DEBUG%"=="" @echo off
@rem ########################################################################## @rem ##########################################################################
@@ -43,11 +45,11 @@ set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1 %JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute if %ERRORLEVEL% equ 0 goto execute
echo. echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. echo location of your Java installation. 1>&2
goto fail goto fail
@@ -57,22 +59,22 @@ set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute if exist "%JAVA_EXE%" goto execute
echo. echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. echo location of your Java installation. 1>&2
goto fail goto fail
:execute :execute
@rem Setup the command line @rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar set CLASSPATH=
@rem Execute Gradle @rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
:end :end
@rem End local scope for the variables with windows NT shell @rem End local scope for the variables with windows NT shell

View File

@@ -1,52 +0,0 @@
package com.infendro.cli
import com.infendro.cli.argument.Argument.*
import kotlin.reflect.KProperty
class Execution(
val arguments: List<Argument>,
) {
class Argument(
val name: String,
val value: String?,
)
operator fun <T> Single<T>.getValue(
thisRef: Any?,
property: KProperty<*>,
): T {
return parser.parse(
arguments
.find { it.name == name }!!
.value
)
}
operator fun <T> SingleOrElse<T>.getValue(
thisRef: Any?,
property: KProperty<*>,
): T {
return arguments
.find { it.name == name }
?.let { parser.parse(it.value) }
?: other
}
operator fun <T> SingleOrNull<T>.getValue(
thisRef: Any?,
property: KProperty<*>,
): T? {
return arguments
.find { it.name == name }
?.let { parser.parse(it.value) }
}
operator fun <T> Multiple<T>.getValue(
thisRef: Any?,
property: KProperty<*>,
): List<T> {
return arguments
.filter { it.name == name }
.map { parser.parse(it.value) }
}
}

View File

@@ -1,45 +0,0 @@
package com.infendro.cli
import com.infendro.cli.ARG.NAME
import com.infendro.cli.ARG.B
import com.infendro.cli.ARG.C
import com.infendro.cli.ARG.D
import com.infendro.cli.ARG.E
import com.infendro.cli.ARG.F
import com.infendro.cli.argument.*
object ARG {
val NAME = stringOrNull("a")
val B = stringOrElse("b", "x")
val C = ints("c", min = 2, max = 3)
val D = strings("d")
val E = booleanOrElse("e", true)
val F = booleanOrNull("f")
}
fun main(args: Array<String>) {
cli {
val G = boolean("g")
arguments(NAME, B, C, D, E, F)
execute {
val name by NAME
val b by B
val c by C
val d by D
val e by E
val f by F
val g by G
println(g)
}
}.run(
arrayOf(
"--a=woah",
"--c=0",
"--c=0",
// "--f=false",
"--g",
)
)
}

View File

@@ -42,4 +42,10 @@ sealed class Argument<T> {
abstract val parser: Parser<T> abstract val parser: Parser<T>
} }
interface Parser<T> {
fun parse(
text: String?,
): T
}
} }

View File

@@ -1,8 +1,8 @@
package com.infendro.cli.argument package com.infendro.cli.argument
import com.infendro.cli.Command import com.infendro.cli.command.Command
private object BooleanParser : Parser<Boolean> { private object BooleanParser : Argument.Parser<Boolean> {
override fun parse( override fun parse(
text: String?, text: String?,
): Boolean { ): Boolean {

View File

@@ -1,8 +1,8 @@
package com.infendro.cli.argument package com.infendro.cli.argument
import com.infendro.cli.Command import com.infendro.cli.command.Command
private object IntParser : Parser<Int> { private object IntParser : Argument.Parser<Int> {
override fun parse( override fun parse(
text: String?, text: String?,
): Int { ): Int {

View File

@@ -1,7 +0,0 @@
package com.infendro.cli.argument
interface Parser<T> {
fun parse(
text: String?,
): T
}

View File

@@ -1,8 +1,8 @@
package com.infendro.cli.argument package com.infendro.cli.argument
import com.infendro.cli.Command import com.infendro.cli.command.Command
private object StringParser : Parser<String> { private object StringParser : Argument.Parser<String> {
override fun parse( override fun parse(
text: String?, text: String?,
): String { ): String {

View File

@@ -1,21 +1,26 @@
package com.infendro.cli package com.infendro.cli.command
import com.infendro.cli.Regex.ARGUMENT import com.infendro.cli.command.Execution
import com.infendro.cli.Regex.ARGUMENT_NAME
import com.infendro.cli.Regex.COMMAND_NAME
import com.infendro.cli.argument.Argument import com.infendro.cli.argument.Argument
import com.infendro.cli.exception.build.* import com.infendro.cli.exception.build.*
import com.infendro.cli.exception.run.ArgumentCountException import com.infendro.cli.exception.run.ArgumentCountException
import com.infendro.cli.exception.run.InvalidArgumentException import com.infendro.cli.exception.run.InvalidArgumentException
import com.infendro.cli.exception.run.UnknownArgumentException import com.infendro.cli.exception.run.UnknownArgumentException
import com.infendro.cli.exception.run.UnknownCommandException import com.infendro.cli.exception.run.UnknownCommandException
import com.infendro.cli.util.Regex.ARGUMENT
import com.infendro.cli.util.Regex.ARGUMENT_NAME
import com.infendro.cli.util.Regex.COMMAND_NAME
class Command private constructor( class Command private constructor(
private val name: String, private val index: Int,
private val name: String?,
private val commands: List<Command>, private val commands: List<Command>,
private val arguments: List<Argument<*>>, private val arguments: List<Argument<*>>,
private val block: Execution.() -> Unit, private val block: Execution.() -> Unit,
) { ) {
private val nextIndex: Int
get() = index + 1
fun run( fun run(
args: Array<String>, args: Array<String>,
) { ) {
@@ -24,11 +29,11 @@ class Command private constructor(
.find { (_, value) -> value.startsWith("--") } .find { (_, value) -> value.startsWith("--") }
?.index ?: args.size ?.index ?: args.size
val c = args.slice(0..<index) val cmd = args.slice(0..<index)
val a = args.slice(index..<args.size) val arg = args.slice(index..<args.size)
try { try {
run(c, a) run(cmd, arg)
} catch (e: UnknownCommandException) { } catch (e: UnknownCommandException) {
println("""unknown command "${e.command}"""") println("""unknown command "${e.command}"""")
} catch (e: InvalidArgumentException) { } catch (e: InvalidArgumentException) {
@@ -45,33 +50,35 @@ class Command private constructor(
} }
private fun run( private fun run(
cmd: List<String>, args: List<String>, cmd: List<String>,
arg: List<String>,
) { ) {
if (cmd.isEmpty()) { if (index == cmd.lastIndex) {
val arguments = parseArguments(args) Execution(
execute(arguments) parseCmd(cmd),
parseArg(arg),
).block()
} else { } else {
val command = commands.find { it.name == cmd[0] } val command = commands.firstOrNull() { it.name == cmd[nextIndex] || it.name == null }
?: throw UnknownCommandException(cmd[0]) ?: throw UnknownCommandException(cmd[nextIndex])
command.run(cmd.drop(1), args) command.run(cmd, arg)
} }
} }
private fun execute( private fun parseCmd(
arguments: List<Execution.Argument>, cmd: List<String>,
) { ): List<Execution.Cmd> {
val execution = Execution(arguments) return cmd.map { Execution.Cmd(it) }
execution.block()
} }
private fun parseArguments( private fun parseArg(
args: List<String>, arg: List<String>,
): List<Execution.Argument> { ): List<Execution.Arg> {
val result = mutableListOf<Execution.Argument>() val result = mutableListOf<Execution.Arg>()
for (arg in args) { for (argument in arg) {
val match = ARGUMENT.matchEntire(arg) val match = ARGUMENT.matchEntire(argument)
?: throw InvalidArgumentException(arg) ?: throw InvalidArgumentException(argument)
val name = match.groups["name"]!!.value val name = match.groups["name"]!!.value
val value = match.groups["value"]?.value val value = match.groups["value"]?.value
@@ -79,7 +86,7 @@ class Command private constructor(
if (arguments.none { it.name == name }) if (arguments.none { it.name == name })
throw UnknownArgumentException(name) throw UnknownArgumentException(name)
result += Execution.Argument(name, value) result += Execution.Arg(name, value)
} }
arguments arguments
@@ -92,26 +99,31 @@ class Command private constructor(
return result return result
} }
class Builder( class Builder internal constructor(
private val name: String = "", private val index: Int,
private val name: String?,
) { ) {
private val commands = mutableListOf<Command>() private val commands = mutableListOf<Command>()
private val arguments = mutableListOf<Argument<*>>() private val arguments = mutableListOf<Argument<*>>()
private lateinit var block: Execution.() -> Unit private lateinit var block: Execution.() -> Unit
private val nextIndex: Int
get() = index + 1
fun command( fun command(
name: String, name: String? = null,
block: Builder.() -> Unit, block: Builder.(Key) -> Unit,
) { ) {
if (!COMMAND_NAME.matches(name)) if (name != null && !COMMAND_NAME.matches(name))
throw IllegalCommandNameException(name) throw IllegalCommandNameException(name)
if (commands.any { it.name == name }) if (commands.any { it.name == name })
throw DuplicateCommandException(name) throw DuplicateCommandException(name)
val builder = Builder(name) val builder = Builder(nextIndex, name)
builder.block() builder.block(Key(nextIndex))
val command = builder.build() val command = builder.build()
commands.add(command) commands.add(command)
} }
@@ -148,15 +160,19 @@ class Command private constructor(
if (!this::block.isInitialized) if (!this::block.isInitialized)
throw NoExecuteException() throw NoExecuteException()
return Command(name, commands, arguments, block) return Command(index, name, commands, arguments, block)
} }
} }
class Key(
internal val index: Int,
)
} }
fun cli( fun cli(
block: Command.Builder.() -> Unit, block: Command.Builder.() -> Unit,
): Command { ): Command {
val builder = Command.Builder() val builder = Command.Builder(-1, null)
builder.block() builder.block()
return builder.build() return builder.build()
} }

View File

@@ -0,0 +1,63 @@
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) }
}
}

View File

@@ -1,5 +1,5 @@
package com.infendro.cli.exception.build package com.infendro.cli.exception.build
class DuplicateCommandException( class DuplicateCommandException(
val command: String, val command: String?,
) : Exception() ) : Exception()

View File

@@ -1,4 +1,4 @@
package com.infendro.cli package com.infendro.cli.util
internal object Regex { internal object Regex {
val COMMAND_NAME = """[a-z]+(?:-[a-z]+)*""".toRegex() val COMMAND_NAME = """[a-z]+(?:-[a-z]+)*""".toRegex()