Scoop API

scoop:scoop.cli:0.1.0

src/cli.scoop

Selected production source · src/cli.scoop

1package scoop.cli
3/** Program name and summary displayed in help. */
4public struct CliConfig(val programName: String, val summary: String = "")
6/** How tokens identify a field. Positional indices start at zero. */
7public enum CliRole { Option, Flag, Argument(Long) }
9/** Acceptable text for each occurrence of a repeated field. */
10public enum CliElementShape { Text, Choice(Array<String>) }
12/** How the token reader collects one field. */
13public enum CliValueShape { Text, Flag, Choice(Array<String>), Repeated(CliElementShape) }
15/** Layout and help text for one field. defaultText is for display only. */
16public struct CliEntry(
17 val sourceName: String, val role: CliRole, val valueShape: CliValueShape,
18 val names: Array<String> = [], val negativeNames: Array<String> = [],
19 val help: String = "", val valueName: String = "", val defaultText: String = "",
20 val required: Boolean = true, val hasDefault: Boolean = false
23/** Declares the argument layout and binds collected fields to an application value. */
24public interface CliArguments<T> {
25 public fun entries(): Array<CliEntry>
26 public fun bind(values: CliValues): T
29/** Declares how to collect and convert one field, including user-defined field types. */
30public interface CliValueParser<T> {
31 public fun shape(): CliValueShape
32 public fun parseValue(values: CliFieldValues): T
35/** The argv scan either produces an application value or requests help. */
36public enum CliResult<T> { Parsed(T), HelpRequested }
38/** Validates the layout once and reuses it for subsequent parsing and help. */
39public class CliParser<T> public constructor(
40 private val config: CliConfig, private val arguments: CliArguments<T>
41) {
42 private val layout: CliLayout = checkedEntries(arguments.entries())
43 public val entries: Array<CliEntry> get() = layout.entries
45 /** Parse arguments starting at the first option or positional value. */
46 public fun parse(argv: Array<String>): CliResult<T> = parseFrom(argv, 0L)
48 /** Parse complete argv including the program name at index zero. */
49 public fun parseCommandLine(argv: Array<String>): CliResult<T> {
50 if (argv.size == 0L) { inputError("", None, "complete argv requires a program item") }
51 return parseFrom(argv, 1L)
52 }
54 private fun parseFrom(argv: Array<String>, start: Long): CliResult<T> =
55 when (CliTokens(entries, layout.positions, argv, start).parse()) {
56 case CliInputResult.Help -> CliResult.HelpRequested
57 case CliInputResult.Value(val values) -> CliResult.Parsed(arguments.bind(values))
58 }
60 public fun writeHelp(writer: TextWriter): Unit = writeCliHelp(config, entries, layout.positions, writer)
61 public fun help(): String {
62 val writer = StringWriter()
63 writeHelp(writer)
64 return writer.toString()
65 }