Skip to content
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion .github/workflows/lint.yml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ jobs:
name: Soundness
uses: swiftlang/github-workflows/.github/workflows/soundness.yml@main
with:
docs_check_enabled: false # bug: https://github.com/apple/swift-argument-parser/issues/704
format_check_enabled: false # bug: https://github.com/apple/swift-argument-parser/issues/702
license_header_check_enabled: false # feature: https://github.com/swiftlang/github-workflows/issues/78
license_header_check_project_name: "Swift Argument Parser" # bug: https://github.com/swiftlang/github-workflows/issues/76
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ hello!
...
```

## Modifying the Help Flag Names
### Modifying the Help Flag Names

Users can see the help screen for a command by passing either the `-h` or the `--help` flag, by default. If you need to use one of those flags for another purpose, you can provide alternative names when configuring a root command.

Expand Down Expand Up @@ -123,11 +123,11 @@ OPTIONS:
-?, --help Show help information.
```

## Hiding Commands
### Hiding Commands

You may not want to show every one of your command as part of your command-line interface. To render a command invisible (but still usable), pass `shouldDisplay: false` to the ``CommandConfiguration`` initializer.

## Generating Help Text Programmatically
### Generating Help Text Programmatically

The help screen is automatically shown to users when they call your command with the help flag. You can generate the same text from within your program by calling the `helpMessage()` method.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ OPTIONS:
-h, --help Show help information.
```

## Customizing Help for Arguments
### Customizing Help for Arguments

For more control over the help text, pass an ``ArgumentHelp`` instance instead of a string literal. The `ArgumentHelp` type can include an abstract (which is what the string literal becomes), a discussion, a value name to use in the usage string, and a visibility level for that argument.

Expand Down Expand Up @@ -74,7 +74,7 @@ OPTIONS:
-h, --help Show help information.
```

## Enumerating Possible Values
### Enumerating Possible Values

When an argument or option has a fixed set of possible values, listing these values in the help screen can simplify use of your tool. You can customize the displayed set of values for custom ``ExpressibleByArgument`` types by implementing ``ExpressibleByArgument/allValueStrings``. Despite the name, ``ExpressibleByArgument/allValueStrings`` does _not_ need to be an exhaustive list of possible values.

