Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
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
76 changes: 76 additions & 0 deletions Package@swift-5.5.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
// swift-tools-version:5.5
//===----------------------------------------------------------*- 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
//
//===----------------------------------------------------------------------===//

import PackageDescription

var package = Package(
name: "swift-argument-parser",
products: [
.library(
name: "ArgumentParser",
targets: ["ArgumentParser"]),
],
dependencies: [],
targets: [
.target(
name: "ArgumentParser",
dependencies: ["ArgumentParserToolInfo"],
exclude: ["CMakeLists.txt"]),
.target(
name: "ArgumentParserTestHelpers",
dependencies: ["ArgumentParser", "ArgumentParserToolInfo"],
exclude: ["CMakeLists.txt"]),
.target(
name: "ArgumentParserToolInfo",
dependencies: [],
exclude: ["CMakeLists.txt"]),

.executableTarget(
name: "roll",
dependencies: ["ArgumentParser"],
path: "Examples/roll"),
.executableTarget(
name: "math",
dependencies: ["ArgumentParser"],
path: "Examples/math"),
.executableTarget(
name: "repeat",
dependencies: ["ArgumentParser"],
path: "Examples/repeat"),

.executableTarget(
name: "changelog-authors",
dependencies: ["ArgumentParser"],
path: "Tools/changelog-authors"),

.testTarget(
name: "ArgumentParserEndToEndTests",
dependencies: ["ArgumentParser", "ArgumentParserTestHelpers"],
exclude: ["CMakeLists.txt"]),
.testTarget(
name: "ArgumentParserUnitTests",
dependencies: ["ArgumentParser", "ArgumentParserTestHelpers"],
exclude: ["CMakeLists.txt"]),
.testTarget(
name: "ArgumentParserExampleTests",
dependencies: ["ArgumentParserTestHelpers"]),
]
)

#if swift(>=5.2)
// Skip if < 5.2 to avoid issue with nested type synthesized 'CodingKeys'
package.targets.append(
.testTarget(
name: "ArgumentParserPackageManagerTests",
dependencies: ["ArgumentParser", "ArgumentParserTestHelpers"],
exclude: ["CMakeLists.txt"]))
#endif
104 changes: 104 additions & 0 deletions Sources/ArgumentParser/Documentation.docc/ArgumentParser.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
# ``ArgumentParser``

Straightforward, type-safe argument parsing for Swift.

## Overview

By using `ArgumentParser`, you can create a command-line interface tool
by declaring simple Swift types.
Begin by declaring a type that defines
the information that you need to collect from the command line.
Decorate each stored property with one of `ArgumentParser`'s property wrappers,
declare conformance to ``ParsableCommand``,
and implement your command's logic in its `run()` method.

```swift
import ArgumentParser

@main
struct Repeat: ParsableCommand {
@Argument(help: "The phrase to repeat.")
var phrase: String

@Option(help: "The number of times to repeat 'phrase'.")
var count: Int?

mutating func run() throws {
let repeatCount = count ?? .max
for _ in 0..<repeatCount {
print(phrase)
}
}
}
```

When a user executes your command,
the `ArgumentParser` library parses the command-line arguments,
instantiates your command type,
and then either calls your `run()` method or exits with a useful message.

```
$ repeat hello --count 3
hello
hello
hello
$ repeat --help
USAGE: repeat [--count <count>] <phrase>

ARGUMENTS:
<phrase> The phrase to repeat.

OPTIONS:
--count <count> The number of times to repeat 'phrase'.
-h, --help Show help for this command.
$ repeat --count 3
Error: Missing expected argument 'phrase'.
Help: <phrase> The phrase to repeat.
Usage: repeat [--count <count>] <phrase>
See 'repeat --help' for more information.
```

## Topics

### Essentials

- <doc:GettingStarted>
- <doc:CommandsAndSubcommands>
- ``ParsableCommand``

### Arguments, Options, and Flags

- <doc:DeclaringArguments>
- ``Argument``
- ``Option``
- ``Flag``
- ``OptionGroup``
- ``ParsableArguments``

### Property Customization

- <doc:CustomizingHelp>
- ``ArgumentHelp``
- ``NameSpecification``

### Custom Types

- ``ExpressibleByArgument``
- ``EnumerableFlag``

### Validation and Errors

- <doc:Validation>
- ``ValidationError``
- ``CleanExit``
- ``ExitCode``

### Shell Completion Scripts

- <doc:InstallingCompletionScripts>
- <doc:CustomizingCompletions>
- ``CompletionKind``

### Advanced Topics

- <doc:ManualParsing>
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# Defining Commands and Subcommands

Break complex command-line tools into a tree of subcommands.

## Overview

When command-line programs grow larger, it can be useful to divide them into a group of smaller programs, providing an interface through subcommands. Utilities such as `git` and the Swift package manager are able to provide varied interfaces for each of their sub-functions by implementing subcommands such as `git branch` or `swift package init`.

Generally, these subcommands each have their own configuration options, as well as options that are shared across several or all aspects of the larger program.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,64 +1,8 @@
# Completion Scripts
# Customizing Completions

Generate customized completion scripts for your shell of choice.
Provide custom shell completions for your command-line tool's arguments and options.

## Generating and Installing Completion Scripts

Command-line tools that you build with `ArgumentParser` include a built-in option for generating completion scripts, with support for Bash, Z shell, and Fish. To generate completions, run your command with the `--generate-completion-script` flag to generate completions for the autodetected shell, or with a value to generate completions for a specific shell.

