A simple Kotlin option parser

Related tags

Utility kopper
Overview

Kopper

A simple Kotlin option parser

Maven Central

Maven Central

kopper is the simple Kotlin option parser library.

kopper-typed extends the kopper library to support delegated properties and parsing as simple as constructing an object. It includes the additional dependency of kotlin-reflect.

Examples

Manual parsing…

import us.jimschubert.kopper.*

fun main(args: Array<String>) {
    val parser = Parser()
    parser.setName("Kopper CLI")
    parser.setApplicationDescription("Kopper example application")

    parser.flag("q", listOf("quiet", "silent"), description = "Run silently")
    parser.option("f", listOf("file"), description = "File name")
    parser.flag("a", listOf("allowEmpty"))

    println(parser.printHelp())

    val arguments = parser.parse(arrayOf("-f", "asdf.txt", "--quiet=true", "trailing", "arguments" ))

    println("q=${arguments.flag("q")}")
    println("quiet=${arguments.flag("quiet")}")
    println("silent=${arguments.flag("silent")}")
    println("f=${arguments.option("f")}")
    println("file=${arguments.option("file")}")
    println("allowEmpty=${arguments.flag("allowEmpty")}")
    println("unparsedArgs=${arguments.unparsedArgs.joinToString()}")
}

Parser objects…

fun main(args: Array<String>) {
    val arguments = ExampleArgs(args)

    if (arguments.help) {
        println(arguments.printHelp())
        return
    }

    println("quiet=${arguments.quiet}")
    println("rate=${arguments.rate}")
    println("maxCount=${arguments.maxCount}")
}

class ExampleArgs(args: Array<String>) : TypedArgumentParser(args) {

    val quiet by BooleanArgument(self, "q",
            default = true,
            longOption = listOf("quiet", "silent"),
            description = "Run quietly"
    )

    val rate by NumericArgument(self, "r", 
            default = 1.0f, 
            description = "Rate"
    )

    val maxCount by NumericArgument(self, "m", 
            longOption = listOf("maxCount"), 
            default = 10, 
            description = "Max Count"
    )
}

Typed parser objects support BooleanArgument, StringArgument, and NumericArgument<T> property delegates. They also expose any additional args as a list of strings in the _etc_ property.

License

MIT License

Comments
  • Make `Parser.parse()` return an object

    Make `Parser.parse()` return an object

    I find it counter intuitive that Parser.parse() does not return anything. I think it should return an object of some kind which holds the information that is in the options and _args fields. Further, I think it would be good if Parser objects were immutable.

    opened by fwilhe 8
  • Weird default value behavior

    Weird default value behavior

    When defining a string option with default value, the default will be applied only if the option appears on the command line without explicit value parameter. Otherwise the delegate returns an empty string.

    I find this counter-intuitive; I would rather expect that omitting the value in the arguments will cause the default value to be used and using a string option without value will either also return the default or throw an error ("option -x requires a parameter").

    In case this is intended, it would be nice to have it configurable.

    opened by SpaceBison 2
  • Gradle-import in IntelliJ fails because of missing property ossrhUsername

    Gradle-import in IntelliJ fails because of missing property ossrhUsername

    When I import the project into intellij, it fails with this message:

    Error:(63, 0) Could not get unknown property 'ossrhUsername' for object of type org.gradle.api.publication.maven.internal.deployer.DefaultGroovyMavenDeployer.

    It should be tested if the property exists before it is used.

    opened by fwilhe 1
  • printHelp should take a PrintStream and handle the write itself

    printHelp should take a PrintStream and handle the write itself

    rather than TypedArgumentParser#printHelp and Parser#printHelp returning String, they should accept a PrintStream and write out each line directly to the stream.

    enhancement 
    opened by jimschubert 0
  • Support name/applicationDescription in typed parser objects

    Support name/applicationDescription in typed parser objects

    As of v0.0.2, typed objects only support options/flags. They should also support setting metadata for printed help in the same was as the manual setup.

    bug 
    opened by jimschubert 0
  • Return ArgumentCollection from parse

    Return ArgumentCollection from parse

    This separates the definition of options (what's available to a user) from the associated arguments (what's provided by the user).

    Included documentation on public methods.

    See #2

    opened by jimschubert 0
