Skip to content

Commit

Permalink
Add aliases support for sub commands (apple#627)
Browse files Browse the repository at this point in the history
This adds support for aliases for subcommands via a new parameter to
CommandConfigurations constructors. The aliases are passed as an array
of strings, where the default is just an empty array that signifies there
are no aliases. The aliases are supported regardless of if a different
commandName is chosen or not. This also updates how subcommands show up
in the help text. Any aliases are now displayed to the right of the original
command.

In addition to the functionality itself, this change:

1. Updates some of the EndToEnd parsing tests to make sure they function
while using aliases.
2. Sprinkles mentions where I saw fit in the documentation.
3. Updates the Math example to have aliases for `math stats average`
(`math stats avg`), and `math multiply` (`math mul`).

`math`'s help text now looks like the below:

```
~ math --help
OVERVIEW: A utility for performing maths.

USAGE: math <subcommand>

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

SUBCOMMANDS:
  add (default)           Print the sum of the values.
  multiply, mul           Print the product of the values.
  stats                   Calculate descriptive statistics.

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

~ math stats --help
OVERVIEW: Calculate descriptive statistics.

USAGE: math stats <subcommand>

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

SUBCOMMANDS:
  average, avg            Print the average of the values.
  stdev                   Print the standard deviation of the values.
  quantiles               Print the quantiles of the values (TBD).

  See 'math help stats <subcommand>' for detailed help.
```

and use of the aliases:

```
~ math mul 10 10
100

~ math stats avg 10 20
15.0
```

This change does NOT add any updates to the shell completion logic for
this feature.

Fixes apple#248
  • Loading branch information
dcantah authored Apr 30, 2024
1 parent 4698969 commit 2b96293
Show file tree
Hide file tree
Showing 11 changed files with 182 additions and 19 deletions.
8 changes: 5 additions & 3 deletions Examples/math/Math.swift
Original file line number Diff line number Diff line change
Expand Up @@ -64,8 +64,9 @@ extension Math {
}

struct Multiply: ParsableCommand {
static let configuration =
CommandConfiguration(abstract: "Print the product of the values.")
static let configuration = CommandConfiguration(
abstract: "Print the product of the values.",
aliases: ["mul"])

@OptionGroup var options: Options

Expand All @@ -92,7 +93,8 @@ extension Math.Statistics {
struct Average: ParsableCommand {
static let configuration = CommandConfiguration(
abstract: "Print the average of the values.",
version: "1.5.0-alpha")
version: "1.5.0-alpha",
aliases: ["avg"])

enum Kind: String, ExpressibleByArgument, CaseIterable {
case mean, median, mode
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ OPTIONS:
-h, --help Show help information.
SUBCOMMANDS:
average Print the average of the values.
average, avg Print the average of the values.
stdev Print the standard deviation of the values.
quantiles Print the quantiles of the values (TBD).
Expand Down Expand Up @@ -84,8 +84,9 @@ extension Math {
}

struct Multiply: ParsableCommand {
static let configuration
= CommandConfiguration(abstract: "Print the product of the values.")
static let configuration = CommandConfiguration(
abstract: "Print the product of the values.",
aliases: ["mul"])

@OptionGroup var options: Math.Options

Expand All @@ -97,6 +98,17 @@ extension Math {
}
```

One thing to note is the aliases parameter for `CommandConfiguration`. This is useful for subcommands
to define alternative names that can be used to invoke them. In this case we've defined a shorthand
for multiply named mul, so you could invoke the `Multiply` command for our program by either of the below:

```
% math multiply 10 15 7
1050
% math mul 10 15 7
1050
```

Next, we'll define `Statistics`, the third subcommand of `Math`. The `Statistics` command specifies a custom command name (`stats`) in its configuration, overriding the default derived from the type name (`statistics`). It also declares two additional subcommands, meaning that it acts as a forked branch in the command tree, and not a leaf.

```swift
Expand All @@ -116,7 +128,8 @@ Let's finish our subcommands with the `Average` and `StandardDeviation` types. E
extension Math.Statistics {
struct Average: ParsableCommand {
static let configuration = CommandConfiguration(
abstract: "Print the average of the values.")
abstract: "Print the average of the values.",
aliases: ["avg"])

enum Kind: String, ExpressibleByArgument {
case mean, median, mode
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

### Creating a Configuration

- ``init(commandName:abstract:usage:discussion:version:shouldDisplay:subcommands:defaultSubcommand:helpNames:)``
- ``init(commandName:abstract:usage:discussion:version:shouldDisplay:subcommands:defaultSubcommand:helpNames:aliases:)``

### Customizing the Help Screen

Expand All @@ -23,4 +23,4 @@
- ``commandName``
- ``version``
- ``shouldDisplay``

- ``aliases``
50 changes: 45 additions & 5 deletions Sources/ArgumentParser/Parsable Types/CommandConfiguration.swift
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,14 @@ public struct CommandConfiguration: Sendable {

/// Flag names to be used for help.
public var helpNames: NameSpecification?


/// An array of aliases for the command's name.
///
/// All of the aliases MUST not match the actual command's name,
/// whether that be the derived name if `commandName` is not provided,
/// or `commandName` itself if provided.
public var aliases: [String]

/// Creates the configuration for a command.
///
/// - Parameters:
Expand All @@ -80,6 +87,9 @@ public struct CommandConfiguration: Sendable {
/// with a simulated Boolean property named `help`. If `helpNames` is
/// `nil`, the names are inherited from the parent command, if any, or
/// are `-h` and `--help`.
/// - aliases: An array of aliases for the command's name. All of the aliases
/// MUST not match the actual command name, whether that be the derived name
/// if `commandName` is not provided, or `commandName` itself if provided.
public init(
commandName: String? = nil,
abstract: String = "",
Expand All @@ -89,7 +99,8 @@ public struct CommandConfiguration: Sendable {
shouldDisplay: Bool = true,
subcommands: [ParsableCommand.Type] = [],
defaultSubcommand: ParsableCommand.Type? = nil,
helpNames: NameSpecification? = nil
helpNames: NameSpecification? = nil,
aliases: [String] = []
) {
self.commandName = commandName
self.abstract = abstract
Expand All @@ -100,6 +111,7 @@ public struct CommandConfiguration: Sendable {
self.subcommands = subcommands
self.defaultSubcommand = defaultSubcommand
self.helpNames = helpNames
self.aliases = aliases
}

/// Creates the configuration for a command with a "super-command".
Expand All @@ -114,7 +126,8 @@ public struct CommandConfiguration: Sendable {
shouldDisplay: Bool = true,
subcommands: [ParsableCommand.Type] = [],
defaultSubcommand: ParsableCommand.Type? = nil,
helpNames: NameSpecification? = nil
helpNames: NameSpecification? = nil,
aliases: [String] = []
) {
self.commandName = commandName
self._superCommandName = _superCommandName
Expand All @@ -126,11 +139,37 @@ public struct CommandConfiguration: Sendable {
self.subcommands = subcommands
self.defaultSubcommand = defaultSubcommand
self.helpNames = helpNames
self.aliases = aliases
}
}

extension CommandConfiguration {
@available(*, deprecated, message: "Use the memberwise initializer with the usage parameter.")
@available(*, deprecated, message: "Use the memberwise initializer with the aliases parameter.")
public init(
commandName: String? = nil,
abstract: String = "",
usage: String? = nil,
discussion: String = "",
version: String = "",
shouldDisplay: Bool = true,
subcommands: [ParsableCommand.Type] = [],
defaultSubcommand: ParsableCommand.Type? = nil,
helpNames: NameSpecification? = nil
) {
self.init(
commandName: commandName,
abstract: abstract,
usage: usage,
discussion: discussion,
version: version,
shouldDisplay: shouldDisplay,
subcommands: subcommands,
defaultSubcommand: defaultSubcommand,
helpNames: helpNames,
aliases: [])
}

@available(*, deprecated, message: "Use the memberwise initializer with the usage and aliases parameters.")
public init(
commandName _commandName: String?,
abstract: String,
Expand All @@ -150,6 +189,7 @@ extension CommandConfiguration {
shouldDisplay: shouldDisplay,
subcommands: subcommands,
defaultSubcommand: defaultSubcommand,
helpNames: helpNames)
helpNames: helpNames,
aliases: [])
}
}
5 changes: 4 additions & 1 deletion Sources/ArgumentParser/Parsing/ArgumentSet.swift
Original file line number Diff line number Diff line change
Expand Up @@ -495,7 +495,10 @@ struct LenientParser {
// parsing to skip over unrecognized input, but if the current
// command or the matched subcommand captures all remaining input,
// then we want to break out of parsing at this point.
if let matchedSubcommand = subcommands.first(where: { $0._commandName == argument }) {
let matchedSubcommand = subcommands.first(where: {
$0._commandName == argument || $0.configuration.aliases.contains(argument)
})
if let matchedSubcommand {
if !matchedSubcommand.includesPassthroughArguments && defaultCapturesForPassthrough {
continue ArgumentLoop
} else if matchedSubcommand.includesPassthroughArguments {
Expand Down
4 changes: 3 additions & 1 deletion Sources/ArgumentParser/Parsing/CommandParser.swift
Original file line number Diff line number Diff line change
Expand Up @@ -41,11 +41,13 @@ struct CommandParser {
self.commandTree = try Tree(root: rootCommand)
} catch Tree<ParsableCommand.Type>.InitializationError.recursiveSubcommand(let command) {
fatalError("The ParsableCommand \"\(command)\" can't have itself as its own subcommand.")
} catch Tree<ParsableCommand.Type>.InitializationError.aliasMatchingCommand(let command) {
fatalError("The ParsableCommand \"\(command)\" can't have an alias with the same name as the command itself.")
} catch {
fatalError("Unexpected error: \(error).")
}
self.currentNode = commandTree

// A command tree that has a depth greater than zero gets a `help`
// subcommand.
if !commandTree.isLeaf {
Expand Down
3 changes: 3 additions & 0 deletions Sources/ArgumentParser/Usage/HelpGenerator.swift
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,9 @@ internal struct HelpGenerator {
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)"
}
Expand Down
9 changes: 8 additions & 1 deletion Sources/ArgumentParser/Utilities/Tree.swift
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,9 @@ extension Tree where Element == ParsableCommand.Type {
}

func firstChild(withName name: String) -> Tree? {
children.first(where: { $0.element._commandName == name })
children.first(where: {
$0.element._commandName == name || $0.element.configuration.aliases.contains(name)
})
}

convenience init(root command: ParsableCommand.Type) throws {
Expand All @@ -94,11 +96,16 @@ extension Tree where Element == ParsableCommand.Type {
if subcommand == command {
throw InitializationError.recursiveSubcommand(subcommand)
}
// We don't allow an alias that has the same name as the command itself.
if subcommand.configuration.aliases.contains(subcommand._commandName) {
throw InitializationError.aliasMatchingCommand(subcommand)
}
try addChild(Tree(root: subcommand))
}
}

enum InitializationError: Error {
case recursiveSubcommand(ParsableCommand.Type)
case aliasMatchingCommand(ParsableCommand.Type)
}
}
Loading

0 comments on commit 2b96293

Please sign in to comment.