ParsableArgumentsValidation.swift 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. //===----------------------------------------------------------------------===//
  2. //
  3. // This source file is part of the Swift Argument Parser open source project
  4. //
  5. // Copyright (c) 2020 Apple Inc. and the Swift project authors
  6. // Licensed under Apache License v2.0 with Runtime Library Exception
  7. //
  8. // See https://swift.org/LICENSE.txt for license information
  9. //
  10. //===----------------------------------------------------------------------===//
  11. extension ParsableArguments {
  12. static func _validate(parent: InputKey?) throws {
  13. let validators: [ParsableArgumentsValidator.Type] = [
  14. PositionalArgumentsValidator.self,
  15. CodingKeyValidator.self,
  16. UniqueNamesValidator.self,
  17. NonsenseFlagsValidator.self,
  18. ]
  19. let errors = validators.compactMap { validator in
  20. validator.validate(self, parent: parent)
  21. }
  22. if errors.count > 0 {
  23. throw ParsableArgumentsValidationError(
  24. parsableArgumentsType: self, underlayingErrors: errors)
  25. }
  26. }
  27. }
  28. protocol ParsableArgumentsValidator {
  29. static func validate(_ type: ParsableArguments.Type, parent: InputKey?)
  30. -> ParsableArgumentsValidatorError?
  31. }
  32. enum ValidatorErrorKind {
  33. case warning
  34. case failure
  35. }
  36. protocol ParsableArgumentsValidatorError: Error {
  37. var kind: ValidatorErrorKind { get }
  38. }
  39. struct ParsableArgumentsValidationError: Error, CustomStringConvertible {
  40. let parsableArgumentsType: ParsableArguments.Type
  41. let underlayingErrors: [Error]
  42. var description: String {
  43. let errorDescriptions =
  44. underlayingErrors
  45. .map {
  46. "- \($0)"
  47. .wrapped(to: 68)
  48. .hangingIndentingEachLine(by: 2)
  49. }
  50. return """
  51. Validation failed for `\(parsableArgumentsType)`:
  52. \(errorDescriptions.joined(separator: "\n"))
  53. """
  54. }
  55. }