Skip to content

Commit

Permalink
Introduce subcommand grouping into the command configuration to impro…
Browse files Browse the repository at this point in the history
…ve help (apple#644)

* Introduce subcommand grouping into the command configuration to improve help

Add optional support for grouping subcommands into named groups, to
help bring order to commands with many subcommands without requiring
additional structure. For example, here's the help for a
"subgroupings" command that has an ungrouped subcommand (m), and two
groups of subcommands ("broken" and "complicated").

    USAGE: subgroupings <subcommand>

    OPTIONS:
      -h, --help              Show help information.

    SUBCOMMANDS:
      m

    BROKEN SUBCOMMANDS:
      foo                     Perform some foo
      bar                     Perform bar operations

    COMPLICATED SUBCOMMANDS:
      n

      See 'subgroupings help <subcommand>' for detailed help.

To be able freely mix subcommands and subcommand groups, CommandConfiguration
has a new initializer that takes a result builder. The help output
above is created like this:

    struct WithSubgroups: ParsableCommand {
      static let configuration = CommandConfiguration(
        commandName: "subgroupings"
      ) {
        CommandGroup(name: "Broken") {
          Foo.self
          Bar.self
        }

        M.self

        CommandGroup(name: "Complicated") {
          N.self
        }
      }
    }

Each `CommandGroup` names a new group and is given commands (there are
no groups within groups). The other entries are arbitrary
ParsableCommands.

This structure is only cosmetic, and only affects help generation by
providing more structure for the reader. It doesn't impact existing
clients, who can still reason about the flattened list of subcommands
if they prefer.

* Add an optional abstract to command groups

* Expand subcommand group result builders to handle all result-builder syntax

Adds support for if, if-else, if #available, and for..in loops.

* Revert "Add an optional abstract to command groups"

This reverts commit ab563a2.

* Eliminate result builders in favor of a second "groupedSubcommands" array

Introduce subcommand groups with a more modest extension to the API that
adds another array of subcommand groups alongside the (ungrouped)
subcommands array. We can consider introducing result builders as a
separate step later, if there's more to be gained from it.

* Drop the (ungrouped) "subcommands" heading when there are none.
  • Loading branch information
DougGregor authored Jun 4, 2024
1 parent 0fbc884 commit 516c2f8
Show file tree
Hide file tree
Showing 4 changed files with 191 additions and 28 deletions.
41 changes: 33 additions & 8 deletions Sources/ArgumentParser/Parsable Types/CommandConfiguration.swift
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,27 @@ public struct CommandConfiguration: Sendable {
public var shouldDisplay: Bool

/// An array of the types that define subcommands for this command.
public var subcommands: [ParsableCommand.Type]

///
/// This property "flattens" the grouping structure of the subcommands.
/// Use 'ungroupedSubcommands' to access 'groupedSubcommands' to retain the grouping structure.
public var subcommands: [ParsableCommand.Type] {
get {
return ungroupedSubcommands + groupedSubcommands.flatMap { $0.subcommands }
}

set {
groupedSubcommands = []
ungroupedSubcommands = newValue
}
}

/// An array of types that define subcommands for this command and are
/// not part of any command group.
public var ungroupedSubcommands: [ParsableCommand.Type]

/// The list of subcommands and subcommand groups.
public var groupedSubcommands: [CommandGroup]

/// The default command type to run if no subcommand is given.
public var defaultSubcommand: ParsableCommand.Type?

Expand Down Expand Up @@ -79,8 +98,10 @@ public struct CommandConfiguration: Sendable {
/// a `--version` flag.
/// - shouldDisplay: A Boolean value indicating whether the command
/// should be shown in the extended help display.
/// - subcommands: An array of the types that define subcommands for the
/// command.
/// - ungroupedSubcommands: An array of the types that define subcommands
/// for the command that are not part of any command group.
/// - groupedSubcommands: An array of command groups, each of which defines
/// subcommands that are part of that logical group.
/// - defaultSubcommand: The default command type to run if no subcommand
/// is given.
/// - helpNames: The flag names to use for requesting help, when combined
Expand All @@ -97,7 +118,8 @@ public struct CommandConfiguration: Sendable {
discussion: String = "",
version: String = "",
shouldDisplay: Bool = true,
subcommands: [ParsableCommand.Type] = [],
subcommands ungroupedSubcommands: [ParsableCommand.Type] = [],
groupedSubcommands: [CommandGroup] = [],
defaultSubcommand: ParsableCommand.Type? = nil,
helpNames: NameSpecification? = nil,
aliases: [String] = []
Expand All @@ -108,7 +130,8 @@ public struct CommandConfiguration: Sendable {
self.discussion = discussion
self.version = version
self.shouldDisplay = shouldDisplay
self.subcommands = subcommands
self.ungroupedSubcommands = ungroupedSubcommands
self.groupedSubcommands = groupedSubcommands
self.defaultSubcommand = defaultSubcommand
self.helpNames = helpNames
self.aliases = aliases
Expand All @@ -124,7 +147,8 @@ public struct CommandConfiguration: Sendable {
discussion: String = "",
version: String = "",
shouldDisplay: Bool = true,
subcommands: [ParsableCommand.Type] = [],
subcommands ungroupedSubcommands: [ParsableCommand.Type] = [],
groupedSubcommands: [CommandGroup] = [],
defaultSubcommand: ParsableCommand.Type? = nil,
helpNames: NameSpecification? = nil,
aliases: [String] = []
Expand All @@ -136,7 +160,8 @@ public struct CommandConfiguration: Sendable {
self.discussion = discussion
self.version = version
self.shouldDisplay = shouldDisplay
self.subcommands = subcommands
self.ungroupedSubcommands = ungroupedSubcommands
self.groupedSubcommands = groupedSubcommands
self.defaultSubcommand = defaultSubcommand
self.helpNames = helpNames
self.aliases = aliases
Expand Down
28 changes: 28 additions & 0 deletions Sources/ArgumentParser/Parsable Types/CommandGroup.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
//===----------------------------------------------------------*- 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
//
//===----------------------------------------------------------------------===//

/// A set of commands grouped together under a common name.
public struct CommandGroup: Sendable {
/// The name of the command group that will be displayed in help.
public let name: String

/// The list of subcommands that are part of this group.
public let subcommands: [ParsableCommand.Type]

/// Create a command group.
public init(
name: String,
subcommands: [ParsableCommand.Type]
) {
self.name = name
self.subcommands = subcommands
}
}
80 changes: 60 additions & 20 deletions Sources/ArgumentParser/Usage/HelpGenerator.swift
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,8 @@ internal struct HelpGenerator {
case subcommands
case options
case title(String)

case groupedSubcommands(String)

var description: String {
switch self {
case .positionalArguments:
Expand All @@ -63,6 +64,8 @@ internal struct HelpGenerator {
return "Options"
case .title(let name):
return name
case .groupedSubcommands(let name):
return "\(name) Subcommands"
}
}
}
Expand Down Expand Up @@ -211,34 +214,67 @@ internal struct HelpGenerator {
}

let configuration = commandStack.last!.configuration
let subcommandElements: [Section.Element] =
configuration.subcommands.compactMap { command in
guard command.configuration.shouldDisplay else { return nil }
var label = command._commandName
for alias in command.configuration.aliases {
label += ", \(alias)"
}
if command == configuration.defaultSubcommand {
label += " (default)"
}
return Section.Element(
label: label,
abstract: command.configuration.abstract)

// Create section for a grouping of subcommands.
func subcommandSection(
header: Section.Header,
subcommands: [ParsableCommand.Type]
) -> Section {
let subcommandElements: [Section.Element] =
subcommands.compactMap { command in
guard command.configuration.shouldDisplay else { return nil }
var label = command._commandName
for alias in command.configuration.aliases {
label += ", \(alias)"
}
if command == configuration.defaultSubcommand {
label += " (default)"
}
return Section.Element(
label: label,
abstract: command.configuration.abstract)
}

return Section(header: header, elements: subcommandElements)
}


// All of the subcommand sections.
var subcommands: [Section] = []

// Add section for the ungrouped subcommands, if there are any.
if !configuration.ungroupedSubcommands.isEmpty {
subcommands.append(
subcommandSection(
header: .subcommands,
subcommands: configuration.ungroupedSubcommands
)
)
}

// Add sections for all of the grouped subcommands.
subcommands.append(
contentsOf: configuration.groupedSubcommands
.compactMap { group in
return subcommandSection(
header: .groupedSubcommands(group.name),
subcommands: group.subcommands
)
}
)

// Combine the compiled groups in this order:
// - arguments
// - named sections
// - options/flags
// - subcommands
// - ungrouped subcommands
// - grouped subcommands
return [
Section(header: .positionalArguments, elements: positionalElements),
] + sectionTitles.map { name in
Section(header: .title(name), elements: titledSections[name, default: []])
} + [
Section(header: .options, elements: optionElements),
Section(header: .subcommands, elements: subcommandElements),
]
] + subcommands
}

func usageMessage() -> String {
Expand All @@ -247,8 +283,12 @@ internal struct HelpGenerator {
}

var includesSubcommands: Bool {
guard let subcommandSection = sections.first(where: { $0.header == .subcommands })
else { return false }
guard let subcommandSection = sections.first(where: {
switch $0.header {
case .groupedSubcommands, .subcommands: return true
case .options, .positionalArguments, .title(_): return false
}
}) else { return false }
return !subcommandSection.elements.isEmpty
}

Expand Down
70 changes: 70 additions & 0 deletions Tests/ArgumentParserUnitTests/HelpGenerationTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -514,6 +514,76 @@ extension HelpGenerationTests {
""")
}

struct WithSubgroups: ParsableCommand {
static let configuration = CommandConfiguration(
commandName: "subgroupings",
subcommands: [ M.self ],
groupedSubcommands: [
CommandGroup(
name: "Broken",
subcommands: [ Foo.self, Bar.self ]
),
CommandGroup(name: "Complicated", subcommands: [ N.self ])
]
)
}

func testHelpSubcommandGroups() throws {
AssertHelp(.default, for: WithSubgroups.self, equals: """
USAGE: subgroupings <subcommand>
OPTIONS:
-h, --help Show help information.
SUBCOMMANDS:
m
BROKEN SUBCOMMANDS:
foo Perform some foo
bar Perform bar operations
COMPLICATED SUBCOMMANDS:
n
See 'subgroupings help <subcommand>' for detailed help.
""")
}

struct OnlySubgroups: ParsableCommand {
static let configuration = CommandConfiguration(
commandName: "subgroupings",
groupedSubcommands: [
CommandGroup(
name: "Broken",
subcommands: [ Foo.self, Bar.self ]
),
CommandGroup(
name: "Complicated",
subcommands: [ M.self, N.self ]
)
]
)
}

func testHelpOnlySubcommandGroups() throws {
AssertHelp(.default, for: OnlySubgroups.self, equals: """
USAGE: subgroupings <subcommand>
OPTIONS:
-h, --help Show help information.
BROKEN SUBCOMMANDS:
foo Perform some foo
bar Perform bar operations
COMPLICATED SUBCOMMANDS:
m
n
See 'subgroupings help <subcommand>' for detailed help.
""")
}
}

extension HelpGenerationTests {
Expand Down

0 comments on commit 516c2f8

Please sign in to comment.