HelpCommand.swift 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. struct HelpCommand: ParsableCommand {
  12. static let configuration = CommandConfiguration(
  13. commandName: "help",
  14. abstract: "Show subcommand help information.",
  15. helpNames: [])
  16. /// Any subcommand names provided after the `help` subcommand.
  17. @Argument var subcommands: [String] = []
  18. /// Capture and ignore any extra help flags given by the user.
  19. @Flag(
  20. name: [.short, .long, .customLong("help", withSingleDash: true)],
  21. help: .private)
  22. var help = false
  23. private(set) var commandStack: [ParsableCommand.Type] = []
  24. private(set) var visibility: ArgumentVisibility = .default
  25. init() {}
  26. mutating func run() throws {
  27. throw CommandError(
  28. commandStack: commandStack,
  29. parserError: .helpRequested(visibility: visibility))
  30. }
  31. mutating func buildCommandStack(with parser: CommandParser) throws {
  32. commandStack = parser.commandStack(for: subcommands)
  33. }
  34. /// Used for testing.
  35. func generateHelp(screenWidth: Int) -> String {
  36. HelpGenerator(
  37. commandStack: commandStack,
  38. visibility: visibility
  39. )
  40. .rendered(screenWidth: screenWidth)
  41. }
  42. enum CodingKeys: CodingKey {
  43. case subcommands
  44. case help
  45. }
  46. init(from decoder: Decoder) throws {
  47. let container = try decoder.container(keyedBy: CodingKeys.self)
  48. self.subcommands = try container.decode([String].self, forKey: .subcommands)
  49. self.help = try container.decode(Bool.self, forKey: .help)
  50. }
  51. init(commandStack: [ParsableCommand.Type], visibility: ArgumentVisibility) {
  52. self.commandStack = commandStack
  53. self.visibility = visibility
  54. self.subcommands = commandStack.map { $0._commandName }
  55. self.help = false
  56. }
  57. }