```
$ example --generate-completion-script bash
#compdef example
local context state state_descr line
_example_commandname="example"
typeset -A opt_args

_example() {
integer ret=1
local -a args
...
}

_example
```

The correct method of installing a completion script depends on your shell and your configuration.

### Installing Zsh Completions

If you have [`oh-my-zsh`](https://ohmyz.sh) installed, you already have a directory of automatically loading completion scripts — `.oh-my-zsh/completions`. Copy your new completion script to that directory.

```
$ example --generate-completion-script zsh > ~/.oh-my-zsh/completions/_example
```

> Your completion script must have the following filename format: `_example`.

Without `oh-my-zsh`, you'll need to add a path for completion scripts to your function path, and turn on completion script autoloading. First, add these lines to `~/.zshrc`:

```
fpath=(~/.zsh/completion $fpath)
autoload -U compinit
compinit
```

Next, create a directory at `~/.zsh/completion` and copy the completion script to the new directory.

### Installing Bash Completions

If you have [`bash-completion`](https://github.com/scop/bash-completion) installed, you can just copy your new completion script to the `/usr/local/etc/bash_completion.d` directory.

Without `bash-completion`, you'll need to source the completion script directly. Copy it to a directory such as `~/.bash_completions/`, and then add the following line to `~/.bash_profile` or `~/.bashrc`:

```
source ~/.bash_completions/example.bash
```

### Installing Fish Completions

Copy the completion script to any path listed in the environment variable `$fish_completion_path`. For example, a typical location is `~/.config/fish/completions/your_script.fish`.

## Customizing Completions
## Overview

`ArgumentParser` provides default completions for any types that it can. For example, an `@Option` property that is a `CaseIterable` type will automatically have the correct values as completion suggestions.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

Support your users (and yourself) by providing rich help for arguments and commands.

## Overview

You can provide help text when declaring any `@Argument`, `@Option`, or `@Flag` by passing a string literal as the `help` parameter:

```swift
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

Use the `@Argument`, `@Option` and `@Flag` property wrappers to declare the command-line interface for your command.

## Overview

When creating commands, you can define three primary kinds of command-line inputs:

- *Arguments* are values given by a user and are read in order from first to last. For example, this command is called with three file names as arguments:
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
# Getting Started with `ArgumentParser`
# Getting Started with ArgumentParser

Learn to set up and customize a simple command-line tool.

## Overview

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 @@ -19,7 +21,7 @@ import PackageDescription
let package = Package(
name: "random",
dependencies: [
.package(url: "https://github.com/apple/swift-argument-parser.git", from: "0.5.0"),
.package(url: "https://github.com/apple/swift-argument-parser.git", from: "0.4.0"),
],
targets: [
.target(
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
# Generating and Installing Completion Scripts

Install shell completion scripts generated by your command-line tool.

## Overview

Command-line tools that you build with `ArgumentParser` include a built-in option for generating completion scripts, with support for Bash, Z shell, and Fish. To generate completions, run your command with the `--generate-completion-script` option to generate completions for your specific shell.

```
$ example --generate-completion-script bash
#compdef example
local context state state_descr line
_example_commandname="example"
typeset -A opt_args

_example() {
integer ret=1
local -a args
...
}

_example
```

The correct method of installing a completion script can depend on both your shell and your configuration.

### Installing Zsh Completions

If you have [`oh-my-zsh`](https://ohmyz.sh) installed, you already have a directory of automatically loading completion scripts — `.oh-my-zsh/completions`. Copy your new completion script to that directory.

```
$ example --generate-completion-script zsh > ~/.oh-my-zsh/completions/_example
```

> Your completion script must have the following filename format: `_example`.

Without `oh-my-zsh`, you'll need to add a path for completion scripts to your function path, and turn on completion script autoloading. First, add these lines to `~/.zshrc`:

```
fpath=(~/.zsh/completion $fpath)
autoload -U compinit
compinit
```

Next, create a directory at `~/.zsh/completion` and copy the completion script to the new directory.

### Installing Bash Completions

If you have [`bash-completion`](https://github.com/scop/bash-completion) installed, you can just copy your new completion script to the `/usr/local/etc/bash_completion.d` directory.

Without `bash-completion`, you'll need to source the completion script directly. Copy it to a directory such as `~/.bash_completions/`, and then add the following line to `~/.bash_profile` or `~/.bashrc`:

```
source ~/.bash_completions/example.bash
```

### Installing Fish Completions

Copy the completion script to any path listed in the environment variable `$fish_completion_path`. For example, a typical location is `~/.config/fish/completions/your_script.fish`.
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

Provide your own array of command-line inputs and work with parsed results by calling alternatives to `main()`.

## Overview

For most programs, calling the static `main()` method on the root command type is all that's necessary. That single call 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
Expand All @@ -28,7 +30,7 @@ The static `parseOrExit()` method either returns a fully initialized instance of
We can perform validation on the inputs and exit the script if necessary:

```swift
guard options.elements.count >= options.count else {
guard let options.elements.count >= options.count else {
let error = ValidationError("Please specify a 'count' less than the number of elements.")
SelectOptions.exit(withError: error)
}
Expand Down Expand Up @@ -101,12 +103,3 @@ howdy
howdy
hi
```









Loading