/
ParsableArgumentsValidation.swift
317 lines (265 loc) · 10.3 KB
/
ParsableArgumentsValidation.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
//===----------------------------------------------------------*- 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
//
//===----------------------------------------------------------------------===//
fileprivate protocol ParsableArgumentsValidator {
static func validate(_ type: ParsableArguments.Type, parent: InputKey.Parent) -> ParsableArgumentsValidatorError?
}
enum ValidatorErrorKind {
case warning
case failure
}
protocol ParsableArgumentsValidatorError: Error {
var kind: ValidatorErrorKind { get }
}
struct ParsableArgumentsValidationError: Error, CustomStringConvertible {
let parsableArgumentsType: ParsableArguments.Type
let underlayingErrors: [Error]
var description: String {
"""
Validation failed for `\(parsableArgumentsType)`:
\(underlayingErrors.map({"- \($0)"}).joined(separator: "\n"))
"""
}
}
extension ParsableArguments {
static func _validate(parent: InputKey.Parent) throws {
let validators: [ParsableArgumentsValidator.Type] = [
PositionalArgumentsValidator.self,
ParsableArgumentsCodingKeyValidator.self,
ParsableArgumentsUniqueNamesValidator.self,
NonsenseFlagsValidator.self,
]
let errors = validators.compactMap { validator in
validator.validate(self, parent: parent)
}
if errors.count > 0 {
throw ParsableArgumentsValidationError(parsableArgumentsType: self, underlayingErrors: errors)
}
}
}
fileprivate extension ArgumentSet {
var firstPositionalArgument: ArgumentDefinition? {
content.first(where: { $0.isPositional })
}
var firstRepeatedPositionalArgument: ArgumentDefinition? {
content.first(where: { $0.isRepeatingPositional })
}
}
/// For positional arguments to be valid, there must be at most one
/// positional array argument, and it must be the last positional argument
/// in the argument list. Any other configuration leads to ambiguity in
/// parsing the arguments.
struct PositionalArgumentsValidator: ParsableArgumentsValidator {
struct Error: ParsableArgumentsValidatorError, CustomStringConvertible {
let repeatedPositionalArgument: String
let positionalArgumentFollowingRepeated: String
var description: String {
"Can't have a positional argument `\(positionalArgumentFollowingRepeated)` following an array of positional arguments `\(repeatedPositionalArgument)`."
}
var kind: ValidatorErrorKind { .failure }
}
static func validate(_ type: ParsableArguments.Type, parent: InputKey.Parent) -> ParsableArgumentsValidatorError? {
let sets: [ArgumentSet] = Mirror(reflecting: type.init())
.children
.compactMap { child in
guard
let codingKey = child.label,
let parsed = child.value as? ArgumentSetProvider
else { return nil }
let key = InputKey(name: codingKey, parent: parent)
return parsed.argumentSet(for: key)
}
guard let repeatedPositional = sets.firstIndex(where: { $0.firstRepeatedPositionalArgument != nil })
else { return nil }
guard let positionalFollowingRepeated = sets[repeatedPositional...]
.dropFirst()
.first(where: { $0.firstPositionalArgument != nil })
else { return nil }
let firstRepeatedPositionalArgument: ArgumentDefinition = sets[repeatedPositional].firstRepeatedPositionalArgument!
let positionalFollowingRepeatedArgument: ArgumentDefinition = positionalFollowingRepeated.firstPositionalArgument!
return Error(
repeatedPositionalArgument: firstRepeatedPositionalArgument.help.keys.first!.name,
positionalArgumentFollowingRepeated: positionalFollowingRepeatedArgument.help.keys.first!.name)
}
}
/// Ensure that all arguments have corresponding coding keys
struct ParsableArgumentsCodingKeyValidator: ParsableArgumentsValidator {
private struct Validator: Decoder {
let argumentKeys: [InputKey]
enum ValidationResult: Swift.Error {
case success
case missingCodingKeys([InputKey])
}
let codingPath: [CodingKey] = []
let userInfo: [CodingUserInfoKey : Any] = [:]
func unkeyedContainer() throws -> UnkeyedDecodingContainer {
fatalError()
}
func singleValueContainer() throws -> SingleValueDecodingContainer {
fatalError()
}
func container<Key>(keyedBy type: Key.Type) throws -> KeyedDecodingContainer<Key> where Key : CodingKey {
let missingKeys = argumentKeys.filter { Key(stringValue: $0.name) == nil }
if missingKeys.isEmpty {
throw ValidationResult.success
} else {
throw ValidationResult.missingCodingKeys(missingKeys)
}
}
}
/// This error indicates that an option, a flag, or an argument of
/// a `ParsableArguments` is defined without a corresponding `CodingKey`.
struct MissingKeysError: ParsableArgumentsValidatorError, CustomStringConvertible {
let missingCodingKeys: [InputKey]
var description: String {
let resolution = """
To resolve this error, make sure that all properties have corresponding
cases in your custom `CodingKey` enumeration.
"""
if missingCodingKeys.count > 1 {
return """
Arguments \(missingCodingKeys.map({ "`\($0)`" }).joined(separator: ",")) \
are defined without corresponding `CodingKey`s.
\(resolution)
"""
} else {
return """
Argument `\(missingCodingKeys[0])` is defined without a corresponding \
`CodingKey`.
\(resolution)
"""
}
}
var kind: ValidatorErrorKind {
.failure
}
}
struct InvalidDecoderError: ParsableArgumentsValidatorError, CustomStringConvertible {
let type: ParsableArguments.Type
var description: String {
"""
The implementation of `init(from:)` for `\(type)`
is not compatible with ArgumentParser. To resolve this issue, make sure
that `init(from:)` calls the `container(keyedBy:)` method on the given
decoder and decodes each of its properties using the returned decoder.
"""
}
var kind: ValidatorErrorKind {
.failure
}
}
static func validate(_ type: ParsableArguments.Type, parent: InputKey.Parent) -> ParsableArgumentsValidatorError? {
let argumentKeys: [InputKey] = Mirror(reflecting: type.init())
.children
.compactMap { child in
guard
let codingKey = child.label,
let _ = child.value as? ArgumentSetProvider
else { return nil }
// Property wrappers have underscore-prefixed names
return InputKey(name: codingKey, parent: parent)
}
guard argumentKeys.count > 0 else {
return nil
}
do {
let _ = try type.init(from: Validator(argumentKeys: argumentKeys))
return InvalidDecoderError(type: type)
} catch let result as Validator.ValidationResult {
switch result {
case .missingCodingKeys(let keys):
return MissingKeysError(missingCodingKeys: keys)
case .success:
return nil
}
} catch {
fatalError("Unexpected validation error: \(error)")
}
}
}
/// Ensure argument names are unique within a `ParsableArguments` or `ParsableCommand`.
struct ParsableArgumentsUniqueNamesValidator: ParsableArgumentsValidator {
struct Error: ParsableArgumentsValidatorError, CustomStringConvertible {
var duplicateNames: [String: Int] = [:]
var description: String {
duplicateNames.map { entry in
"Multiple (\(entry.value)) `Option` or `Flag` arguments are named \"\(entry.key)\"."
}.joined(separator: "\n")
}
var kind: ValidatorErrorKind { .failure }
}
static func validate(_ type: ParsableArguments.Type, parent: InputKey.Parent) -> ParsableArgumentsValidatorError? {
let argSets: [ArgumentSet] = Mirror(reflecting: type.init())
.children
.compactMap { child in
guard
let codingKey = child.label,
let parsed = child.value as? ArgumentSetProvider
else { return nil }
let key = InputKey(name: codingKey, parent: parent)
return parsed.argumentSet(for: key)
}
let countedNames: [String: Int] = argSets.reduce(into: [:]) { countedNames, args in
for name in args.content.flatMap({ $0.names }) {
countedNames[name.synopsisString, default: 0] += 1
}
}
let duplicateNames = countedNames.filter { $0.value > 1 }
return duplicateNames.isEmpty
? nil
: Error(duplicateNames: duplicateNames)
}
}
struct NonsenseFlagsValidator: ParsableArgumentsValidator {
struct Error: ParsableArgumentsValidatorError, CustomStringConvertible {
var names: [String]
var description: String {
"""
One or more Boolean flags is declared with an initial value of `true`.
This results in the flag always being `true`, no matter whether the user
specifies the flag or not.
To resolve this error, change the default to `false`, provide a value
for the `inversion:` parameter, or remove the `@Flag` property wrapper
altogether.
Affected flag(s):
\(names.joined(separator: "\n"))
"""
}
var kind: ValidatorErrorKind { .warning }
}
static func validate(_ type: ParsableArguments.Type, parent: InputKey.Parent) -> ParsableArgumentsValidatorError? {
let argSets: [ArgumentSet] = Mirror(reflecting: type.init())
.children
.compactMap { child in
guard
let codingKey = child.label,
let parsed = child.value as? ArgumentSetProvider
else { return nil }
let key = InputKey(name: codingKey, parent: parent)
return parsed.argumentSet(for: key)
}
let nonsenseFlags: [String] = argSets.flatMap { args -> [String] in
args.compactMap { def in
if case .nullary = def.update,
!def.help.isComposite,
def.help.options.contains(.isOptional),
def.help.defaultValue == "true"
{
return def.unadornedSynopsis
} else {
return nil
}
}
}
return nonsenseFlags.isEmpty
? nil
: Error(names: nonsenseFlags)
}
}