Sources/OrgstarCLI/Arguments.swift
45 lines · 2031 bytes
1/// A command's words after its name: positional arguments, flags, and options with a value,
2/// as `--name value` or `--name=value`. `--` ends the options.
3struct Arguments {
4 var positional: [String] = []
5 var flags: Set<String> = []
6 var options: [String: [String]] = [:]
7
8 /// `aliases` maps short names, such as `-o`, to long ones.
9 init(_ words: [String], command: String, flags known: Set<String>, options takes: Set<String> = [], aliases: [String: String] = [:]) throws(Failure) {
10 var rest = words[...]
11 while let word = rest.popFirst() {
12 if word == "--" {
13 positional += rest
14 break
15 }
16 guard word.hasPrefix("-"), word != "-" else {
17 positional.append(word)
18 continue
19 }
20 var name = word
21 var value: String?
22 if let equals = word.firstIndex(of: "="), word.hasPrefix("--") {
23 name = String(word[..<equals])
24 value = String(word[word.index(after: equals)...])
25 }
26 name = aliases[name] ?? name
27 if known.contains(name), value == nil {
28 flags.insert(name)
29 } else if takes.contains(name) {
30 guard let given = value ?? rest.popFirst() else { throw Failure(.usage, "\(command): \(name) needs a value") }
31 options[name, default: []].append(given)
32 } else {
33 throw Failure(.usage, "\(command): unknown option \(word)")
34 }
35 }
36 }
37
38 func value(_ name: String) -> String? { options[name]?.last }
39
40 /// Throws unless there are between `min` and `max` positional arguments.
41 func expect(_ min: Int, _ max: Int, _ command: String) throws(Failure) {
42 if positional.count < min { throw Failure(.usage, "\(command): missing argument; see orgstar \(command) --help") }
43 if positional.count > max { throw Failure(.usage, "\(command): unexpected argument \(positional[max])") }
44 }
45}