Releases(v0.0.3)
  • v0.0.3(Dec 31, 2016)

    Enhance:

    • (see #6) Update printHelp to write directly to a PrintStream instance

    Bug:

    • (fix #5) TypedArgumentParser now allows setting name and applicationDescription via optional constructor parameters
    Source code(tar.gz)
    Source code(zip)
  • v0.0.2(Dec 13, 2016)

    • Modify Parser to support method chanining (f5e0320)
      • changes #name and #applicationDescription pubic properties to setter methods.
    • Return ArgumentCollection from parse (d542dca)
      • moves Parser#isSet and Parser#get to new ArgumentCollection
      • ArgumentCollection is a true collection

    … and other non-feature commits.

    Source code(tar.gz)
    Source code(zip)
  • v0.0.1(Dec 13, 2016)

Owner
Jim Schubert
Core team and founding member of OpenAPI Generator. C#, Kotlin, Scala Java, JavaScript
Jim Schubert
APK parser for Android

APK Parser Features Retrieve basic apk metas, such as title, icon, package name, version, etc. Parse and convert binary xml file to text Classes from

Jared Rummler 613 Dec 20, 2022
Apk parser for java

APK parser lib, for decoding binary XML files, getting APK meta info. Table of Contents Features Get APK-parser Usage 1. APK Info 2. Get Binary XML an

Hsiafan 1.1k Dec 18, 2022
Parser and Expression Evaluator for Logic Statements

LogicParser Parser and Expression Evaluator for Logic Statements: The steps behind the whole process of evaluating a given logic statement encompass:

Bărbuț-Dică Sami 1 Dec 8, 2021
🧹 Error correcting parser plugin

Tidyparse The main goal of this project is to speed up the process of learning a new language by suggesting ways to fix source code. Tidyparse expects

breandan 5 Dec 15, 2022
UE Capability parser used by smartphonecombo.it and cacombos.com

UE Capability Parser Warning Work In progress UE Capability parser used by smartphonecombo.it and cacombos.com $ java -jar uecapabilityparser.jar --he

Andrea Mennillo 4 Oct 16, 2022
Simple-Claim-Form - Android App for creating a simple dynamic form with MVVM architecture

Simple-Claim-Form Android App for creating a simple dynamic form with MVVM archi

Shubham Gangpuri 1 Aug 14, 2022
nestegg - Very simple Kotlin caching library

nestegg - Very simple Kotlin caching library

Runner-be 4 Jun 15, 2022
DiskCache - Simple and readable disk cache for kotlin and android applications

DiskCache Simple and readable disk cache for kotlin and android applications (with journaled lru strategy) This is a simple lru disk cache, based on t

Giovanni Corte 14 Dec 2, 2022
a simple cache for android and java

ASimpleCache ASimpleCache 是一个为android制定的 轻量级的 开源缓存框架。轻量到只有一个java文件(由十几个类精简而来)。 1、它可以缓存什么东西? 普通的字符串、JsonObject、JsonArray、Bitmap、Drawable、序列化的java对象,和 b

Michael Yang 3.7k Dec 14, 2022
✔️ Secure, simple key-value storage for Android

Hawk 2.0 Secure, simple key-value storage for android Important Note This version has no backward compatibility with Hawk 1+ versions. If you still wa

Orhan Obut 3.9k Dec 20, 2022
A simple library for validating user input in forms using annotations.

ValidationKomensky for Android A simple library for validating user input in forms using annotations. Features: Validate all views at once and show fe

Inmite s.r.o. 512 Nov 20, 2022
Create a simple and more understandable Android logs.

DebugLog Create a simple and more understandable Android logs. #Why? android.util.Log is the most usable library of the Android. But, when the app rel

mf 418 Nov 25, 2022
A small library which will save you from writing the same intent creation code again and again for the most simple tasks

Android Intents A small library which will save you from writing the same intent creation code again and again for the most simple tasks. I found myse

MarvinLabs 420 Nov 20, 2022
A simple Android utils library to write any type of data into cache files and read them later.

CacheUtilsLibrary This is a simple Android utils library to write any type of data into cache files and then read them later, using Gson to serialize

Wesley Lin 134 Nov 25, 2022
Ask Permission - Simple RunTime permission manager

Ask Permission https://kishanjvaghela.github.io/Ask-Permission/ Simple RunTime permission manager How to use Add url to your gradle file compile 'com.

Kishan Vaghela 77 Nov 18, 2022
A simple and easy to use stopwatch and timer library for android

TimeIt Now with Timer support! A simple and easy to use stopwatch and timer library for android Introduction A stopwatch can be a very important widge

Yashovardhan Dhanania 35 Dec 10, 2022
A helper library to ease the most repetitive codes with simple reusable attributes.

ak-universal-android-helper A helper library to ease the most repetitive codes with simple reusable attributes. AKUAH can help you with many repetitiv

Aakash Kumar 20 Jul 8, 2020
Trail is a simple logging system for Java and Android. Create logs using the same API and the library will detect automatically in which platform the code is running.

Trail Trail is a simple logging system for Java and Android. Create logs using the same API and the library will detect automatically in which platfor

Mauricio Togneri 13 Aug 29, 2022
Expirable Disk Lru Cache is a secure(with encryption) wrapper for [DiskLruCache](https://github.com/JakeWharton/DiskLruCache) that allows expiring of key/value pairs by specifying evictionTimeSpan. It has very simple API.

ExpirableDiskLruCache ExpirableDiskLruCache is a wrapper for DiskLruCache that allows expiring of key/value pairs by specifying evictionTimeSpan. It h

Vijay Rawat 24 Oct 3, 2022