在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称(OpenSource Name):xenomachina/kotlin-argparser开源软件地址(OpenSource Url):https://github.com/xenomachina/kotlin-argparser开源编程语言(OpenSource Language):Kotlin 72.5%开源软件介绍(OpenSource Introduction):This is a library for parsing command-line arguments. It can parse both options and positional arguments. It aims to be easy to use and concise yet powerful and robust. OverviewDefining options and positional arguments is as simple as: import com.xenomachina.argparser.ArgParser
class MyArgs(parser: ArgParser) {
val v by parser.flagging("enable verbose mode")
val name by parser.storing("name of the user")
val count by parser.storing("number of the widgets") { toInt() }
val source by parser.positional("source filename")
val destination by parser.positional("destination filename")
} An instance of The name of an option is inferred from the name of the property it is bound to.
The options above are named Direct control over an option's name is also possible, and for most types of options it is also possible to have multiple names, like a short and long name: class MyArgs(parser: ArgParser) {
val verbose by parser.flagging(
"-v", "--verbose",
help = "enable verbose mode")
val name by parser.storing(
"-N", "--name",
help = "name of the user")
val count by parser.storing(
"-c", "--count",
help = "number of widgets") { toInt() }
val source by parser.positional(
"SOURCE",
help = "source filename")
val destination by parser.positional(
"DEST",
help = "destination filename")
} The unparsed command-line arguments are passed to the fun main(args: Array<String>) = mainBody {
ArgParser(args).parseInto(::MyArgs).run {
println("Hello, ${name}!")
println("I'm going to move ${count} widgets from ${source} to ${destination}.")
// TODO: move widgets
}
} See kotlin-argparser-example for a complete example project. NomenclatureOptions, arguments, flags... what's the difference? An application's The unparsed arguments can then be parsed into options, which start
with a hyphen (" Options can also have option arguments. In the command A flag is a boolean option which has no arguments and which is false if not
provided, but true if provided. The Option TypesBoolean FlagsBoolean flags are created by asking the parser for a val verbose by parser.flagging("-v", "--verbose",
help = "enable verbose mode") Here the presence of either Storing a Single ArgumentSingle argument options are created by asking the parser for a
val name by parser.storing("-N", "--name",
help = "name of the user") Here either A function can also be supplied to transform the argument into the desired
type. Here the val size by parser.storing("-c", "--count",
help = "number of widgets") { toInt() } Adding to a CollectionOptions that add to a val includeDirs by parser.adding(
"-I", help = "directory to search for header files") { File(this) } Now each time the Mapping from an option to a fixed valueFor choosing between a fixed set of values (typically, but not necessarily,
from an enum), a val mode by parser.mapping(
"--fast" to Mode.FAST,
"--small" to Mode.SMALL,
"--quiet" to Mode.QUIET,
help = "mode of operation") Here the
More advanced optionsFor all other types of options, the For example, it is possible to create an option that has multiple arguments: fun ArgParser.putting(vararg names: String, help: String) =
option<MutableMap<String, String>>(*names,
argNames = listOf("KEY", "VALUE"),
help = help) {
value.orElse { mutableMapOf<String, String>() }.apply {
put(arguments.first(), arguments.last()) }
} Note that the fun ArgParser.putting(help: String) =
ArgParser.DelegateProvider { identifier ->
putting(identifierToOptionName(identifier), help = help) } Positional ArgumentsPositional arguments are collected by using the For a single positional argument: val destination by parser.positional("destination filename") An explicit name may also be specified: val destination by parser.positional("DEST",
help = "destination filename") The name ("DEST", here) is used in error handling and help text. For a list of positional arguments: val sources by parser.positionalList("SOURCE", 1..Int.MAX_VALUE,
help = "source filename") The range indicates how many arguments should be collected, and defaults to the
value shown in this example. As the name suggests, the resulting property will
be a Both of these methods accept an optional transform function for converting
arguments from val destination by parser.positional("DEST",
help = "...") { File(this) }
val sources by parser.positionalList("SOURCE", 1..Int.MAX_VALUE,
help = "...") { File(this) } Modifying DelegatesThe delegates returned by any of these methods also have a few methods for setting optional attributes: Adding a Default ValueCertain types of delegates (notably val name by parser.storing("-N", "--name", help = "...").default("John Doe") Note that it is possible to use val name by parser.storing("-N", "--name", help = "...").default<String?>(null) The type of the resulting property be nullable (a Adding a ValidatorSometimes it's easier to validate an option at the end of parsing, in which
case the val percentages by parser.adding("--percentages", help = "...") { toInt() }
.addValidator {
if (value.sum() != 100)
throw InvalidArgumentException(
"Percentages must add up to 100%")
} Error HandlingIf the parser determines that execution should not continue it will throw a
These exceptions can be caused by user error, or even if the user requests help
(eg: via the It is recommended that transform functions (given to As a convenience, these exceptions can be handled by using the class ParsedArgs(parser: ArgParser) {
val name by positional("The user's name").default("world")
}
fun main(args: Array<String>) = mainBody {
ArgParser(args).parseInto(::ParsedArgs).run {
println("Hello, {name}!")
}
} ParsingParsing of command-line arguments is performed sequentially. So long as
option-processing is enabled, each not-yet-processed command-line argument that
starts with a hyphen ( Short OptionsShort options start with a single hyphen. If the option takes an argument, the argument can either be appended: # "-o" with argument "ARGUMENT"
my_program -oARGUMENT or can be the following command-line argument: # "-o" with argument "ARGUMENT"
my_program -o ARGUMENT Zero argument short options can also be appended to each other without intermediate hyphens: # "-x", "-y" and "-z" options
my_program -xyz An option that accepts arguments is also allowed at the end of such a chain: # "-x", "-y" and "-z" options, with argument for "-z"
my_program -xyzARGUMENT Long OptionsLong options start with a double hyphen ( # "--foo" with argument "ARGUMENT"
my_program --foo=ARGUMENT or can be the following command-line argument: # "--foo" with argument "ARGUMENT"
my_program --foo ARGUMENT Multi-argument OptionsMulti-argument options are supported, though currently not by any of the convenience methods. Option-arguments after the first must be separate command-line arguments, for both an long and short forms of an option. Positional ArgumentsIn GNU mode (the default), options can be interspersed with positional arguments, but in POSIX mode the first positional argument that is encountered disables option processing for the remaining arguments. In either mode, if the argument "--" is encountered while option processing is enabled, then option processing is disabled for the rest of the command-line. Once the options and option-arguments have been eliminated, what remains are considered to be positional arguments. Each positional argument delegate can specify a minimum and maximum number of arguments it is willing to collect. The positional arguments are distributed to the delegates by allocating each positional delegate at least as many arguments as it requires. If more than the minimum number of positional arguments have been supplied then additional arguments will be allocated to the first delegate up to its maximum, then the second, and so on, until all arguments have been allocated to a delegate. This makes it easy to create a program that behaves like class Args(parser: ArgParser) {
// accept 1 regex followed by n filenames
val regex by parser.positional("REGEX",
help = "regular expression to search for")
val files by parser.positionalList("FILE",
help = "file to search in")
} And equally easy to create a program that behaves like class Args(parser: ArgParser) {
// accept n source files followed by 1 destination
val sources by parser.positionalList("SOURCE",
help = "source file")
val destination by parser.positional("DEST",
help = "destination file")
} Forcing ParsingParsing normally does not begin until a delegate's value is accessed. Sometimes this is not desirable, so it is possible to enforce the parsing of arguments into a class of values. This ensures that all arguments that are required are provided, and all arguments provided are consumed. Forcing can be done in a separate step using the val parser = ArgParser(args)
val parsedArgs = ParsedArgs(parser)
parser.force()
// now you can use parsedArgs Alternatively, forcing can be done inline via the val parsedArgs = ArgParser(args).parseInto(::ParsedArgs)
// now you can use parsedArgs In both cases exceptions will be thrown where parsing or validation errors are found. Help FormattingBy default,
The creation of the Caveats
Configuring Your BuildKotlin-argparser binaries are hosted on Maven Central and also Bintray's JCenter. In Gradle, add something like this in your // you probably already have this part
buildscript {
repositories {
mavenCentral() // or jcenter()
}
}
dependencies {
compile "com.xenomachina:kotlin-argparser:$kotlin_argparser_version"
} In Maven add something like this to your <dependency>
<groupId>com.xenomachina</groupId>
<artifactId>kotlin-argparser</artifactId>
<version>VERSION</version>
</dependency> Information on setting up other build systems, as well as the current version number, can be found on MVN Repository's page for Kotlin-argparser. ThanksThanks to the creators of Python's
Thanks also to the team behind Kotlin. Finally, thanks to all of the people who have contributed code and/or issues. |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论