- Remove DispatchSemaphore usage that violated Swift concurrency rules - Implement RunLoop-based async-to-sync bridging in runAsyncCapture() - Convert all capture methods to async/await patterns - Replace Thread.sleep with Task.sleep in async contexts - Keep ParsableCommand for compatibility, avoid AsyncParsableCommand issues - Add comprehensive tests and documentation - Improve error handling and browser helper filtering 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com>
32 KiB
https://swiftpackageindex.com/apple/swift-argument-parser/1.5.1/documentation/argumentparser llms-full.txt
Swift Argument Parser
Framework
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. For async renditions of run, declare AsyncParsableCommand conformance instead.
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? = nil
mutating func run() throws {
let repeatCount = count ?? 2
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.
Additional Resources
Topics
Essentials
Getting Started with ArgumentParser
Learn to set up and customize a simple command-line tool.
A type that can be executed as part of a nested tree of commands.
A type that can be executed asynchronously, as part of a nested tree of commands.
Defining Commands and Subcommands
Break complex command-line tools into a tree of subcommands.
Define your command’s abstract, extended discussion, or usage string, and set the flags used to invoke the help display.
Arguments, Options, and Flags
Declaring Arguments, Options, and Flags
Use the @Argument, @Option and @Flag property wrappers to declare the command-line interface for your command.
A property wrapper that represents a positional command-line argument.
A property wrapper that represents a command-line option.
A property wrapper that represents a command-line flag.
A wrapper that transparently includes a parsable type.
A type that can be parsed from a program’s command-line arguments.
Property Customization
Support your users (and yourself) by providing rich help for arguments, options, and flags.
Help information for a command-line argument.
Visibility level of an argument’s help.
A specification for how to represent a property as a command-line argument label.
Custom Types
protocol ExpressibleByArgument
A type that can be expressed as a command-line argument.
A type that represents the different possible flags to be used by a @Flag property.
Validation and Errors
Provide helpful feedback to users when things go wrong.
An error type that is presented to the user as an error with parsing their command-line input.
An error type that represents a clean (i.e. non-error state) exit of the utility.
An error type that only includes an exit code.
Shell Completion Scripts
Generating and Installing Completion Scripts
Install shell completion scripts generated by your command-line tool.
Provide custom shell completions for your command-line tool’s arguments and options.
The type of completion to use for an argument or option.
Advanced Topics
Provide your own array of command-line inputs or work directly with parsed command-line arguments.
Learn about ArgumentParser’s experimental features.
Structures
A set of commands grouped together under a common name.
Extended Modules
Current page is ArgumentParser
| |
Customizing Completions
- ArgumentParser
- Customizing Completions
Article
Customizing Completions
Provide custom shell completions for your command-line tool’s arguments and options.
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.
When declaring an option or argument, you can customize the completions that are offered by specifying a CompletionKind. With this completion kind you can specify that the value should be a file, a directory, or one of a list of strings:
struct Example: ParsableCommand {
@Option(help: "The file to read from.", completion: .file())
var input: String
@Option(help: "The output directory.", completion: .directory)
var outputDir: String
@Option(help: "The preferred file format.", completion: .list(["markdown", "rst"]))
var format: String
enum CompressionType: String, CaseIterable, ExpressibleByArgument {
case zip, gzip
}
@Option(help: "The compression type to use.")
var compression: CompressionType
}
The generated completion script will suggest only file names for the --input option, only directory names for --output-dir, and only the strings markdown and rst for --format. The --compression option uses the default completions for a CaseIterable type, so the completion script will suggest zip and gzip.
You can define the default completion kind for custom ExpressibleByArgument types by implementing defaultCompletionKind. For example, any arguments or options with this File type will automatically use files for completions:
struct File: Hashable, ExpressibleByArgument {
var path: String
init?(argument: String) {
self.path = argument
}
static var defaultCompletionKind: CompletionKind {
.file()
}
}
For even more control over the suggested completions, you can specify a function that will be called during completion by using the .custom completion kind.
func listExecutables(_ arguments: [String]) -> [String] {
// Generate the list of executables in the current directory
}
struct SwiftRun {
@Option(help: "The target to execute.", completion: .custom(listExecutables))
var target: String?
}
In this example, when a user requests completions for the --target option, the completion script runs the SwiftRun command-line tool with a special syntax, calling the listExecutables function with an array of the arguments given so far.
See Also
Shell Completion Scripts
Generating and Installing Completion Scripts
Install shell completion scripts generated by your command-line tool.
The type of completion to use for an argument or option.
Current page is Customizing Completions
| |
OptionGroup Overview
- ArgumentParser
- OptionGroup
Structure
OptionGroup
A wrapper that transparently includes a parsable type.
@propertyWrapper
struct OptionGroup<Value> where Value : ParsableArguments
Overview
Use an option group to include a group of options, flags, or arguments declared in a parsable type.
struct GlobalOptions: ParsableArguments {
@Flag(name: .shortAndLong)
var verbose: Bool
@Argument var values: [Int]
}
struct Options: ParsableArguments {
@Option var name: String
@OptionGroup var globals: GlobalOptions
}
The flag and positional arguments declared as part of GlobalOptions are included when parsing Options.
Topics
Creating an Option Group
init(title: String, visibility: ArgumentVisibility)
Creates a property that represents another parsable type, using the specified title and visibility.
Option Group Properties
The title to use in the help screen for this option group.
Infrequently Used APIs
Creates a property that represents another parsable type.
Deprecated
The value presented by this property wrapper.
Default Implementations
API Reference\ CustomStringConvertible Implementations
Relationships
Conforms To
Swift.CopyableSwift.CustomStringConvertibleSwift.DecodableSwift.Sendable
See Also
Arguments, Options, and Flags
Declaring Arguments, Options, and Flags
Use the @Argument, @Option and @Flag property wrappers to declare the command-line interface for your command.
A property wrapper that represents a positional command-line argument.
A property wrapper that represents a command-line option.
A property wrapper that represents a command-line flag.
A type that can be parsed from a program’s command-line arguments.
Current page is OptionGroup
| |
ArgumentParser Flag
- ArgumentParser
- Flag
- wrappedValue
Instance Property
wrappedValue
The value presented by this property wrapper.
var wrappedValue: Value { get set }
Current page is wrappedValue
| |
chooseLast Flag
- ArgumentParser
- FlagExclusivity
- chooseLast
Type Property
chooseLast
The last enumeration case that is provided is used.
static var chooseLast: FlagExclusivity { get }
Current page is chooseLast
| |
Exclusive Flag Usage
- ArgumentParser
- FlagExclusivity
- exclusive
Type Property
exclusive
Only one of the enumeration cases may be provided.
static var exclusive: FlagExclusivity { get }
Current page is exclusive
| |
ValidationError Message
- ArgumentParser
- ValidationError
- message
Instance Property
message
The error message represented by this instance, this string is presented to the user when a ValidationError is thrown from either; run(), validate() or a transform closure.
var message: String { get }
Current page is message
| |
Swift Argument Parser
- ArgumentParser
- ParsableCommand
- main()
Type Method
main()
Executes this command, or one of its subcommands, with the program’s command-line arguments.
static func main()
Discussion
Instead of calling this method directly, you can add @main to the root command for your command-line tool.
This method parses an instance of this type, one of its subcommands, or another built-in ParsableCommand type, from command-line arguments, and then calls its run() method, exiting with a relevant error message if necessary.
See Also
Starting the Program
Executes this command, or one of its subcommands, with the given arguments.
Current page is main()
| |
Extended Grapheme Initializer
- ArgumentParser
- ArgumentHelp
- init(extendedGraphemeClusterLiteral:)
Initializer
init(extendedGraphemeClusterLiteral:)
Inherited from ExpressibleByStringLiteral.init(extendedGraphemeClusterLiteral:).
ArgumentParserSwift
init(extendedGraphemeClusterLiteral value: Self.StringLiteralType)
Available when ExtendedGraphemeClusterLiteralType is Self.StringLiteralType.
Current page is init(extendedGraphemeClusterLiteral:)
| |
ArgumentHelp Initializer
- ArgumentParser
- ArgumentHelp
- init(stringLiteral:)
Initializer
init(stringLiteral:)
Inherited from ExpressibleByStringLiteral.init(stringLiteral:).
init(stringLiteral value: String)
Current page is init(stringLiteral:)
| |
Swift run() Method
Instance Method
run()
Inherited from ParsableCommand.run().
mutating func run() throws
Current page is run()
| |
FlagInversion Operator
- ArgumentParser
- FlagInversion
- !=(_:_:)
Operator
!=(_:_:)
Inherited from Equatable.!=(_:_:).
ArgumentParserSwift
static func != (lhs: Self, rhs: Self) -> Bool
Current page is !=(_:_:)
| |
Argument Help Initializer
- ArgumentParser
- ArgumentHelp
- init(_:discussion:valueName:visibility:)
Initializer
init(_:discussion:valueName:visibility:)
Creates a new help instance.
init(
_ abstract: String = "",
discussion: String = "",
valueName: String? = nil,
visibility: ArgumentVisibility = .default
)
Current page is init(_:discussion:valueName:visibility:)
| |
CustomStringConvertible Implementations
- ArgumentParser
- OptionGroup
- CustomStringConvertible Implementations
API Collection
CustomStringConvertible Implementations
Topics
Instance Properties
Current page is CustomStringConvertible Implementations
| |
Grapheme Cluster Implementations
- ArgumentParser
- ArgumentHelp
- ExpressibleByExtendedGraphemeClusterLiteral Implementations
API Collection
ExpressibleByExtendedGraphemeClusterLiteral Implementations
Topics
Initializers
init(unicodeScalarLiteral: Self.ExtendedGraphemeClusterLiteralType)
Current page is ExpressibleByExtendedGraphemeClusterLiteral Implementations
| |
String Literal Implementations
- ArgumentParser
- ArgumentHelp
- ExpressibleByStringLiteral Implementations
API Collection
ExpressibleByStringLiteral Implementations
Topics
Initializers
init(extendedGraphemeClusterLiteral: Self.StringLiteralType)
Current page is ExpressibleByStringLiteral Implementations
| |