Expand Down Expand Up @@ -113,9 +113,9 @@ OPTIONS:
-h, --help Show help information.
```

### Deriving Possible Values
#### Deriving Possible Values

ExpressibleByArgument types that conform to ``CaseIterable`` do not need to manually specify ``ExpressibleByArgument/allValueStrings``. Instead, a list of possible values is derived from the type's cases, as in this updated example:
ExpressibleByArgument types that conform to `CaseIterable` do not need to manually specify ``ExpressibleByArgument/allValueStrings``. Instead, a list of possible values is derived from the type's cases, as in this updated example:

```swift
enum Fruit: String, CaseIterable, ExpressibleByArgument {
Expand Down Expand Up @@ -148,9 +148,9 @@ OPTIONS:
-h, --help Show help information.
```

For an ``ExpressibleByArgument`` and ``CaseIterable`` type with many cases, you may still want to implement ``ExpressibleByArgument/allValueStrings`` to avoid an overly long list of values appearing in the help screen. For these types it is recommended to include the most common possible values.
For an ``ExpressibleByArgument`` and `CaseIterable` type with many cases, you may still want to implement ``ExpressibleByArgument/allValueStrings`` to avoid an overly long list of values appearing in the help screen. For these types it is recommended to include the most common possible values.

## Controlling Argument Visibility
### Controlling Argument Visibility

You can specify the visibility of any argument, option, or flag.

Expand Down Expand Up @@ -218,7 +218,7 @@ OPTIONS:
-h, --help Show help information.
```

## Grouping Arguments in the Help Screen
### Grouping Arguments in the Help Screen

When you provide a title in an `@OptionGroup` declaration, that type's properties are grouped together under your title in the help screen. For example, this command bundles similar arguments together under a "Build Options" title:

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ Your lucky numbers are:
1 2 3
```

## Customizing option and flag names
### Customizing option and flag names

By default, options and flags derive the name that you use on the command line from the name of the property, such as `--count` and `--index`. Camel-case names are converted to lowercase with hyphen-separated words, like `--strip-whitespace`.

Expand Down Expand Up @@ -132,7 +132,7 @@ struct Example: ParsableCommand {
**Note:** You can also pass `withSingleDash: true` to `.customLong` to create a single-dash flag or option, such as `-verbose`. Use this name specification only when necessary, such as when migrating a legacy command-line interface. Using long names with a single-dash prefix can lead to ambiguity with combined short names: it may not be obvious whether `-file` is a single option or the combination of the four short options `-f`, `-i`, `-l`, and `-e`.


## Parsing custom types
### Parsing custom types

Arguments and options can be parsed from any type that conforms to the ``ExpressibleByArgument`` protocol. Standard library integer and floating-point types, strings, and Booleans all conform to `ExpressibleByArgument`.

Expand Down Expand Up @@ -201,7 +201,7 @@ struct Example: ParsableCommand {

Throw an error from the `transform` function to indicate that the user provided an invalid value for that type. See <doc:Validation> for more about customizing `transform` function errors.

## Using flag inversions, enumerations, and counts
### Using flag inversions, enumerations, and counts

Flags are most frequently used for `Bool` properties. You can generate a `true`/`false` pair of flags by specifying a flag inversion:

Expand Down Expand Up @@ -288,7 +288,7 @@ Verbosity level: 4
```


## Specifying default values
### Specifying default values

You can specify default values for almost all supported argument, option, and flag types using normal property initialization syntax:

Expand Down Expand Up @@ -327,7 +327,7 @@ If a default is not specified, the user must provide a value for that argument/o
You must also always specify a default of `false` for a non-optional `Bool` flag, as in the example above. This makes the behavior consistent with both normal Swift properties (which either must be explicitly initialized or optional to initialize a `struct`/`class` containing them) and the other property types.


## Specifying a parsing strategy
### Specifying a parsing strategy

When parsing a list of command-line inputs, `ArgumentParser` distinguishes between dash-prefixed keys and un-prefixed values. When looking for the value for a key, only an un-prefixed value will be selected by default.

Expand Down Expand Up @@ -358,7 +358,7 @@ Usage: example [--verbose] --name <name> [<file>]

Parsing options as arrays is similar — only adjacent key-value pairs are recognized by default.

### Alternative single-value parsing strategies
#### Alternative single-value parsing strategies

You can change this behavior by providing a different parsing strategy in the `@Option` initializer. **Be careful when selecting any of the alternative parsing strategies** — they may lead your command-line tool to have unexpected behavior for users!

Expand All @@ -376,7 +376,7 @@ The `.scanningForValue` strategy, on the other hand, looks ahead in the list of
Verbose: true, name: Tomás, file: none
```

### Alternative array parsing strategies
#### Alternative array parsing strategies

The default strategy for parsing options as arrays is to read each value from a key-value pair. For example, this command expects zero or more input file names:

Expand Down Expand Up @@ -427,7 +427,7 @@ Verbose: true, files: ["file1.swift", "file2.swift"]
Verbose: false, files: ["file1.swift", "file2.swift", "--verbose"]
```

### Alternative positional argument parsing strategies
#### Alternative positional argument parsing strategies

The default strategy for parsing arrays of positional arguments is to ignore all dash-prefixed command-line inputs. For example, this command accepts a `--verbose` flag and a list of file names as positional arguments:

Expand Down Expand Up @@ -469,7 +469,7 @@ Verbose: true, files: ["file1.swift", "file2.swift", "--other"]
Verbose: false, files: ["--", "--verbose", "file1.swift", "file2.swift", "--other"]
```

### Ignoring unknown arguments
#### Ignoring unknown arguments

Different versions of a CLI tool may have full or partial sets of supported flags and options.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ Command-line programs built using `ArgumentParser` may include some built-in exp

If you have any feedback on experimental features, please [open a GitHub issue][issue].

## List of Experimental Features
### List of Experimental Features

| Name | Description | related PRs | Version |
| ------------- | ------------- | ------------- | ------------- |
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ Learn to set up and customize a simple command-line tool.

This guide walks through building an example command. You'll learn about the different tools that `ArgumentParser` provides for defining a command's options, customizing the interface, and providing help text for your user.

## Adding ArgumentParser as a Dependency
### Adding ArgumentParser as a Dependency

Let's write a tool called `count` that reads an input file, counts the words, and writes the result to an output file.

Expand All @@ -31,7 +31,7 @@ let package = Package(
)
```

## Building Our First Command
### Building Our First Command

Once we've built the `count` tool, we'll be able to run it like this:

Expand Down Expand Up @@ -69,7 +69,7 @@ Finally, the `Count` command is designated as the program's entry point by apply

> Note: The Swift compiler uses either the type marked with `@main` or a `main.swift` file as the entry point for an executable program. You can use either one, but not both — rename your `main.swift` file to the name of the command when you add `@main`. In this case, rename the file to `Count.swift`.

## Working with Named Options
### Working with Named Options

Our `count` tool may have a usability problem — it's not immediately clear whether a user should provide the input file first, or the output file. Instead of using positional arguments for our two inputs, let's specify that they should be labeled options:

Expand Down Expand Up @@ -106,7 +106,7 @@ This interface has a trade-off for the users of our `count` tool: With `@Argumen
Counting words in 'readme.md' and writing the result into 'readme.counts'.
```

## Adding a Flag
### Adding a Flag

Next, we want to add a `--verbose` flag to our tool, and only print the message if the user specifies that option:

Expand Down Expand Up @@ -142,7 +142,7 @@ struct Count: ParsableCommand {
The `@Flag` property wrapper denotes a command-line input that looks like `--name`, deriving its name from the name of your property. Flags are most frequently used for Boolean values, like the `verbose` property here.


## Using Custom Names
### Using Custom Names

We can customize the names of our options and add an alternative to the `verbose` flag so that users can specify `-v` instead of `--verbose`. The new interface will look like this:

Expand Down Expand Up @@ -175,7 +175,7 @@ struct Count: ParsableCommand {

The default name specification is `.long`, which uses a property's name with a two-dash prefix. `.short` uses only the first letter of a property's name with a single-dash prefix, and allows combining groups of short options. You can specify custom short and long names with the `.customShort(_:)` and `.customLong(_:)` methods, respectively, or use the combined `.shortAndLong` property to specify the common case of both the short and long derived names.

## Providing Help
### Providing Help

`ArgumentParser` automatically generates help for any command when a user provides the `-h` or `--help` flags:

Expand Down Expand Up @@ -222,7 +222,7 @@ OPTIONS:

```

## The Complete Utility
### The Complete Utility

As promised, here's the complete `count` command, for your experimentation:

Expand Down Expand Up @@ -289,7 +289,7 @@ struct RuntimeError: Error, CustomStringConvertible {
```


## Next Steps … Swift concurrency
### Next Steps … Swift concurrency

`ArgumentParser` supports Swift concurrency, notably `async` renditions of `run`. If you use `async` rendition of `run`, conform to `AsyncParsableCommand` instead of `ParsableCommand`.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ Provide your own array of command-line inputs or work directly with parsed comma

For most programs, denoting the root command type as `@main` is all that's necessary. As the program's entry point, that type parses the command-line arguments to find the correct command from your tree of nested subcommands, instantiates and validates the result, and executes the chosen command. For more control, however, you can perform each of those steps manually.

## Parsing Arguments
### Parsing Arguments

For simple Swift scripts, and for those who prefer a straight-down-the-left-edge-of-the-screen scripting style, you can define a single ``ParsableArguments`` type to parse explicitly from the command-line arguments.

Expand Down Expand Up @@ -47,7 +47,7 @@ let chosen = options.elements
print(chosen.joined(separator: "\n"))
```

## Parsing Commands
### Parsing Commands

Manually parsing commands is a little more complex than parsing a simple `ParsableArguments` type. The result of parsing from a tree of subcommands may be of a different type than the root of the tree, so the static ``ParsableCommand/parseAsRoot(_:)`` method returns a type-erased ``ParsableCommand``.

Expand Down Expand Up @@ -80,7 +80,7 @@ You chose to do something else.
1050
```

## Providing Command-Line Input
### Providing Command-Line Input

All of the parsing methods — `parse()`, `parseOrExit()`, and `parseAsRoot()` — can optionally take an array of command-line inputs as an argument. You can use this capability to test your commands, to perform pre-parse filtering of the command-line arguments, or to manually execute commands from within the same or another target.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ howdy
hey
```

## Handling Post-Validation Errors
### Handling Post-Validation Errors

The ``ValidationError`` type is a special `ArgumentParser` error — a validation error's message is always accompanied by an appropriate usage string. You can throw other errors, from either the `validate()` or `run()` method to indicate that something has gone wrong that isn't validation-specific. Errors that conform to `CustomStringConvertible` or `LocalizedError` provide the best experience for users.

Expand Down Expand Up @@ -103,7 +103,7 @@ struct Example: ParsableCommand {
}
```

## Handling Transform Errors
### Handling Transform Errors

During argument and option parsing, you can use a closure to transform the command line strings to custom types. If this transformation fails, you can throw a `ValidationError`; its `message` property will be displayed to the user.

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:aliases:)``
- ``init(commandName:abstract:usage:discussion:version:shouldDisplay:subcommands:groupedSubcommands:defaultSubcommand:helpNames:aliases:)``

### Customizing the Help Screen

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -618,7 +618,7 @@ extension Argument {
/// Creates a property that reads an array from zero or more arguments.
///
/// - Parameters:
/// - initial: A default value to use for this property.
/// - wrappedValue: A default value to use for this property.
/// - parsingStrategy: The behavior to use when parsing multiple values from
/// the command-line arguments.
/// - help: Information about how to use this argument.
Expand Down
4 changes: 2 additions & 2 deletions Sources/ArgumentParser/Parsable Properties/Errors.swift
Original file line number Diff line number Diff line change
Expand Up @@ -82,8 +82,8 @@ public struct CleanExit: Error, CustomStringConvertible {
///
/// - Parameter command: The command type to offer help for, if different
/// from the root command.
public static func helpRequest(_ type: ParsableCommand.Type? = nil) -> CleanExit {
self.init(base: .helpRequest(type))
public static func helpRequest(_ command: ParsableCommand.Type? = nil) -> CleanExit {
self.init(base: .helpRequest(command))
}

/// Treat this error as a clean exit with the given message.
Expand Down
4 changes: 2 additions & 2 deletions Sources/ArgumentParser/Parsable Properties/Flag.swift
Original file line number Diff line number Diff line change
Expand Up @@ -345,7 +345,6 @@ extension Flag where Value == Bool {
///
/// - Parameters:
/// - name: A specification for what names are allowed for this flag.
/// - wrappedValue: A default value to use for this property, provided implicitly by the compiler during property wrapper initialization.
/// - inversion: The method for converting this flag's name into an on/off pair.
/// - exclusivity: The behavior to use when an on/off pair of flags is specified.
/// - help: Information about how to use this flag.
Expand Down Expand Up @@ -580,7 +579,8 @@ extension Flag {
/// This property has an empty array as its default value.
///
/// - Parameters:
/// - name: A specification for what names are allowed for this flag.
/// - wrappedValue: A default value to use for this property, provided
// implicitly by the compiler during property wrapper initialization.
/// - help: Information about how to use this flag.
public init<Element>(
wrappedValue: [Element],
Expand Down
2 changes: 0 additions & 2 deletions Sources/ArgumentParser/Parsable Properties/Option.swift
Original file line number Diff line number Diff line change
Expand Up @@ -706,8 +706,6 @@ extension Option {
/// - help: Information about how to use this option.
/// - completion: The type of command-line completion provided for this
/// option.
/// - transform: A closure that converts a string into this property's
/// element type, or else throws an error.
public init<T>(
wrappedValue: Array<T>,
name: NameSpecification = .long,
Expand Down
3 changes: 3 additions & 0 deletions Sources/ArgumentParser/Parsable Types/ParsableCommand.swift
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,9 @@ extension ParsableCommand {
/// Returns the usage text for the given subcommand of this command.
///
/// - Parameters:
/// - subcommand: The subcommand to generate the help screen for.
/// `subcommand` must be declared in the subcommand tree of this
/// command.
/// - includeHidden: Include hidden help information in the generated
/// message.
/// - Returns: The usage text for this type.
Expand Down