Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add aliases support for sub commands #627

Merged
merged 1 commit into from
Apr 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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.")
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@rauhul Added this as we spoke about for source stability, let me know if I'm dumb and missed something.

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) {
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@natecook1000 Rauhul and I talked on this. I think it makes sense for this case to not be a validation and be a hard error given it won't break any existing programs.

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)
}
}