├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── settings.gradle ├── .gitignore ├── publish.gradle ├── travis_windows_setup.bat ├── CHANGELOG.md ├── .travis.yml ├── gradlew.bat ├── example ├── build.gradle └── src │ └── commonMain │ └── kotlin │ └── Example.kt ├── README.md ├── src ├── commonMain │ └── kotlin │ │ └── de │ │ └── dbaelz │ │ └── konclik │ │ ├── Models.kt │ │ ├── KonclikDsl.kt │ │ └── Parser.kt └── commonTest │ └── kotlin │ └── ParserTest.kt ├── gradlew └── LICENSE /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dbaelz/Konclik/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'konclik' 2 | include ':example' 3 | 4 | enableFeaturePreview('GRADLE_METADATA') -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | /local.properties 4 | /.idea/ 5 | .DS_Store 6 | /build/ 7 | /example/build 8 | /jvm/build 9 | /jvm/out 10 | /native/build -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Thu Oct 11 15:39:46 PDT 2018 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-4.7-all.zip 7 | -------------------------------------------------------------------------------- /publish.gradle: -------------------------------------------------------------------------------- 1 | def pomBaseData = { 2 | licenses { 3 | license { 4 | name "Apache License, Version 2.0" 5 | url "https://www.apache.org/licenses/LICENSE-2.0.txt" 6 | } 7 | } 8 | scm { 9 | url "https://github.com/dbaelz/Konclik" 10 | } 11 | } 12 | 13 | def generatePom = { pom -> 14 | pom.withXml { 15 | def root = it.asNode() 16 | root.appendNode('name', project.name) 17 | root.appendNode('description', 'Kotlin/Native Command Line Interface Kit') 18 | root.appendNode('url', 'https://github.com/dbaelz/Konclik') 19 | root.children().last() + pomBaseData 20 | } 21 | } 22 | 23 | ext.generatePom = generatePom 24 | -------------------------------------------------------------------------------- /travis_windows_setup.bat: -------------------------------------------------------------------------------- 1 | REM https://github.com/korlibs/klock/blob/2614171f6981b5905768f4c225114b0a2ebf3a79/travis_win.bat 2 | 3 | RD /s /q "c:\Program Files\IIS" 4 | RD /s /q "c:\Program Files\Java" 5 | RD /s /q "c:\Program Files\Microsoft" 6 | RD /s /q "c:\Program Files\Microsoft Visual Studio" 7 | RD /s /q "c:\Program Files\Microsoft Visual Studio 14.0" 8 | RD /s /q "c:\Program Files\cmake" 9 | RD /s /q "c:\Program Files\Microsoft SDKs" 10 | RD /s /q "c:\Program Files (x86)\IIS" 11 | RD /s /q "c:\Program Files (x86)\Java" 12 | RD /s /q "c:\Program Files (x86)\Microsoft" 13 | RD /s /q "c:\Program Files (x86)\Microsoft Visual Studio" 14 | RD /s /q "c:\Program Files (x86)\Microsoft Visual Studio 14.0" 15 | RD /s /q "c:\Program Files (x86)\cmake" 16 | RD /s /q "c:\Program Files (x86)\Microsoft SDKs" 17 | 18 | choco install jdk8 -y -params "installdir=c:\\java8" 19 | 20 | del c:\java8\src.zip 21 | del c:\java8\javafx-src.zip 22 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## [Unreleased] 2 | 3 | 4 | ## [0.6.0] - 2018-10-29 5 | ### Added 6 | - Use Travis CI to build and upload the artifacts ([#1](https://github.com/dbaelz/Konclik/pull/1)) 7 | - Print help and the current version with the `--help` and `--version` parameter ([#2](https://github.com/dbaelz/Konclik/pull/2)) 8 | - Define a CLI application in a `main()` function ([#4](https://github.com/dbaelz/Konclik/pull/4)) 9 | - KDoc documentation for the DSL Builders ([#9](https://github.com/dbaelz/Konclik/pull/9)) 10 | - Improve readme and add changelog ([#7](https://github.com/dbaelz/Konclik/pull/7)) 11 | 12 | ### Changed 13 | - Utilization of the new multiplatform Gradle plugin ([#3](https://github.com/dbaelz/Konclik/pull/3)) 14 | 15 | 16 | ## [0.5.0] - 2018-09-23 17 | ### Added 18 | - DSL providing models and builders to create a CLI application 19 | - Parser for the arguments handed over to the app 20 | - Kotlin/Native multiplatform support for `linux` and `macos` targets 21 | - Gradle module to create a JAR targeting the JVM 22 | - Example CLI app to demonstrate the usage -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | matrix: 2 | include: 3 | - os: linux 4 | language: java 5 | jdk: oraclejdk8 6 | script: 7 | - ./gradlew clean build 8 | before_cache: 9 | - rm -f $HOME/.gradle/caches/modules-2/modules-2.lock 10 | - rm -fr $HOME/.gradle/caches/*/plugin-resolution/ 11 | cache: 12 | directories: 13 | - $HOME/.gradle/caches/ 14 | - $HOME/.gradle/wrapper/ 15 | - $HOME/.konan/cache/ 16 | - $HOME/.konan/dependencies/ 17 | deploy: 18 | provider: script 19 | script: ./gradlew publish 20 | skip_cleanup: true 21 | dry-run: false 22 | on: 23 | branch: master 24 | # - os: windows 25 | # language: shell 26 | # env: 27 | # - JAVA_HOME=c:\\java8 28 | # script: 29 | # - ./travis_windows_setup.bat 30 | # - ./gradlew.bat clean windowsTest 31 | # before_cache: 32 | # - rm -f $HOME/.gradle/caches/modules-2/modules-2.lock 33 | # - rm -fr $HOME/.gradle/caches/*/plugin-resolution/ 34 | # cache: 35 | # directories: 36 | # - $HOME/.gradle/caches/ 37 | # - $HOME/.gradle/wrapper/ 38 | # - $HOME/.konan/cache/ 39 | # - $HOME/.konan/dependencies/ 40 | # deploy: 41 | # provider: script 42 | # script: ./gradlew.bat publishWindowsPublicationToMavenRepository 43 | # skip_cleanup: true 44 | # dry-run: false 45 | # on: 46 | # branch: master 47 | - os: osx 48 | language: java 49 | jdk: oraclejdk8 50 | script: 51 | - ./gradlew clean macosTest 52 | before_cache: 53 | - rm -f $HOME/.gradle/caches/modules-2/modules-2.lock 54 | - rm -fr $HOME/.gradle/caches/*/plugin-resolution/ 55 | cache: 56 | directories: 57 | - $HOME/.gradle/caches/ 58 | - $HOME/.gradle/wrapper/ 59 | - $HOME/.konan/cache/ 60 | - $HOME/.konan/dependencies/ 61 | deploy: 62 | provider: script 63 | script: ./gradlew publishMacosPublicationToMavenRepository 64 | skip_cleanup: true 65 | dry-run: false 66 | on: 67 | branch: master 68 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /example/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'kotlin-multiplatform' 2 | apply plugin: 'java' 3 | 4 | kotlin { 5 | targets { 6 | fromPreset(presets.macosX64, 'macos') 7 | fromPreset(presets.linuxX64, 'linux') 8 | fromPreset(presets.mingwX64, 'windows') 9 | fromPreset(presets.jvm, 'jvm') 10 | fromPreset(presets.js, 'js') { 11 | compilations.main { 12 | compileKotlinJs.kotlinOptions { 13 | moduleKind = "commonjs" 14 | } 15 | } 16 | } 17 | 18 | configure([macos, linux, windows]) { 19 | compilations.main.outputKinds 'executable' 20 | } 21 | } 22 | sourceSets { 23 | all { 24 | dependencies { 25 | implementation rootProject 26 | } 27 | } 28 | } 29 | } 30 | 31 | dependencies { 32 | commonMainImplementation 'org.jetbrains.kotlin:kotlin-stdlib' 33 | jvmMainImplementation 'org.jetbrains.kotlin:kotlin-stdlib-jdk8' 34 | jsMainImplementation 'org.jetbrains.kotlin:kotlin-stdlib-js' 35 | } 36 | 37 | ['Macos', 'Linux', 'Windows'].forEach { target -> 38 | task "run$target" { 39 | dependsOn "linkDebugExecutable$target" 40 | doLast { 41 | exec { 42 | commandLine kotlin.targets[target.toLowerCase()].compilations.main.getBinary('executable', 'debug') 43 | } 44 | } 45 | } 46 | } 47 | 48 | def jvmCompilations = kotlin.targets.jvm.compilations 49 | task createExecutableJar(type: Jar) { 50 | dependsOn jvmMainClasses 51 | manifest { 52 | attributes 'Main-Class': 'ExampleKt' 53 | } 54 | baseName = 'example' 55 | from { jvmCompilations.main.output } 56 | from { jvmCompilations.main.runtimeDependencyFiles.collect { it.isDirectory() ? it : zipTree(it) } } 57 | } 58 | 59 | task runJar(type: Exec) { 60 | dependsOn createExecutableJar 61 | commandLine "java", "-jar", "$buildDir/libs/example.jar" 62 | } 63 | 64 | apply plugin: 'com.moowork.node' 65 | 66 | node { 67 | version = node_version 68 | download = true 69 | workDir = rootProject.file('.gradle/nodejs') 70 | } 71 | 72 | def jsCompilations = kotlin.targets.js.compilations 73 | task createJsRuntimeDir { 74 | dependsOn jsMainClasses, jsTestClasses 75 | doLast { 76 | copy { 77 | from jsCompilations.main.output.first() 78 | into "$buildDir/js" 79 | } 80 | copy { 81 | jsCompilations.test.runtimeDependencyFiles.each { 82 | if (it.exists() && !it.isDirectory()) { 83 | from zipTree(it.absolutePath).matching { include '*.js' } 84 | } 85 | } 86 | into "$buildDir/js/node_modules" 87 | } 88 | } 89 | } 90 | 91 | task runNodejs(type: NodeTask) { 92 | dependsOn createJsRuntimeDir 93 | script = file("$buildDir/js/example.js") 94 | execOverrides { 95 | it.workingDir = "$buildDir/js" 96 | } 97 | } 98 | 99 | // Fix for https://github.com/srs/gradle-node-plugin/issues/301 100 | repositories.whenObjectAdded { 101 | if (it instanceof IvyArtifactRepository) { 102 | metadataSources { 103 | artifact() 104 | } 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /example/src/commonMain/kotlin/Example.kt: -------------------------------------------------------------------------------- 1 | import de.dbaelz.konclik.Command 2 | import de.dbaelz.konclik.Parameter 3 | import de.dbaelz.konclik.ParseResult 4 | import de.dbaelz.konclik.konclikApp 5 | 6 | fun main(args: Array) = konclikApp(args) { 7 | metadata { 8 | name = "Example Application" 9 | description = "Demo of the available DSL" 10 | version = "0.4.2" 11 | } 12 | command { 13 | metadata { 14 | name = "hello" 15 | description = "A simple example which prints 'Hello \$user!'" 16 | } 17 | parameters { 18 | arguments = listOf(Parameter.Argument("user")) 19 | 20 | options = listOf( 21 | Parameter.Option.Switch("--verbose"), 22 | Parameter.Option.Switch("--uppercase"), 23 | Parameter.Option.Value("--times"), 24 | Parameter.Option.Value("--tags", 3, listOf("#kotlin", "#cli", "#dsl")) 25 | ) 26 | } 27 | action { command, providedParameters -> 28 | val user: String = providedParameters.positionalArguments["user"] ?: "world" 29 | 30 | var text = "Hello $user!" 31 | 32 | if (providedParameters.options.containsKey("--uppercase")) { 33 | text = text.toUpperCase() 34 | } 35 | 36 | providedParameters.options["--times"].orEmpty().let { 37 | var times = 1 38 | if (it.isNotEmpty()) { 39 | try { 40 | it.firstOrNull()?.toIntOrNull()?.let { 41 | if (it > 0) times = it 42 | } 43 | } catch (exception: NumberFormatException) { 44 | } 45 | } 46 | (1..times).forEach { println(text) } 47 | } 48 | 49 | var tags = "" 50 | providedParameters.options["--tags"]?.forEach { 51 | tags += "$it " 52 | } 53 | if (tags.isNotEmpty()) println(tags) 54 | 55 | if (providedParameters.options.containsKey("--verbose")) { 56 | println() 57 | println(command) 58 | println(providedParameters) 59 | } 60 | } 61 | } 62 | command { 63 | metadata { 64 | name = "develop" 65 | } 66 | parameters { 67 | options = listOf( 68 | Parameter.Option.Choice("--language", setOf("Kotlin", "Java"), "Kotlin") 69 | ) 70 | } 71 | action { _, parameters -> 72 | parameters.options["--language"]?.firstOrNull()?.let { 73 | when (it) { 74 | "Kotlin" -> println("Yeah! Kotlin!") 75 | "Java" -> println("Really? Java?") 76 | } 77 | } 78 | } 79 | } 80 | command { 81 | metadata { 82 | name = "echo" 83 | } 84 | action(::printlnAction) 85 | onError { command, error -> 86 | println("Error executing command \"${command.name}\"") 87 | println(error.toString()) 88 | } 89 | } 90 | } 91 | 92 | private fun printlnAction(command: Command, parameters: ParseResult.Parameters) { 93 | println(command) 94 | println(parameters) 95 | } 96 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Konclik: Kotlin/Native Command Line Interface Kit 2 | [![Build Status](https://travis-ci.com/dbaelz/Konclik.svg?branch=master)](https://travis-ci.com/dbaelz/Konclik) 3 | 4 | Konclik is a library for the development of a CLI application. 5 | 6 | #### Why Konclik? 7 | 8 | - Provides a simple yet useful Kotlin DSL to define the application 9 | - Built with Kotlin's [Multi-platform Project](https://kotlinlang.org/docs/reference/multiplatform.html) tools so you can write once and run everywhere 10 | - Targets Linux, Windows, MacOS, Jvm, and NodeJS 11 | 12 | #### Version 13 | - The newest version of Konclik is `0.6.0` 14 | - All changes are documented in the [CHANGELOG](CHANGELOG.md) 15 | 16 | #### Contributing 17 | Issues, contributions and suggestions are very welcome. 18 | Please report bugs, improvements and new features with an issue, 19 | so we can discuss the next steps. 20 | 21 | ## Project structure 22 | 23 | This project uses the [new MPP plugin](https://kotlinlang.org/docs/reference/building-mpp-with-gradle.html), 24 | the root contains Konclik's core source in the `src` directory. 25 | In addition to the core, the following submodules are available. 26 | - `example`: An example, which demonstrates a Konclik app targeting MacOS, Linux, Windows, Jvm, and NodeJS. 27 | 28 | ## Setup 29 | Konclik is published to bintray and can easily be integrated into an existing project. 30 | 31 | #### Repository 32 | 33 | ```gradle 34 | repositories { 35 | maven { 36 | url "https://dl.bintray.com/dbaelz/konclik" 37 | } 38 | // Other repos like: 39 | //jcenter() 40 | } 41 | ``` 42 | 43 | #### Download 44 | 45 | ```gradle 46 | dependencies { 47 | // With Gradle Metadata enabled, all targets can depend on 48 | implementation "de.dbaelz.konclik:konclik:0.6.0" 49 | 50 | // All artifacts are available with the -target suffix 51 | implementation "de.dbaelz.konclik:konclik-macos:0.6.0" 52 | implementation "de.dbaelz.konclik:konclik-linux:0.6.0" 53 | implementation "de.dbaelz.konclik:konclik-windows:0.6.0" 54 | implementation "de.dbaelz.konclik:konclik-jvm:0.6.0" 55 | implementation "de.dbaelz.konclik:konclik-js:0.6.0" 56 | } 57 | ``` 58 | 59 | 60 | ## Available tasks 61 | 62 | *Note: If the Host machine does not support a specific target, that target's tasks will simply be ignored.* 63 | 64 | The following Gradle tasks are available: 65 | - Testing: `jsTest`, `macosTest`, `jvmTest`, `linuxTest`, `windowsTest` 66 | - `publish`: Publish to bintray, replace the publishing url with your own repository. 67 | - `publishToMavenLocal`: Publish a version to your local machine, available in the `mavenLocal()` repository 68 | - Example App: `example:runMacos`, `example:runJar`, `example:runLinux`, `example:runWindows`, `example:runNodejs` 69 | 70 | 71 | 72 | ## Konclik DSL Example 73 | This project provides an [example](example/src/commonMain/kotlin), which 74 | shows the usage of the DSL. 75 | 76 | The current DSL is WIP, but suitable to build effective CLI applications. 77 | It provides KDoc to explain the usage. A short overview of the components: 78 | - `konclikApp`: The CLI app 79 | * The app provides optional `metadata` (name, description and version) 80 | * A app consists of one or more `command` entries 81 | * Use `run()` to parse the provided CLI args and execute the command with these args 82 | * The app provides a help output showing the available commands, when a invalid command was entered 83 | * It prints a version info with `--version` 84 | - `command`: 85 | * It's identified by its `name`. The `description` is optional 86 | * `parameters` can be defined for the command. They evaluated in the following order: 87 | * `arguments`: Positional arguments, internally evaluated by the order of the list 88 | * `options`: Options are optional and could be switch or value parameters 89 | * The `action` consists of the logic to execute for the command 90 | * By default, parser errors are printed to standard out. With `onError` this can be changed and custom error handling is possible 91 | * The command prints a help page with `--help` and returns 92 | 93 | 94 | ## License 95 | [Apache 2 License](LICENSE) 96 | -------------------------------------------------------------------------------- /src/commonMain/kotlin/de/dbaelz/konclik/Models.kt: -------------------------------------------------------------------------------- 1 | package de.dbaelz.konclik 2 | 3 | data class KonclikApp(val name: String = "", 4 | val description: String = "", 5 | val version: String = "", 6 | private val commands: List = emptyList()) { 7 | fun run(args: List = emptyList()) { 8 | if (args.isEmpty()) { 9 | showHelp() 10 | } else { 11 | val commandName = args.first() 12 | if (commandName == "--version") { 13 | showVersion() 14 | } else { 15 | findCommand(commandName)?.execute(args.drop(1)) ?: showHelp() 16 | } 17 | } 18 | } 19 | 20 | private fun showVersion() { 21 | println("$name; Version ${if (version.isNotEmpty()) version else "not provided"}") 22 | } 23 | 24 | private fun showHelp() { 25 | println(name + if (description.isNotEmpty()) ": $description" else "") 26 | if (version.isNotEmpty()) println("Version: $version") 27 | 28 | if (commands.isNotEmpty()) { 29 | println() 30 | println("Available commands:") 31 | commands.forEach { 32 | println("${it.name}: ${it.description}") 33 | } 34 | } 35 | } 36 | 37 | private fun findCommand(name: String): Command? = commands.find { it.name == name } 38 | } 39 | 40 | data class Command(val name: String, 41 | val description: String = "", 42 | val arguments: List = emptyList(), 43 | val options: List = emptyList(), 44 | val action: ((Command, ParseResult.Parameters) -> Unit)? = null, 45 | val onError: ((Command, ParseResult.Error) -> Unit)? = null) { 46 | fun getOptionByName(name: String): Parameter.Option? { 47 | return options.find { it.name == name } 48 | } 49 | 50 | fun execute(args: List = emptyList()) { 51 | if (args.isNotEmpty() && args.first() == "--help") { 52 | showHelp() 53 | return 54 | } 55 | 56 | val parseResult = parseArgs(this, args) 57 | when (parseResult) { 58 | is ParseResult.Parameters -> action?.invoke(this, parseResult) 59 | is ParseResult.Error -> if (onError != null) onError.invoke(this, parseResult) else println(parseResult.defaultMessage) 60 | } 61 | } 62 | 63 | private fun showHelp() { 64 | println(name) 65 | if (description.isNotEmpty()) println(description) 66 | 67 | if (arguments.isNotEmpty()) { 68 | println() 69 | println("Available arguments:") 70 | arguments.forEach { 71 | println("\t${it.name}") 72 | } 73 | } 74 | 75 | if (options.isNotEmpty()) { 76 | println() 77 | println("Available options:") 78 | options.forEach { 79 | when (it) { 80 | is Parameter.Option.Switch -> println("\tSwitch \"${it.name}\"") 81 | is Parameter.Option.Value -> println("\tValue \"${it.name}\", arguments: ${it.numberArgs}, defaults: ${it.defaults}") 82 | is Parameter.Option.Choice -> println("\tChoice \"${it.name}\", choices: ${it.choices}, default: ${it.default}") 83 | } 84 | } 85 | } 86 | } 87 | } 88 | 89 | sealed class Parameter { 90 | abstract val name: String 91 | 92 | data class Argument(override val name: String) : Parameter() 93 | sealed class Option : Parameter() { 94 | data class Switch(override val name: String) : Option() 95 | data class Value(override val name: String, val numberArgs: Int = 1, val defaults: List = emptyList()) : Option() 96 | data class Choice(override val name: String, val choices: Set = emptySet(), val default: String = "") : Option() 97 | } 98 | } 99 | 100 | sealed class ParseResult { 101 | data class Parameters(val positionalArguments: Map = mapOf(), 102 | val options: Map> = mapOf()) : ParseResult() 103 | 104 | data class Error(val code: Code, val parsedValue: String = "", val defaultMessage: String) : ParseResult() { 105 | enum class Code { 106 | NO_OPTION_AVAILABLE, 107 | NOT_ENOUGH_VALUES_FOR_OPTION, 108 | MORE_POSITIONAL_ARGUMENTS_THAN_EXPECTED, 109 | POSITIONAL_ARGUMENT_AFTER_OPTION, 110 | INCORRECT_CHOICE_VALUE_PROVIDED 111 | } 112 | } 113 | } 114 | 115 | -------------------------------------------------------------------------------- /src/commonMain/kotlin/de/dbaelz/konclik/KonclikDsl.kt: -------------------------------------------------------------------------------- 1 | package de.dbaelz.konclik 2 | 3 | @DslMarker 4 | annotation class KonclikDsl 5 | 6 | /** 7 | * Creates the CLI application produced with the DSL. 8 | * @param block The lambda, which defines the CLI application. 9 | * @return The application created by the DSL. 10 | */ 11 | fun konclikApp(block: KonclikAppBuilder.() -> Unit): KonclikApp = KonclikAppBuilder().apply(block).build() 12 | 13 | 14 | /** 15 | * Creates and afterwards runs the CLI application. 16 | * It could be used as right hand side of a main function. 17 | * @param args The input args for the CLI application. 18 | * @param block The lambda, which defines the CLI application. 19 | * @return Unit so it could be used with main(). 20 | */ 21 | fun konclikApp(args: Array, block: KonclikAppBuilder.() -> Unit): Unit = 22 | KonclikAppBuilder().apply(block).build().run(args.toList()) 23 | 24 | /** 25 | * Builder for the KonclikApp. 26 | * @see KonclikApp 27 | */ 28 | @KonclikDsl 29 | class KonclikAppBuilder { 30 | private var metadata: Triple = Triple("", "", "") 31 | private var commands = mutableListOf() 32 | 33 | /** 34 | * Contains the metadata (name, description, version) of the application. 35 | * @param block The lambda with the metadata. 36 | * @see AppMetadataBuilder 37 | */ 38 | fun metadata(block: AppMetadataBuilder.() -> Unit) { 39 | metadata = AppMetadataBuilder().apply(block).build() 40 | } 41 | 42 | /** 43 | * Contains the available commands of the application. 44 | * @param block The lambda with the commands. 45 | * @see CommandBuilder 46 | */ 47 | fun command(block: CommandBuilder.() -> Unit) { 48 | commands.add(CommandBuilder().apply(block).build()) 49 | } 50 | 51 | /** 52 | * Builds the application with the provided information. 53 | * @return The created KonclikApp. 54 | */ 55 | fun build(): KonclikApp = KonclikApp(metadata.first, metadata.second, metadata.third, commands) 56 | } 57 | 58 | /** 59 | * Builder for the application metadata. 60 | * These metadata is printed in the application due the help and version parameters 61 | * @property name The optional name 62 | * @property description The optional description 63 | * @property version The version string 64 | */ 65 | @KonclikDsl 66 | class AppMetadataBuilder { 67 | var name: String = "" 68 | var description: String = "" 69 | var version: String = "" 70 | 71 | fun build(): Triple = Triple(name, description, version) 72 | } 73 | 74 | /** 75 | * Builder for the command. It includes all required arguments, options and logic which define 76 | * the input and output of the command. 77 | */ 78 | @KonclikDsl 79 | class CommandBuilder { 80 | private var metadata: Pair = Pair("", "") 81 | private var arguments = listOf() 82 | private var options = listOf() 83 | private var action: ((Command, ParseResult.Parameters) -> Unit)? = null 84 | private var onError: ((Command, ParseResult.Error) -> Unit)? = null 85 | 86 | /** 87 | * The action contains the code to execute when the command is called. 88 | * @param block A lambda with the command and the parsed/evaluated args as parameters. 89 | */ 90 | fun action(block: (command: Command, parameters: ParseResult.Parameters) -> Unit) { 91 | action = block 92 | } 93 | 94 | /** 95 | * The provided lambda is called when an error occurred due the parsing of the provided args and the 96 | * evaluation of the command. 97 | * @param block A lambda with the command and the error model as parameters. 98 | */ 99 | fun onError(block: (command: Command, error: ParseResult.Error) -> Unit) { 100 | onError = block 101 | } 102 | 103 | /** 104 | * The metadata (name, description) of the command. 105 | */ 106 | fun metadata(block: MetadataBuilder.() -> Unit) { 107 | metadata = MetadataBuilder().apply(block).build() 108 | } 109 | 110 | /** 111 | * The parameters lambda contains of two list properties: One for the positional arguments 112 | * and another for the options. 113 | * @See ParametersBuilder 114 | */ 115 | fun parameters(block: ParametersBuilder.() -> Unit) { 116 | val (arguments, options) = ParametersBuilder().apply(block).build() 117 | this.arguments = arguments 118 | this.options = options 119 | } 120 | 121 | 122 | fun build(): Command = Command(metadata.first, metadata.second, arguments, options, action, onError) 123 | } 124 | 125 | /** 126 | * The metadata of the command, containing the mandatory name and the optional description. 127 | * @property name The mandatory name, which identifies a command. 128 | * @property description The optional description. 129 | */ 130 | @KonclikDsl 131 | class MetadataBuilder { 132 | lateinit var name: String 133 | var description: String = "" 134 | 135 | fun build(): Pair = Pair(name, description) 136 | } 137 | 138 | /** 139 | * @property arguments The optional list of positional arguments. 140 | * @property options The optional list of options. 141 | */ 142 | @KonclikDsl 143 | class ParametersBuilder { 144 | var arguments = listOf() 145 | var options = listOf() 146 | 147 | fun build(): Pair, List> { 148 | return Pair(arguments, options) 149 | } 150 | } 151 | -------------------------------------------------------------------------------- /src/commonMain/kotlin/de/dbaelz/konclik/Parser.kt: -------------------------------------------------------------------------------- 1 | package de.dbaelz.konclik 2 | 3 | fun parseArgs(command: Command, args: List): ParseResult { 4 | val providedPositionalArguments = mutableMapOf() 5 | val providedOptions = mutableMapOf>() 6 | 7 | var positionalArgumentsHandled = false 8 | var argsHandledCounter = 0 9 | 10 | val argsListIterator = args.listIterator() 11 | while (argsListIterator.hasNext()) { 12 | val arg = argsListIterator.next() 13 | 14 | if (isOption(arg)) { 15 | val option = command.getOptionByName(arg) 16 | 17 | // Option found: No more position arguments from here on 18 | positionalArgumentsHandled = true 19 | 20 | if (option == null) { 21 | return ParseResult.Error(ParseResult.Error.Code.NO_OPTION_AVAILABLE, 22 | arg, "ERROR: The command has no option \"$arg\"") 23 | } 24 | 25 | when (option) { 26 | is Parameter.Option.Switch -> providedOptions[option.name] = emptyList() 27 | is Parameter.Option.Value -> { 28 | val requiredArgs = option.numberArgs - option.defaults.size 29 | if (enoughArgsProvided(args.listIterator(argsListIterator.nextIndex()), requiredArgs)) { 30 | val values = mutableListOf() 31 | while (argsListIterator.hasNext()) { 32 | val current = argsListIterator.next() 33 | if (isOption(current)) { 34 | // Next option detected: Move the cursor backwards so the arg is evaluated again 35 | argsListIterator.previous() 36 | break 37 | } else { 38 | values.add(current) 39 | } 40 | } 41 | if (values.size < option.numberArgs) { 42 | // There are less args provided then the option requires 43 | // Simply fill up with the defaults beginning with the first one 44 | values.addAll(option.defaults.subList(0, option.numberArgs - values.size)) 45 | } 46 | providedOptions[option.name] = values 47 | } else { 48 | return ParseResult.Error(ParseResult.Error.Code.NOT_ENOUGH_VALUES_FOR_OPTION, 49 | option.name, "ERROR: Not enough values provided for option \"${option.name}\"") 50 | } 51 | } 52 | is Parameter.Option.Choice -> { 53 | if (enoughArgsProvided(args.listIterator(argsListIterator.nextIndex()), 1)) { 54 | val value = argsListIterator.next() 55 | if (option.choices.contains(value)) { 56 | providedOptions[option.name] = listOf(value) 57 | } else { 58 | return ParseResult.Error(ParseResult.Error.Code.INCORRECT_CHOICE_VALUE_PROVIDED, 59 | option.name, "ERROR: Incorrect value provided for choice option \"${option.name}\"") 60 | } 61 | } else { 62 | return ParseResult.Error(ParseResult.Error.Code.NOT_ENOUGH_VALUES_FOR_OPTION, 63 | option.name, "ERROR: Not enough values provided for option \"${option.name}\"") 64 | } 65 | } 66 | } 67 | 68 | } else if (!positionalArgumentsHandled) { 69 | // It's a positional argument 70 | if (argsHandledCounter < command.arguments.size) { 71 | // Add with key = argument.name, value = arg 72 | providedPositionalArguments[command.arguments[argsHandledCounter].name] = arg 73 | argsHandledCounter++ 74 | } else { 75 | return ParseResult.Error(ParseResult.Error.Code.MORE_POSITIONAL_ARGUMENTS_THAN_EXPECTED, 76 | arg, "ERROR: More positional arguments provided than expected. Argument: \"$arg\"") 77 | } 78 | } else { 79 | return ParseResult.Error(ParseResult.Error.Code.POSITIONAL_ARGUMENT_AFTER_OPTION, 80 | arg, "ERROR: The positional arguments must precede the options. Argument: \"$arg\"") 81 | } 82 | } 83 | 84 | command.options.forEach { option -> 85 | if (providedOptions.containsKey(option.name)) { 86 | return@forEach 87 | } 88 | 89 | // For value and choice options without args provided, but with default(s): Add the default(s) 90 | when (option) { 91 | is Parameter.Option.Value -> if (option.defaults.isNotEmpty()) { 92 | providedOptions[option.name] = option.defaults 93 | } 94 | is Parameter.Option.Choice -> if (option.default.isNotEmpty()) { 95 | providedOptions[option.name] = listOf(option.default) 96 | } 97 | else -> {} 98 | } 99 | } 100 | 101 | return ParseResult.Parameters(providedPositionalArguments, providedOptions) 102 | } 103 | 104 | private fun enoughArgsProvided(iterator: ListIterator, requiredArgs: Int): Boolean { 105 | if (requiredArgs <= 0) return true 106 | 107 | var remaining = requiredArgs 108 | while (iterator.hasNext()) { 109 | if (isOption(iterator.next())) { 110 | // Next option detected. Check if enough args provided 111 | return remaining == 0 112 | } else { 113 | remaining-- 114 | } 115 | } 116 | return remaining == 0 117 | } 118 | 119 | private fun isOption(arg: String) = arg.startsWith("--") -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn () { 37 | echo "$*" 38 | } 39 | 40 | die () { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save () { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /src/commonTest/kotlin/ParserTest.kt: -------------------------------------------------------------------------------- 1 | import de.dbaelz.konclik.Command 2 | import de.dbaelz.konclik.Parameter 3 | import de.dbaelz.konclik.ParseResult 4 | import de.dbaelz.konclik.parseArgs 5 | import kotlin.test.Test 6 | import kotlin.test.assertEquals 7 | import kotlin.test.assertTrue 8 | 9 | class ParserTest { 10 | 11 | @Test 12 | fun Command_without_Parameters_and_no_args_should_return_empty_maps() { 13 | val result = parseArgs(Command("test"), emptyList()) 14 | 15 | assertTrue(result is ParseResult.Parameters) 16 | if (result is ParseResult.Parameters) { 17 | assertEquals(emptyMap(), result.positionalArguments) 18 | assertEquals(emptyMap(), result.options) 19 | } 20 | } 21 | 22 | @Test 23 | fun Command_with_defaults_and_no_args_should_return_defaults() { 24 | val command = Command("test", 25 | options = listOf(Parameter.Option.Value("--value1", 1, listOf("value1Default")), 26 | Parameter.Option.Value("--value2", 2, listOf("value2Default1", "value2Default2")), 27 | Parameter.Option.Choice("--choice1", setOf("one", "two"), "two"))) 28 | 29 | val result = parseArgs(command, emptyList()) 30 | 31 | assertTrue(result is ParseResult.Parameters) 32 | if (result is ParseResult.Parameters) { 33 | assertEquals(3, result.options.size) 34 | assertEquals(listOf("value1Default"), result.options["--value1"]) 35 | assertEquals(listOf("value2Default1", "value2Default2"), result.options["--value2"]) 36 | assertEquals(listOf("two"), result.options["--choice1"]) 37 | } 38 | } 39 | 40 | @Test 41 | fun Command_with_defaults_and_args_should_return_parsed_args() { 42 | val command = Command("test", 43 | arguments = listOf(Parameter.Argument("argument1")), 44 | options = listOf(Parameter.Option.Switch("--switch1"), 45 | Parameter.Option.Value("--value1", 1, listOf("value1Default")), 46 | Parameter.Option.Value("--value2", 2, listOf("value2Default1", "value2Default2")), 47 | Parameter.Option.Choice("--choice1", setOf("one", "two"), "two"))) 48 | val args = listOf("someargument", "--switch1", "--value1", "value1Something", "--value2", "value2Something", "--choice1", "one") 49 | 50 | val result = parseArgs(command, args) 51 | 52 | assertTrue(result is ParseResult.Parameters) 53 | if (result is ParseResult.Parameters) { 54 | assertEquals(1, result.positionalArguments.size) 55 | assertEquals("someargument", result.positionalArguments["argument1"]) 56 | 57 | assertEquals(4, result.options.size) 58 | assertEquals(emptyList(), result.options["--switch1"]) 59 | assertEquals(listOf("value1Something"), result.options["--value1"]) 60 | assertEquals(listOf("value2Something", "value2Default1"), result.options["--value2"]) 61 | assertEquals(listOf("one"), result.options["--choice1"]) 62 | } 63 | } 64 | 65 | 66 | // Parsing: Error Cases 67 | 68 | @Test 69 | fun Option_not_available() { 70 | val command = Command("test", 71 | options = listOf(Parameter.Option.Value("--value1", 1, listOf("value1Default")))) 72 | val args = listOf("--value1", "value1Something", "--value2", "value2Something") 73 | 74 | val result = parseArgs(command, args) 75 | 76 | assertTrue(result is ParseResult.Error) 77 | if (result is ParseResult.Error) { 78 | assertEquals(ParseResult.Error.Code.NO_OPTION_AVAILABLE, result.code) 79 | } 80 | } 81 | 82 | @Test 83 | fun Not_enough_values_for_value_option() { 84 | val command = Command("test", 85 | options = listOf(Parameter.Option.Value("--value1", 2, emptyList()))) 86 | val args = listOf("--value1", "somevalue") 87 | 88 | val result = parseArgs(command, args) 89 | 90 | assertTrue(result is ParseResult.Error) 91 | if (result is ParseResult.Error) { 92 | assertEquals(ParseResult.Error.Code.NOT_ENOUGH_VALUES_FOR_OPTION, result.code) 93 | } 94 | } 95 | 96 | @Test 97 | fun No_value_provided_for_choice_option() { 98 | val command = Command("test", 99 | options = listOf(Parameter.Option.Choice("--value1", setOf("one", "two")))) 100 | val args = listOf("--value1") 101 | 102 | val result = parseArgs(command, args) 103 | 104 | assertTrue(result is ParseResult.Error) 105 | if (result is ParseResult.Error) { 106 | assertEquals(ParseResult.Error.Code.NOT_ENOUGH_VALUES_FOR_OPTION, result.code) 107 | } 108 | } 109 | 110 | @Test 111 | fun Incorrect_value_provided_for_choice_option() { 112 | val command = Command("test", 113 | options = listOf(Parameter.Option.Choice("--value1", setOf("one", "two")))) 114 | val args = listOf("--value1", "three") 115 | 116 | val result = parseArgs(command, args) 117 | 118 | assertTrue(result is ParseResult.Error) 119 | if (result is ParseResult.Error) { 120 | assertEquals(ParseResult.Error.Code.INCORRECT_CHOICE_VALUE_PROVIDED, result.code) 121 | } 122 | } 123 | 124 | @Test 125 | fun More_positional_arguments_provided_than_expected() { 126 | val command = Command("test", 127 | arguments = listOf(Parameter.Argument("argument1"))) 128 | val args = listOf("somearg", "anotherarg") 129 | 130 | val result = parseArgs(command, args) 131 | 132 | assertTrue(result is ParseResult.Error) 133 | if (result is ParseResult.Error) { 134 | assertEquals(ParseResult.Error.Code.MORE_POSITIONAL_ARGUMENTS_THAN_EXPECTED, result.code) 135 | } 136 | } 137 | 138 | @Test 139 | fun Positional_argument_after_option() { 140 | val command = Command("test", 141 | arguments = listOf(Parameter.Argument("argument1")), 142 | options = listOf(Parameter.Option.Switch("--switch1"), 143 | Parameter.Option.Value("--value1", 1, listOf("value1Default")))) 144 | val args = listOf("--switch1", "someargument", "--value1", "value1Something") 145 | 146 | val result = parseArgs(command, args) 147 | 148 | assertTrue(result is ParseResult.Error) 149 | if (result is ParseResult.Error) { 150 | assertEquals(ParseResult.Error.Code.POSITIONAL_ARGUMENT_AFTER_OPTION, result.code) 151 | } 152 | } 153 | } 154 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | --------------------------------------------------------------------------------