forked from apple/swift-argument-parser
/
ArgumentDefinition.swift
431 lines (385 loc) · 12.2 KB
/
ArgumentDefinition.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
//===----------------------------------------------------------*- swift -*-===//
//
// This source file is part of the Swift Argument Parser open source project
//
// Copyright (c) 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
struct ArgumentDefinition {
/// A closure that modifies a `ParsedValues` instance to include this
/// argument's value.
enum Update {
typealias Nullary = (InputOrigin, Name?, inout ParsedValues) throws -> Void
typealias Unary = (InputOrigin, Name?, String, inout ParsedValues) throws -> Void
/// An argument that gets its value solely from its presence.
case nullary(Nullary)
/// An argument that takes a string as its value.
case unary(Unary)
}
typealias Initial = (InputOrigin, inout ParsedValues) throws -> Void
enum Kind {
/// An option or flag, with a name and an optional value.
case named([Name])
/// A positional argument.
case positional
/// A pseudo-argument that takes its value from a property's default value
/// instead of from command-line arguments.
case `default`
}
struct Help {
struct Options: OptionSet {
var rawValue: UInt
static let isOptional = Options(rawValue: 1 << 0)
static let isRepeating = Options(rawValue: 1 << 1)
}
var options: Options
var defaultValue: String?
var keys: [InputKey]
var allValues: [String]
var isComposite: Bool
var abstract: String
var discussion: String
var valueName: String
var visibility: ArgumentVisibility
var parentTitle: String
init(
allValues: [String],
options: Options,
help: ArgumentHelp?,
defaultValue: String?,
key: InputKey,
isComposite: Bool
) {
self.options = options
self.defaultValue = defaultValue
self.keys = [key]
self.allValues = allValues
self.isComposite = isComposite
self.abstract = help?.abstract ?? ""
self.discussion = help?.discussion ?? ""
self.valueName = help?.valueName ?? ""
self.visibility = help?.visibility ?? .default
self.parentTitle = ""
}
}
/// This folds the public `ArrayParsingStrategy` and `SingleValueParsingStrategy`
/// into a single enum.
enum ParsingStrategy {
/// Expect the next `SplitArguments.Element` to be a value and parse it. Will fail if the next
/// input is an option.
case `default`
/// Parse the next `SplitArguments.Element.value`
case scanningForValue
/// Parse the next `SplitArguments.Element` as a value, regardless of its type.
case unconditional
/// Parse multiple `SplitArguments.Element.value` up to the next non-`.value`
case upToNextOption
/// Parse all remaining `SplitArguments.Element` as values, regardless of its type.
case allRemainingInput
}
var kind: Kind
var help: Help
var completion: CompletionKind
var parsingStrategy: ParsingStrategy
var update: Update
var initial: Initial
var names: [Name] {
switch kind {
case .named(let n): return n
case .positional, .default: return []
}
}
var valueName: String {
help.valueName.mapEmpty {
names.preferredName?.valueString
?? help.keys.first?.rawValue.convertedToSnakeCase(separator: "-")
?? "value"
}
}
init(
kind: Kind,
help: Help,
completion: CompletionKind,
parsingStrategy: ParsingStrategy = .default,
update: Update,
initial: @escaping Initial = { _, _ in }
) {
if case (.positional, .nullary) = (kind, update) {
preconditionFailure("Can't create a nullary positional argument.")
}
self.kind = kind
self.help = help
self.completion = completion
self.parsingStrategy = parsingStrategy
self.update = update
self.initial = initial
}
}
extension ArgumentDefinition: CustomDebugStringConvertible {
var debugDescription: String {
switch (kind, update) {
case (.named(let names), .nullary):
return names
.map { $0.synopsisString }
.joined(separator: ",")
case (.named(let names), .unary):
return names
.map { $0.synopsisString }
.joined(separator: ",")
+ " <\(valueName)>"
case (.positional, _):
return "<\(valueName)>"
case (.default, _):
return ""
}
}
}
extension ArgumentDefinition {
var optional: ArgumentDefinition {
var result = self
result.help.options.insert(.isOptional)
return result
}
var nonOptional: ArgumentDefinition {
var result = self
result.help.options.remove(.isOptional)
return result
}
}
extension ArgumentDefinition {
var isPositional: Bool {
if case .positional = kind {
return true
}
return false
}
var isRepeatingPositional: Bool {
isPositional && help.options.contains(.isRepeating)
}
var isNullary: Bool {
if case .nullary = update {
return true
} else {
return false
}
}
var allowsJoinedValue: Bool {
names.contains(where: { $0.allowsJoined })
}
}
extension ArgumentDefinition.Kind {
static func name(key: InputKey, specification: NameSpecification) -> ArgumentDefinition.Kind {
let names = specification.makeNames(key)
return ArgumentDefinition.Kind.named(names)
}
}
// MARK: - Common @Argument, @Option, Unparsed Initializer Path
extension ArgumentDefinition {
// MARK: Unparsed Keys
/// Creates an argument definition for a property that isn't parsed from the
/// command line.
///
/// This initializer is used for any property defined on a `ParsableArguments`
/// type that isn't decorated with one of ArgumentParser's property wrappers.
init(unparsedKey: String, default defaultValue: Any?) {
self.init(
container: Bare<Any>.self,
key: InputKey(rawValue: unparsedKey),
kind: .default,
allValues: [],
help: .private,
defaultValueDescription: nil,
parsingStrategy: .default,
parser: { (key, origin, name, valueString) in
throw ParserError.unableToParseValue(
origin, name, valueString, forKey: key, originalError: nil)
},
initial: defaultValue,
completion: nil)
}
init<Container>(
container: Container.Type,
key: InputKey,
kind: ArgumentDefinition.Kind,
help: ArgumentHelp?,
parsingStrategy: ParsingStrategy,
initial: Container.Initial?,
completion: CompletionKind?
) where Container: ArgumentDefinitionContainerExpressibleByArgument {
self.init(
container: Container.self,
key: key,
kind: kind,
allValues: Container.Contained.allValueStrings,
help: help,
defaultValueDescription: Container.defaultValueDescription(initial),
parsingStrategy: parsingStrategy,
parser: { (key, origin, name, valueString) -> Container.Contained in
guard let value = Container.Contained(argument: valueString) else {
throw ParserError.unableToParseValue(
origin, name, valueString, forKey: key, originalError: nil)
}
return value
},
initial: initial,
completion: completion ?? Container.Contained.defaultCompletionKind)
}
init<Container>(
container: Container.Type,
key: InputKey,
kind: ArgumentDefinition.Kind,
help: ArgumentHelp?,
parsingStrategy: ParsingStrategy,
transform: @escaping (String) throws -> Container.Contained,
initial: Container.Initial?,
completion: CompletionKind?
) where Container: ArgumentDefinitionContainer {
self.init(
container: Container.self,
key: key,
kind: kind,
allValues: [],
help: help,
defaultValueDescription: nil,
parsingStrategy: parsingStrategy,
parser: { (key, origin, name, valueString) -> Container.Contained in
do {
return try transform(valueString)
} catch {
throw ParserError.unableToParseValue(
origin, name, valueString, forKey: key, originalError: error)
}
},
initial: initial,
completion: completion)
}
private init<Container>(
container: Container.Type,
key: InputKey,
kind: ArgumentDefinition.Kind,
allValues: [String],
help: ArgumentHelp?,
defaultValueDescription: String?,
parsingStrategy: ParsingStrategy,
parser: @escaping (InputKey, InputOrigin, Name?, String) throws -> Container.Contained,
initial: Container.Initial?,
completion: CompletionKind?
) where Container: ArgumentDefinitionContainer {
self.init(
kind: kind,
help: .init(
allValues: allValues,
options: Container.helpOptions.union(initial != nil ? [.isOptional] : []),
help: help,
defaultValue: defaultValueDescription,
key: key,
isComposite: false),
completion: completion ?? .default,
parsingStrategy: parsingStrategy,
update: .unary({ (origin, name, valueString, parsedValues) in
let value = try parser(key, origin, name, valueString)
Container.update(
parsedValues: &parsedValues,
value: value,
key: key,
origin: origin)
}),
initial: { origin, values in
let inputOrigin: InputOrigin
switch kind {
case .default:
inputOrigin = InputOrigin(element: .defaultValue)
case .named, .positional:
inputOrigin = origin
}
values.set(initial, forKey: key, inputOrigin: inputOrigin)
})
}
}
// MARK: - Abstraction over T, Option<T>, Array<T>
protocol ArgumentDefinitionContainer {
associatedtype Contained
associatedtype Initial
static var helpOptions: ArgumentDefinition.Help.Options { get }
static func update(
parsedValues: inout ParsedValues,
value: Contained,
key: InputKey,
origin: InputOrigin)
}
protocol ArgumentDefinitionContainerExpressibleByArgument:
ArgumentDefinitionContainer where Contained: ExpressibleByArgument {
static func defaultValueDescription(_ initial: Initial?) -> String?
}
enum Bare<T> { }
extension Bare: ArgumentDefinitionContainer {
typealias Contained = T
typealias Initial = T
static var helpOptions: ArgumentDefinition.Help.Options { [] }
static func update(
parsedValues: inout ParsedValues,
value: Contained,
key: InputKey,
origin: InputOrigin
) {
parsedValues.set(value, forKey: key, inputOrigin: origin)
}
}
extension Bare: ArgumentDefinitionContainerExpressibleByArgument
where Contained: ExpressibleByArgument {
static func defaultValueDescription(_ initial: T?) -> String? {
guard let initial = initial else { return nil }
return initial.defaultValueDescription
}
}
extension Optional: ArgumentDefinitionContainer {
typealias Contained = Wrapped
typealias Initial = Wrapped
static var helpOptions: ArgumentDefinition.Help.Options { [.isOptional] }
static func update(
parsedValues: inout ParsedValues,
value: Contained,
key: InputKey,
origin: InputOrigin
) {
parsedValues.set(value, forKey: key, inputOrigin: origin)
}
}
extension Optional: ArgumentDefinitionContainerExpressibleByArgument
where Contained: ExpressibleByArgument {
static func defaultValueDescription(_ initial: Initial?) -> String? {
guard let initial = initial else { return nil }
return initial.defaultValueDescription
}
}
extension Array: ArgumentDefinitionContainer {
typealias Contained = Element
typealias Initial = Array<Element>
static var helpOptions: ArgumentDefinition.Help.Options { [.isRepeating] }
static func update(
parsedValues: inout ParsedValues,
value: Element,
key: InputKey,
origin: InputOrigin
) {
parsedValues.update(
forKey: key,
inputOrigin: origin,
initial: .init(),
closure: { $0.append(value) })
}
}
extension Array: ArgumentDefinitionContainerExpressibleByArgument
where Element: ExpressibleByArgument {
static func defaultValueDescription(_ initial: Array<Element>?) -> String? {
guard let initial = initial else { return nil }
guard !initial.isEmpty else { return nil }
return initial
.lazy
.map { $0.defaultValueDescription }
.joined(separator: ", ")
}
}