| 1 | | import Foundation |
| 2 | | |
| 3 | | /// The `--option value` pairs, preserving repeated values in argument order. |
| 4 | | struct OptionValues { |
| 5 | 24 | private var values: [String: [String]] = [:] |
| 6 | | |
| 7 | | /// - Throws: `ReportOptionsError` for an option outside `allowed` or without its value. |
| 8 | 24 | init(arguments: [String], allowed: Set<String>) throws { |
| 9 | 24 | var index = arguments.startIndex |
| 10 | 88 | while index < arguments.endIndex { |
| 11 | 70 | let option = arguments[index] |
| 12 | 70 | guard allowed.contains(option) else { |
| 13 | 3 | throw ReportOptionsError.unknownOption(option) |
| 14 | 67 | } |
| 15 | 67 | guard index + 1 < arguments.endIndex else { |
| 16 | 3 | throw ReportOptionsError.missingValue(option: option) |
| 17 | 64 | } |
| 18 | 64 | values[option, default: []].append(arguments[index + 1]) |
| 19 | 64 | index += 2 |
| 20 | 64 | } |
| 21 | 18 | } |
| 22 | | |
| 23 | 99 | subscript(option: String) -> String? { values[option]?.last } |
| 24 | | |
| 25 | 10 | func all(_ option: String) -> [String] { values[option] ?? [] } |
| 26 | | |
| 27 | 34 | func required(_ option: String) throws -> String { |
| 28 | 34 | guard let value = self[option] else { throw ReportOptionsError.missingOption(option) } |
| 29 | 29 | return value |
| 30 | 34 | } |
| 31 | | |
| 32 | | /// Accepts only web destinations, never executable URL schemes. |
| 33 | 11 | func runURL() throws -> String? { |
| 34 | 11 | guard let value = self["--run-url"] else { return nil } |
| 35 | 3 | guard let url = URL(string: value), ["https", "http"].contains(url.scheme?.lowercased()), |
| 36 | 3 | url.host != nil |
| 37 | 3 | else { throw ReportOptionsError.invalidRunURL(value) } |
| 38 | 2 | return value |
| 39 | 11 | } |
| 40 | | } |