ArgumentParser+AsyncAwait.swift 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. /*
  2. * Copyright 2021, gRPC Authors All rights reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. /// NOTE: This file should be removed when the `async` branch of `swift-argument-parser` has been
  17. /// released: https://github.com/apple/swift-argument-parser/tree/async
  18. #if compiler(>=5.5.2) && canImport(_Concurrency)
  19. import ArgumentParser
  20. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  21. protocol AsyncParsableCommand: ParsableCommand {
  22. mutating func runAsync() async throws
  23. }
  24. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  25. extension AsyncParsableCommand {
  26. public mutating func run() throws {
  27. throw CleanExit.helpRequest(self)
  28. }
  29. }
  30. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  31. extension ParsableCommand {
  32. static func main(_ arguments: [String]? = nil) async {
  33. do {
  34. var command = try parseAsRoot(arguments)
  35. if var asyncCommand = command as? AsyncParsableCommand {
  36. try await asyncCommand.runAsync()
  37. } else {
  38. try command.run()
  39. }
  40. } catch {
  41. exit(withError: error)
  42. }
  43. }
  44. }
  45. #endif