commit a0f2155b0cce9877564caff11af3173eddc09355 Author: Infendro Date: Sat Jul 12 20:15:32 2025 +0200 initial commit diff --git a/.gitea/workflows/main.yaml b/.gitea/workflows/main.yaml new file mode 100644 index 0000000..dd78fce --- /dev/null +++ b/.gitea/workflows/main.yaml @@ -0,0 +1,36 @@ +on: + push: + branches: + - main + +env: + GIT__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/ diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..769753d --- /dev/null +++ b/.gitignore @@ -0,0 +1,10 @@ +# IDE +/.idea/ + +# Gradle +/.gradle/ +/gradle.properties + +# Kotlin +/.kotlin/ +/build/ diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..0a04128 --- /dev/null +++ b/LICENSE @@ -0,0 +1,165 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + + This version of the GNU Lesser General Public License incorporates +the terms and conditions of version 3 of the GNU General Public +License, supplemented by the additional permissions listed below. + + 0. Additional Definitions. + + As used herein, "this License" refers to version 3 of the GNU Lesser +General Public License, and the "GNU GPL" refers to version 3 of the GNU +General Public License. + + "The Library" refers to a covered work governed by this License, +other than an Application or a Combined Work as defined below. + + An "Application" is any work that makes use of an interface provided +by the Library, but which is not otherwise based on the Library. +Defining a subclass of a class defined by the Library is deemed a mode +of using an interface provided by the Library. + + A "Combined Work" is a work produced by combining or linking an +Application with the Library. The particular version of the Library +with which the Combined Work was made is also called the "Linked +Version". + + The "Minimal Corresponding Source" for a Combined Work means the +Corresponding Source for the Combined Work, excluding any source code +for portions of the Combined Work that, considered in isolation, are +based on the Application, and not on the Linked Version. + + The "Corresponding Application Code" for a Combined Work means the +object code and/or source code for the Application, including any data +and utility programs needed for reproducing the Combined Work from the +Application, but excluding the System Libraries of the Combined Work. + + 1. Exception to Section 3 of the GNU GPL. + + You may convey a covered work under sections 3 and 4 of this License +without being bound by section 3 of the GNU GPL. + + 2. Conveying Modified Versions. + + If you modify a copy of the Library, and, in your modifications, a +facility refers to a function or data to be supplied by an Application +that uses the facility (other than as an argument passed when the +facility is invoked), then you may convey a copy of the modified +version: + + a) under this License, provided that you make a good faith effort to + ensure that, in the event an Application does not supply the + function or data, the facility still operates, and performs + whatever part of its purpose remains meaningful, or + + b) under the GNU GPL, with none of the additional permissions of + this License applicable to that copy. + + 3. Object Code Incorporating Material from Library Header Files. + + The object code form of an Application may incorporate material from +a header file that is part of the Library. You may convey such object +code under terms of your choice, provided that, if the incorporated +material is not limited to numerical parameters, data structure +layouts and accessors, or small macros, inline functions and templates +(ten or fewer lines in length), you do both of the following: + + a) Give prominent notice with each copy of the object code that the + Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the object code with a copy of the GNU GPL and this license + document. + + 4. Combined Works. + + You may convey a Combined Work under terms of your choice that, +taken together, effectively do not restrict modification of the +portions of the Library contained in the Combined Work and reverse +engineering for debugging such modifications, if you also do each of +the following: + + a) Give prominent notice with each copy of the Combined Work that + the Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the Combined Work with a copy of the GNU GPL and this license + document. + + c) For a Combined Work that displays copyright notices during + execution, include the copyright notice for the Library among + these notices, as well as a reference directing the user to the + copies of the GNU GPL and this license document. + + d) Do one of the following: + + 0) Convey the Minimal Corresponding Source under the terms of this + License, and the Corresponding Application Code in a form + suitable for, and under terms that permit, the user to + recombine or relink the Application with a modified version of + the Linked Version to produce a modified Combined Work, in the + manner specified by section 6 of the GNU GPL for conveying + Corresponding Source. + + 1) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (a) uses at run time + a copy of the Library already present on the user's computer + system, and (b) will operate properly with a modified version + of the Library that is interface-compatible with the Linked + Version. + + e) Provide Installation Information, but only if you would otherwise + be required to provide such information under section 6 of the + GNU GPL, and only to the extent that such information is + necessary to install and execute a modified version of the + Combined Work produced by recombining or relinking the + Application with a modified version of the Linked Version. (If + you use option 4d0, the Installation Information must accompany + the Minimal Corresponding Source and Corresponding Application + Code. If you use option 4d1, you must provide the Installation + Information in the manner specified by section 6 of the GNU GPL + for conveying Corresponding Source.) + + 5. Combined Libraries. + + You may place library facilities that are a work based on the +Library side by side in a single library together with other library +facilities that are not Applications and are not covered by this +License, and convey such a combined library under terms of your +choice, if you do both of the following: + + a) Accompany the combined library with a copy of the same work based + on the Library, uncombined with any other library facilities, + conveyed under the terms of this License. + + b) Give prominent notice with the combined library that part of it + is a work based on the Library, and explaining where to find the + accompanying uncombined form of the same work. + + 6. Revised Versions of the GNU Lesser General Public License. + + The Free Software Foundation may publish revised and/or new versions +of the GNU Lesser General Public License from time to time. Such new +versions will be similar in spirit to the present version, but may +differ in detail to address new problems or concerns. + + Each version is given a distinguishing version number. If the +Library as you received it specifies that a certain numbered version +of the GNU Lesser General Public License "or any later version" +applies to it, you have the option of following the terms and +conditions either of that published version or of any later version +published by the Free Software Foundation. If the Library as you +received it does not specify a version number of the GNU Lesser +General Public License, you may choose any version of the GNU Lesser +General Public License ever published by the Free Software Foundation. + + If the Library as you received it specifies that a proxy can decide +whether future versions of the GNU Lesser General Public License shall +apply, that proxy's public statement of acceptance of any version is +permanent authorization for you to choose that version for the +Library. diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..3723863 --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,48 @@ +group = "com.infendro" +version = "1.2.2" + +repositories { + mavenCentral() +} + +plugins { + alias(libs.plugins.multiplatform) + id("maven-publish") +} + +kotlin { + jvm() + js { + nodejs() + } + linuxX64() +} + +publishing { + repositories { + maven { + url = uri("https://git.infendro.com/api/packages/Infendro/maven") + authentication.create("header", HttpHeaderAuthentication::class) + credentials(HttpHeaderCredentials::class) { + val token = secret("git.token") ?: throw GradleException() + + name = "Authorization" + value = "token $token" + } + } + } +} + +fun secret( + key: String, +): String? { + val property = key + val environment = key + .uppercase() + .replace(".", "__") + + val prop = properties[property] as String? + val env = System.getenv(environment) + + return prop ?: env +} diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml new file mode 100644 index 0000000..bb704f3 --- /dev/null +++ b/gradle/libs.versions.toml @@ -0,0 +1,5 @@ +[versions] +kotlin = "2.1.20" + +[plugins] +multiplatform = { id = "org.jetbrains.kotlin.multiplatform", version.ref = "kotlin" } diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..d64cd49 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..1af9e09 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..1aa94a4 --- /dev/null +++ b/gradlew @@ -0,0 +1,249 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (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 +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# 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 + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# 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 +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..93e3f59 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 0000000..c23d142 --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1 @@ +rootProject.name = "cli" diff --git a/src/commonMain/kotlin/com/infendro/cli/Command.kt b/src/commonMain/kotlin/com/infendro/cli/Command.kt new file mode 100644 index 0000000..c074e14 --- /dev/null +++ b/src/commonMain/kotlin/com/infendro/cli/Command.kt @@ -0,0 +1,162 @@ +package com.infendro.cli + +import com.infendro.cli.Regex.ARGUMENT +import com.infendro.cli.Regex.ARGUMENT_NAME +import com.infendro.cli.Regex.COMMAND_NAME +import com.infendro.cli.argument.Argument +import com.infendro.cli.exception.build.* +import com.infendro.cli.exception.run.ArgumentCountException +import com.infendro.cli.exception.run.InvalidArgumentException +import com.infendro.cli.exception.run.UnknownArgumentException +import com.infendro.cli.exception.run.UnknownCommandException + +class Command private constructor( + private val name: String, + private val commands: List, + private val arguments: List>, + private val block: Execution.() -> Unit, +) { + fun run( + args: Array, + ) { + val index = args + .withIndex() + .find { (_, value) -> value.startsWith("--") } + ?.index ?: args.size + + val c = args.slice(0.. println("""argument "${e.argument}" must appear ${e.min} times""") + e.max == Int.MAX_VALUE -> println("""argument "${e.argument}" must appear at least ${e.min} times""") + else -> println("""argument "${e.argument}" must appear between ${e.min} and ${e.max} times""") + } + } + } + + private fun run( + cmd: List, args: List, + ) { + if (cmd.isEmpty()) { + val arguments = parseArguments(args) + execute(arguments) + } else { + val command = commands.find { it.name == cmd[0] } + ?: throw UnknownCommandException(cmd[0]) + command.run(cmd.drop(1), args) + } + } + + private fun execute( + arguments: List, + ) { + val execution = Execution(arguments) + execution.block() + } + + private fun parseArguments( + args: List, + ): List { + val result = mutableListOf() + + for (arg in args) { + val match = ARGUMENT.matchEntire(arg) + ?: throw InvalidArgumentException(arg) + + val name = match.groups["name"]!!.value + val value = match.groups["value"]?.value + + if (arguments.none { it.name == name }) + throw UnknownArgumentException(name) + + result += Execution.Argument(name, value) + } + + arguments + .forEach { argument -> + 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( + private val name: String = "", + ) { + private val commands = mutableListOf() + private val arguments = mutableListOf>() + private lateinit var block: Execution.() -> Unit + + fun command( + name: String, + block: Builder.() -> Unit, + ) { + if (!COMMAND_NAME.matches(name)) + throw IllegalCommandNameException(name) + + if (commands.any { it.name == name }) + throw DuplicateCommandException(name) + + val builder = Builder(name) + builder.block() + 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(name, commands, arguments, block) + } + } +} + +fun cli( + block: Command.Builder.() -> Unit, +): Command { + val builder = Command.Builder() + builder.block() + return builder.build() +} diff --git a/src/commonMain/kotlin/com/infendro/cli/Execution.kt b/src/commonMain/kotlin/com/infendro/cli/Execution.kt new file mode 100644 index 0000000..b6eff1c --- /dev/null +++ b/src/commonMain/kotlin/com/infendro/cli/Execution.kt @@ -0,0 +1,52 @@ +package com.infendro.cli + +import com.infendro.cli.argument.Argument.* +import kotlin.reflect.KProperty + +class Execution( + val arguments: List, +) { + class Argument( + val name: String, + val value: String?, + ) + + operator fun Single.getValue( + thisRef: Any?, + property: KProperty<*>, + ): T { + return parser.parse( + arguments + .find { it.name == name }!! + .value + ) + } + + operator fun SingleOrElse.getValue( + thisRef: Any?, + property: KProperty<*>, + ): T { + return arguments + .find { it.name == name } + ?.let { parser.parse(it.value) } + ?: other + } + + operator fun SingleOrNull.getValue( + thisRef: Any?, + property: KProperty<*>, + ): T? { + return arguments + .find { it.name == name } + ?.let { parser.parse(it.value) } + } + + operator fun Multiple.getValue( + thisRef: Any?, + property: KProperty<*>, + ): List { + return arguments + .filter { it.name == name } + .map { parser.parse(it.value) } + } +} diff --git a/src/commonMain/kotlin/com/infendro/cli/Main.kt b/src/commonMain/kotlin/com/infendro/cli/Main.kt new file mode 100644 index 0000000..ca8e5f0 --- /dev/null +++ b/src/commonMain/kotlin/com/infendro/cli/Main.kt @@ -0,0 +1,45 @@ +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) { + 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", + ) + ) +} \ No newline at end of file diff --git a/src/commonMain/kotlin/com/infendro/cli/Regex.kt b/src/commonMain/kotlin/com/infendro/cli/Regex.kt new file mode 100644 index 0000000..a57d67c --- /dev/null +++ b/src/commonMain/kotlin/com/infendro/cli/Regex.kt @@ -0,0 +1,7 @@ +package com.infendro.cli + +internal object Regex { + val COMMAND_NAME = """[a-z]+(?:-[a-z]+)*""".toRegex() + val ARGUMENT_NAME = """[a-z]+(?:[\-.][a-z]+)*""".toRegex() + val ARGUMENT = """--(?[a-z]+(?:[\-.][a-z]+)*)(?:=(?.*))?""".toRegex() +} diff --git a/src/commonMain/kotlin/com/infendro/cli/argument/Argument.kt b/src/commonMain/kotlin/com/infendro/cli/argument/Argument.kt new file mode 100644 index 0000000..afc3792 --- /dev/null +++ b/src/commonMain/kotlin/com/infendro/cli/argument/Argument.kt @@ -0,0 +1,45 @@ +package com.infendro.cli.argument + +sealed class Argument { + abstract val name: String + abstract val min: Int + abstract val max: Int + + abstract class Single : Argument() { + final override val min: Int + get() = 1 + final override val max: Int + get() = 1 + + abstract val parser: Parser + } + + abstract class SingleOrElse : Argument() { + abstract val other: T + + final override val min: Int + get() = 0 + final override val max: Int + get() = 1 + + abstract val parser: Parser + } + + abstract class SingleOrNull : Argument() { + final override val min: Int + get() = 0 + final override val max: Int + get() = 1 + + abstract val parser: Parser + } + + abstract class Multiple : Argument>() { + override val min: Int + get() = 0 + override val max: Int + get() = Int.MAX_VALUE + + abstract val parser: Parser + } +} diff --git a/src/commonMain/kotlin/com/infendro/cli/argument/Boolean.kt b/src/commonMain/kotlin/com/infendro/cli/argument/Boolean.kt new file mode 100644 index 0000000..8db70b4 --- /dev/null +++ b/src/commonMain/kotlin/com/infendro/cli/argument/Boolean.kt @@ -0,0 +1,84 @@ +package com.infendro.cli.argument + +import com.infendro.cli.Command + +private object BooleanParser : Parser { + override fun parse( + text: String?, + ): Boolean { + return text == null || text.toBooleanStrict() + } +} + +class BooleanArgument( + override val name: String, +) : Argument.Single() { + override val parser: Parser + 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() { + override val parser: Parser + 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() { + override val parser: Parser + 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() { + override val parser: Parser + 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) } diff --git a/src/commonMain/kotlin/com/infendro/cli/argument/Int.kt b/src/commonMain/kotlin/com/infendro/cli/argument/Int.kt new file mode 100644 index 0000000..113d0ca --- /dev/null +++ b/src/commonMain/kotlin/com/infendro/cli/argument/Int.kt @@ -0,0 +1,84 @@ +package com.infendro.cli.argument + +import com.infendro.cli.Command + +private object IntParser : Parser { + override fun parse( + text: String?, + ): Int { + return text!!.toInt() + } +} + +class IntArgument( + override val name: String, +) : Argument.Single() { + override val parser: Parser + 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() { + override val parser: Parser + 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() { + override val parser: Parser + 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() { + override val parser: Parser + 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) } diff --git a/src/commonMain/kotlin/com/infendro/cli/argument/Parser.kt b/src/commonMain/kotlin/com/infendro/cli/argument/Parser.kt new file mode 100644 index 0000000..c93353e --- /dev/null +++ b/src/commonMain/kotlin/com/infendro/cli/argument/Parser.kt @@ -0,0 +1,7 @@ +package com.infendro.cli.argument + +interface Parser { + fun parse( + text: String?, + ): T +} diff --git a/src/commonMain/kotlin/com/infendro/cli/argument/String.kt b/src/commonMain/kotlin/com/infendro/cli/argument/String.kt new file mode 100644 index 0000000..54c35f3 --- /dev/null +++ b/src/commonMain/kotlin/com/infendro/cli/argument/String.kt @@ -0,0 +1,84 @@ +package com.infendro.cli.argument + +import com.infendro.cli.Command + +private object StringParser : Parser { + override fun parse( + text: String?, + ): String { + return text!! + } +} + +class StringArgument( + override val name: String, +) : Argument.Single() { + override val parser: Parser + 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() { + override val parser: Parser + 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() { + override val parser: Parser + 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() { + override val parser: Parser + 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) } diff --git a/src/commonMain/kotlin/com/infendro/cli/exception/build/DuplicateArgumentException.kt b/src/commonMain/kotlin/com/infendro/cli/exception/build/DuplicateArgumentException.kt new file mode 100644 index 0000000..0d5d11d --- /dev/null +++ b/src/commonMain/kotlin/com/infendro/cli/exception/build/DuplicateArgumentException.kt @@ -0,0 +1,5 @@ +package com.infendro.cli.exception.build + +class DuplicateArgumentException( + val argument: String, +) : Exception() diff --git a/src/commonMain/kotlin/com/infendro/cli/exception/build/DuplicateCommandException.kt b/src/commonMain/kotlin/com/infendro/cli/exception/build/DuplicateCommandException.kt new file mode 100644 index 0000000..4a21135 --- /dev/null +++ b/src/commonMain/kotlin/com/infendro/cli/exception/build/DuplicateCommandException.kt @@ -0,0 +1,5 @@ +package com.infendro.cli.exception.build + +class DuplicateCommandException( + val command: String, +) : Exception() diff --git a/src/commonMain/kotlin/com/infendro/cli/exception/build/DuplicateExecuteException.kt b/src/commonMain/kotlin/com/infendro/cli/exception/build/DuplicateExecuteException.kt new file mode 100644 index 0000000..91134a1 --- /dev/null +++ b/src/commonMain/kotlin/com/infendro/cli/exception/build/DuplicateExecuteException.kt @@ -0,0 +1,3 @@ +package com.infendro.cli.exception.build + +class DuplicateExecuteException : Exception() diff --git a/src/commonMain/kotlin/com/infendro/cli/exception/build/IllegalArgumentNameException.kt b/src/commonMain/kotlin/com/infendro/cli/exception/build/IllegalArgumentNameException.kt new file mode 100644 index 0000000..3ad2f2d --- /dev/null +++ b/src/commonMain/kotlin/com/infendro/cli/exception/build/IllegalArgumentNameException.kt @@ -0,0 +1,5 @@ +package com.infendro.cli.exception.build + +class IllegalArgumentNameException( + val name: String, +) : Exception() diff --git a/src/commonMain/kotlin/com/infendro/cli/exception/build/IllegalCommandNameException.kt b/src/commonMain/kotlin/com/infendro/cli/exception/build/IllegalCommandNameException.kt new file mode 100644 index 0000000..f857b99 --- /dev/null +++ b/src/commonMain/kotlin/com/infendro/cli/exception/build/IllegalCommandNameException.kt @@ -0,0 +1,5 @@ +package com.infendro.cli.exception.build + +class IllegalCommandNameException( + val name: String, +) : Exception() diff --git a/src/commonMain/kotlin/com/infendro/cli/exception/build/NoExecuteException.kt b/src/commonMain/kotlin/com/infendro/cli/exception/build/NoExecuteException.kt new file mode 100644 index 0000000..4fc891b --- /dev/null +++ b/src/commonMain/kotlin/com/infendro/cli/exception/build/NoExecuteException.kt @@ -0,0 +1,3 @@ +package com.infendro.cli.exception.build + +class NoExecuteException : Exception() diff --git a/src/commonMain/kotlin/com/infendro/cli/exception/run/ArgumentCountException.kt b/src/commonMain/kotlin/com/infendro/cli/exception/run/ArgumentCountException.kt new file mode 100644 index 0000000..bef1654 --- /dev/null +++ b/src/commonMain/kotlin/com/infendro/cli/exception/run/ArgumentCountException.kt @@ -0,0 +1,7 @@ +package com.infendro.cli.exception.run + +class ArgumentCountException( + val argument: String, + val min: Int, + val max: Int, +) : Exception() diff --git a/src/commonMain/kotlin/com/infendro/cli/exception/run/InvalidArgumentException.kt b/src/commonMain/kotlin/com/infendro/cli/exception/run/InvalidArgumentException.kt new file mode 100644 index 0000000..01b73f6 --- /dev/null +++ b/src/commonMain/kotlin/com/infendro/cli/exception/run/InvalidArgumentException.kt @@ -0,0 +1,5 @@ +package com.infendro.cli.exception.run + +class InvalidArgumentException( + val argument: String, +) : Exception() diff --git a/src/commonMain/kotlin/com/infendro/cli/exception/run/UnknownArgumentException.kt b/src/commonMain/kotlin/com/infendro/cli/exception/run/UnknownArgumentException.kt new file mode 100644 index 0000000..4c7d9ab --- /dev/null +++ b/src/commonMain/kotlin/com/infendro/cli/exception/run/UnknownArgumentException.kt @@ -0,0 +1,5 @@ +package com.infendro.cli.exception.run + +class UnknownArgumentException( + val argument: String, +) : Exception() diff --git a/src/commonMain/kotlin/com/infendro/cli/exception/run/UnknownCommandException.kt b/src/commonMain/kotlin/com/infendro/cli/exception/run/UnknownCommandException.kt new file mode 100644 index 0000000..780f916 --- /dev/null +++ b/src/commonMain/kotlin/com/infendro/cli/exception/run/UnknownCommandException.kt @@ -0,0 +1,5 @@ +package com.infendro.cli.exception.run + +class UnknownCommandException( + val command: String, +) : Exception()