### Project Setup and Options Source: https://github.com/apple/swift-argument-parser/blob/main/CMakeLists.txt Configures the CMake version, project name, languages, and build options for examples and shared libraries. ```cmake cmake_minimum_required(VERSION 3.19) # Due to a bug in CMake, we need to enable the C language before we can use # GNUInstallDirs. project(swift-argument-parser LANGUAGES C Swift) option(BUILD_EXAMPLES "Build Example Programs" TRUE) option(BUILD_SHARED_LIBS "Build shared libraries by default" YES) ``` -------------------------------- ### Install Fish Completion Script Source: https://github.com/apple/swift-argument-parser/blob/main/Sources/ArgumentParser/Documentation.docc/Articles/InstallingCompletionScripts.md Copy the generated Fish completion script to a directory listed in the `$fish_completion_path` environment variable, such as `~/.config/fish/completions/your_script.fish`. ```fish # Example installation path for Fish completions # ~/.config/fish/completions/your_script.fish ``` -------------------------------- ### Enumerable Flag Usage Examples Source: https://github.com/apple/swift-argument-parser/blob/main/Sources/ArgumentParser/Documentation.docc/Articles/DeclaringArguments.md Shows how to use flags defined with enumerations. The examples demonstrate parsing custom flag names and handling missing required flags. ```shell % example --in-memory-cache --pink --silver .inMemoryCache [.pink, .silver] % example Error: Missing one of: '--in-memory-cache', '--persistent-cache' ``` -------------------------------- ### Install Bash Completion Script Source: https://github.com/apple/swift-argument-parser/blob/main/Sources/ArgumentParser/Documentation.docc/Articles/InstallingCompletionScripts.md If `bash-completion` is installed, copy the generated script to `/usr/local/etc/bash_completion.d/`. Otherwise, source the script directly from a custom directory. ```bash source ~/.bash_completions/example.bash ``` -------------------------------- ### Install Zsh Completion Script with Oh My Zsh Source: https://github.com/apple/swift-argument-parser/blob/main/Sources/ArgumentParser/Documentation.docc/Articles/InstallingCompletionScripts.md To install Zsh completions when using Oh My Zsh, copy the generated script to the `.oh-my-zsh/completions` directory. Ensure the filename follows the `_example` format. ```bash $ example --generate-completion-script zsh > ~/.oh-my-zsh/completions/_example ``` -------------------------------- ### Example Command-Line Usage and Help Output Source: https://github.com/apple/swift-argument-parser/blob/main/README.md Demonstrates how the Swift Argument Parser library handles command-line arguments, including successful execution, error messages for missing arguments, and the generated help information. ```bash $ repeat hello --count 3 hello hello hello ``` ```bash $ repeat --count 3 Error: Missing expected argument 'phrase'. Help: The phrase to repeat. Usage: repeat [--count ] [--include-counter] See 'repeat --help' for more information. ``` ```bash $ repeat --help USAGE: repeat [--count ] [--include-counter] ARGUMENTS: The phrase to repeat. OPTIONS: --include-counter Include a counter with each repetition. -c, --count The number of times to repeat 'phrase'. -h, --help Show help for this command. ``` -------------------------------- ### Flag Inversion Examples Source: https://github.com/apple/swift-argument-parser/blob/main/Sources/ArgumentParser/Documentation.docc/Articles/DeclaringArguments.md Demonstrates how to use prefixed flags for boolean properties. The output shows the effect of different flag combinations. ```shell % example --enable-required-element true true % example --no-index --disable-required-element false false % example --index Error: Missing one of: '--enable-required-element', '--disable-required-element' ``` -------------------------------- ### Generate Bash Completion Script Source: https://github.com/apple/swift-argument-parser/blob/main/Sources/ArgumentParser/Documentation.docc/Articles/InstallingCompletionScripts.md Run your command with the `--generate-completion-script bash` option to output a completion script for Bash. This script can then be installed according to your Bash environment setup. ```bash $ example --generate-completion-script bash #compdef example _example() { ... } _example ``` -------------------------------- ### Provide Custom Input for Parsing Source: https://github.com/apple/swift-argument-parser/blob/main/Sources/ArgumentParser/Documentation.docc/Articles/ManualParsing.md Test commands or manually execute them by providing a custom array of command-line inputs to parsing methods. This example filters out shouting phrases before parsing. ```swift let noShoutingArguments = CommandLine.arguments.dropFirst().filter { phrase.uppercased() != phrase } let options = SelectOptions.parseOrExit(noShoutingArguments) ``` -------------------------------- ### Repeat Help Subcommand Source: https://github.com/apple/swift-argument-parser/blob/main/Tests/ArgumentParserGenerateDoccReferenceTests/Snapshots/testRepeatMarkdownReference().md This snippet shows how to get help for the 'repeat' command and its subcommands. ```APIDOC ## repeat help ### Description Shows subcommand help information for the 'repeat' command. ### Method N/A (Command-line tool) ### Endpoint N/A (Command-line tool) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Command Line Usage ``` repeat help [...] ``` ### Arguments - **subcommands** (String) - Optional - The subcommands for which to show help. ### Request Example ```bash repeat help ``` ### Response #### Success Response (Output) - Help information for the specified subcommands or general help if no subcommand is provided. ``` -------------------------------- ### Define Main Entry Point with @main in Swift Source: https://github.com/apple/swift-argument-parser/blob/main/Sources/ArgumentParser/Documentation.docc/Articles/CommandsAndSubcommands.md Marks the 'Math' struct as the main entry point for the command-line application. The Swift compiler uses this attribute to determine the program's execution start. ```swift @main struct Math: ParsableCommand { // ... } ``` -------------------------------- ### Handle Invalid JSON Input Source: https://github.com/apple/swift-argument-parser/blob/main/Sources/ArgumentParser/Documentation.docc/Articles/Validation.md Example of running the command with invalid JSON input, demonstrating the `ValidationError` thrown by the `ExampleDataModel.dataModel` transform. ```shell % example '{"Bad JSON"}' Error: The value '{"Bad JSON"}' is invalid for '': dataCorrupted(Swift.DecodingError.Context(codingPath: [], debugDescription: "The given data was not valid JSON.", underlyingError: Optional(Error Domain=NSCocoaErrorDomain Code=3840 "No value for key in object around character 11." UserInfo={NSDebugDescription=No value for key in object around character 11.}))) Usage: example --fail-option See 'select --help' for more information. ``` -------------------------------- ### Integer Flag Counting Examples Source: https://github.com/apple/swift-argument-parser/blob/main/Sources/ArgumentParser/Documentation.docc/Articles/DeclaringArguments.md Illustrates how an `Int` flag can be used to count occurrences. The output shows the verbosity level based on the number of times the flag is provided. ```shell % example --verbose Verbosity level: 1 % example -vvvv Verbosity level: 4 ``` -------------------------------- ### count-lines help Subcommand Source: https://github.com/apple/swift-argument-parser/blob/main/Tests/ArgumentParserGenerateDoccReferenceTests/Snapshots/testCountLinesDoccReference().md This section describes how to get help for the count-lines command and its subcommands. ```APIDOC ## count-lines help [...] ### Description Show subcommand help information. ### Method N/A (Command-line tool) ### Endpoint N/A (Command-line tool) ### Parameters #### Path Parameters - **subcommands** (string) - Optional - ### Request Example N/A (Command-line tool) ### Response N/A (Command-line tool output) ``` -------------------------------- ### Subdirectory Inclusion Source: https://github.com/apple/swift-argument-parser/blob/main/CMakeLists.txt Adds subdirectories for sources, examples, tests, and modules, conditionally based on build options. ```cmake add_subdirectory(Sources) if(BUILD_EXAMPLES) add_subdirectory(Examples) endif() if(BUILD_TESTING) add_subdirectory(Tests) endif() add_subdirectory(cmake/modules) ``` -------------------------------- ### Print Selected Elements Source: https://github.com/apple/swift-argument-parser/blob/main/Sources/ArgumentParser/Documentation.docc/Articles/ManualParsing.md Process and print the selected elements after successful parsing and validation. This example shuffles and takes a prefix of the elements. ```swift let chosen = options.elements .shuffled() .prefix(options.count) print(chosen.joined(separator: "\n")) ``` -------------------------------- ### Handle Custom Option Error Source: https://github.com/apple/swift-argument-parser/blob/main/Sources/ArgumentParser/Documentation.docc/Articles/Validation.md Example of running the command with valid JSON input but triggering the custom error defined for the `--fail-option`. ```shell % example '{"tokenCount":0,"tokens":[],"identifier":"F77D661C-C5B7-448E-9344-267B284F66AD"}' --fail-option="Some Text Here!" Error: The value 'Some Text Here!' is invalid for '--fail-option ': Trying to write to failOption always produces an error. Input: Some Text Here! Usage: example --fail-option See 'select --help' for more information. ``` -------------------------------- ### Build roll executable with ArgumentParser Source: https://github.com/apple/swift-argument-parser/blob/main/Examples/CMakeLists.txt Defines a CMake executable named 'roll' that links against the Swift Argument Parser library. This example includes multiple source files for the executable. ```cmake add_executable(roll roll/main.swift roll/SplitMix64.swift) target_link_libraries(roll PRIVATE ArgumentParser) ``` -------------------------------- ### Use .unconditional Parsing Strategy for Options Source: https://github.com/apple/swift-argument-parser/blob/main/Sources/ArgumentParser/Documentation.docc/Articles/DeclaringArguments.md Employ the `.unconditional` parsing strategy to force an option to always take the immediate next input as its value, even if it starts with a dash. This can lead to unexpected behavior if not used carefully. ```swift @Option(parsing: .unconditional) var name: String ``` -------------------------------- ### Help Screen with Grouped Arguments Source: https://github.com/apple/swift-argument-parser/blob/main/Sources/ArgumentParser/Documentation.docc/Articles/CustomizingHelp.md Observe how the arguments are presented in the help screen, with the 'Build Options' group clearly delineated. This output is generated by running the command with the --help flag. ```text % example --help USAGE: example [--verbose] [--config-file ] [--compiler-setting ...] [--linker-setting ...] ARGUMENTS: The input file to process. BUILD OPTIONS: --compiler-setting A setting to pass to the compiler. --linker-setting A setting to pass to the linker. OPTIONS: --verbose Show extra output. --config-file The path to a configuration file. -h, --help Show help information. ``` -------------------------------- ### Creating a Configuration Source: https://github.com/apple/swift-argument-parser/blob/main/Sources/ArgumentParser/Documentation.docc/Extensions/CommandConfiguration.md Initializes a CommandConfiguration with various customizable properties. ```APIDOC ## Initializing CommandConfiguration ### Description Initializes a new `CommandConfiguration` instance. ### Method `init` ### Parameters - **commandName** (String) - The name of the command. - **abstract** (String) - A short description of the command. - **usage** (String) - The usage string for the command. - **discussion** (String) - A detailed discussion of the command. - **version** (String) - The version of the command. - **shouldDisplay** (Bool) - Whether to display the command in help output. - **subcommands** ([ParsableCommand]) - An array of subcommands. - **groupedSubcommands** ([[ParsableCommand]]) - An array of grouped subcommands. - **defaultSubcommand** (ParsableCommand.Type?) - The default subcommand to run. - **helpNames** (OptionSet) - Custom names for the help flag. ``` -------------------------------- ### Async Main Entry Point for Swift 5.5 Source: https://github.com/apple/swift-argument-parser/blob/main/Sources/ArgumentParser/Documentation.docc/Extensions/AsyncParsableCommand.md In Swift 5.5, use this structure for the main entry point when your root command cannot be designated with @main. Replace <#RootCommand#> with your command's type. ```swift @main struct AsyncMain: AsyncMainProtocol { typealias Command = <#RootCommand#> } ``` -------------------------------- ### Repeat Command Help Source: https://github.com/apple/swift-argument-parser/blob/main/Tests/ArgumentParserGenerateDoccReferenceTests/Snapshots/testRepeatDoccReference().md Shows how to display help information for the 'repeat' command and its subcommands. This is useful for understanding available options. ```swift repeat help [...] ``` -------------------------------- ### Directory Configuration Source: https://github.com/apple/swift-argument-parser/blob/main/CMakeLists.txt Sets the output directories for archives, libraries, executables, and Swift modules. ```cmake list(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/cmake/modules) set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib) set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib) set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin) set(CMAKE_Swift_MODULE_DIRECTORY ${CMAKE_BINARY_DIR}/swift) ``` -------------------------------- ### Include Modules and Support Source: https://github.com/apple/swift-argument-parser/blob/main/CMakeLists.txt Includes CMake modules for testing and Swift support. ```cmake include(CTest) include(GNUInstallDirs) include(SwiftSupport) ``` -------------------------------- ### Math Help Command Source: https://github.com/apple/swift-argument-parser/blob/main/Tests/ArgumentParserGenerateDoccReferenceTests/Snapshots/testMathDoccReference().md Displays subcommand help information. Accepts a list of subcommands and supports version/help flags. ```bash math help [...] [--version] ``` -------------------------------- ### Define Nested Statistics Command Source: https://github.com/apple/swift-argument-parser/blob/main/Sources/ArgumentParser/Documentation.docc/Articles/CommandsAndSubcommands.md Define a 'Statistics' subcommand that itself has subcommands. This example sets a custom command name 'stats' and declares 'Average' and 'StandardDeviation' as its subcommands. ```swift extension Math { struct Statistics: ParsableCommand { static let configuration = CommandConfiguration( commandName: "stats", abstract: "Calculate descriptive statistics.", subcommands: [Average.self, StandardDeviation.self]) } } ``` -------------------------------- ### Repeat Command Help Source: https://github.com/apple/swift-argument-parser/blob/main/Tests/ArgumentParserGenerateDoccReferenceTests/Snapshots/testRepeatMarkdownReference().md Shows how to access help information for the 'repeat' subcommand and its potential subcommands. ```swift repeat help [...] ``` -------------------------------- ### Define Shared Arguments with ParsableArguments Source: https://github.com/apple/swift-argument-parser/blob/main/Sources/ArgumentParser/Documentation.docc/Articles/CommandsAndSubcommands.md Create a type conforming to `ParsableArguments` to define arguments shared across multiple subcommands. This example includes a flag and a list of integers. ```swift struct Options: ParsableArguments { @Flag(name: [.long, .customShort("x")], help: "Use hexadecimal notation for the result.") var hexadecimalOutput = false @Argument(help: "A group of integers to operate on.") var values: [Int] } ``` -------------------------------- ### Define Root Command with Subcommands Source: https://github.com/apple/swift-argument-parser/blob/main/Sources/ArgumentParser/Documentation.docc/Articles/CommandsAndSubcommands.md Define the main command for your application and list its subcommands. A default subcommand can be specified. ```swift struct Math: ParsableCommand { static let configuration = CommandConfiguration( abstract: "A utility for performing maths.", subcommands: [Add.self, Multiply.self, Statistics.self], defaultSubcommand: Add.self) } ``` -------------------------------- ### Main Math Utility Command Source: https://github.com/apple/swift-argument-parser/blob/main/Tests/ArgumentParserGenerateDoccReferenceTests/Snapshots/testMathDoccReference().md The base command for the math utility. Use --version to show the version and --help for usage information. ```bash math [--version] [--help] ``` -------------------------------- ### math.help Source: https://github.com/apple/swift-argument-parser/blob/main/Tests/ArgumentParserGenerateDoccReferenceTests/Snapshots/testMathMarkdownReference().md Displays help information for subcommands. ```APIDOC ## math.help ### Description Show subcommand help information. ### Method N/A (Command-line utility) ### Endpoint N/A ### Parameters #### Query Parameters - **--version** (flag) - Optional - Show the version. #### Path Parameters - **subcommands** (array) - Optional - ``` -------------------------------- ### Define Custom Help Text for a Command Source: https://github.com/apple/swift-argument-parser/blob/main/Sources/ArgumentParser/Documentation.docc/Articles/CustomizingCommandHelp.md Configure the abstract, usage, and discussion for a command to customize its help screen. The abstract is a short description, usage shows command syntax, and discussion provides extended information. ```swift struct Repeat: ParsableCommand { static let configuration = CommandConfiguration( abstract: "Repeats your input phrase.", usage: """ repeat repeat --count """, discussion: """ Prints to stdout forever, or until you halt the program. """) @Argument(help: "The phrase to repeat.") var phrase: String @Option(help: "How many times to repeat.") var count: Int? = nil mutating func run() throws { for _ in 0..<(count ?? 2) { print(phrase) } } } ``` -------------------------------- ### math.help Source: https://github.com/apple/swift-argument-parser/blob/main/Tests/ArgumentParserGenerateDoccReferenceTests/Snapshots/testMathDoccReference().md Displays help information for subcommands within the math utility. ```APIDOC ## math.help ### Description Show subcommand help information. ### Method N/A (CLI Tool) ### Endpoint N/A (CLI Tool) ### Parameters #### Query Parameters - **--version** (flag) - Optional - Show the version. #### Path Parameters - **subcommands** (array of strings) - Optional - The subcommands to show help for. ``` -------------------------------- ### Handle Array Arguments with Default Values Source: https://github.com/apple/swift-argument-parser/blob/main/Sources/ArgumentParser/Documentation.docc/Articles/DeclaringArguments.md When an array property has a default value, user-supplied values replace the entire default array. This example demonstrates how to display lucky numbers provided by the user or the default set. ```swift struct Lucky: ParsableCommand { @Argument var numbers = [7, 14, 21] mutating func run() throws { print(""" Your lucky numbers are: \(numbers.map(String.init).joined(separator: " ")) """) } } ``` -------------------------------- ### Generate Help Text Programmatically Source: https://github.com/apple/swift-argument-parser/blob/main/Sources/ArgumentParser/Documentation.docc/Articles/CustomizingCommandHelp.md Generate the help message for a command at runtime using the `helpMessage()` method. You can also specify a column width for wrapping the output. ```swift let help = Repeat.helpMessage() // `help` matches the output above let fortyColumnHelp = Repeat.helpMessage(columns: 40) // `fortyColumnHelp` is the same help screen, but wrapped to 40 columns ``` -------------------------------- ### Validate Command-Line Input with `validate()` Source: https://github.com/apple/swift-argument-parser/blob/main/Sources/ArgumentParser/Documentation.docc/Articles/Validation.md Implement the `validate()` method on a `ParsableCommand` to check custom input requirements after parsing. Throw a `ValidationError` with a descriptive message to guide users when input is invalid. This method is called before `run()`. ```swift struct Select: ParsableCommand { @Option var count: Int = 1 @Argument var elements: [String] = [] mutating func validate() throws { guard count >= 1 else { throw ValidationError("Please specify a 'count' of at least 1.") } guard !elements.isEmpty else { throw ValidationError("Please provide at least one element to choose from.") } guard count <= elements.count else { throw ValidationError("Please specify a 'count' less than the number of elements.") } } mutating func run() { print(elements.shuffled().prefix(count).joined(separator: "\n")) } } ``` -------------------------------- ### Color Help Subcommand Usage Source: https://github.com/apple/swift-argument-parser/blob/main/Tests/ArgumentParserGenerateDoccReferenceTests/Snapshots/testColorMarkdownReference().md Shows how to display help information for the 'color' command's subcommands. This is useful for understanding available options and their usage. ```bash color help [...] ``` -------------------------------- ### Advanced Help Customization with ArgumentHelp Source: https://github.com/apple/swift-argument-parser/blob/main/Sources/ArgumentParser/Documentation.docc/Articles/CustomizingHelp.md Use `ArgumentHelp` instances for more control over help text, including abstract, discussion, value name, and visibility. This allows for richer descriptions and clearer usage strings. ```swift struct Example: ParsableCommand { @Flag(help: "Display extra information while processing.") var verbose = false @Option(help: ArgumentHelp( "The number of extra lines to show.", valueName: "n")) var extraLines = 0 @Argument(help: ArgumentHelp( "The input file.", discussion: "If no input file is provided, the tool reads from stdin.", valueName: "file")) var inputFile: String? } ``` -------------------------------- ### Configure Zsh for Custom Completions Source: https://github.com/apple/swift-argument-parser/blob/main/Sources/ArgumentParser/Documentation.docc/Articles/InstallingCompletionScripts.md If not using Oh My Zsh, configure your `~/.zshrc` to include a custom completion directory and enable autoloading for completion scripts. Then, place the generated script in the specified directory. ```bash fpath=(~/.zsh/completion $fpath) autoload -U compinit compinit ``` -------------------------------- ### Basic Help Text for Arguments Source: https://github.com/apple/swift-argument-parser/blob/main/Sources/ArgumentParser/Documentation.docc/Articles/CustomizingHelp.md Assign simple string literals to the `help` parameter for `@Flag`, `@Option`, and `@Argument` to provide basic help text. This text appears in the generated help screen. ```swift struct Example: ParsableCommand { @Flag(help: "Display extra information while processing.") var verbose = false @Option(help: "The number of extra lines to show.") var extraLines = 0 @Argument(help: "The input file.") var inputFile: String? } ``` -------------------------------- ### Add help text to options and flags Source: https://github.com/apple/swift-argument-parser/blob/main/Sources/ArgumentParser/Documentation.docc/Articles/GettingStarted.md Provide descriptive text for options and flags by passing a string literal to the `help` parameter in their initializers. This text appears in the automatically generated help screen. ```swift @main struct Count: ParsableCommand { @Option(name: [.short, .customLong("input")]) var inputFile: String @Option(name: [.short, .customLong("output")]) var outputFile: String @Flag(name: .shortAndLong, help: "Print status updates while counting.") var verbose = false mutating func run() throws { ... } } ``` -------------------------------- ### Async File Utility with ArgumentParser Source: https://github.com/apple/swift-argument-parser/blob/main/Sources/ArgumentParser/Documentation.docc/Articles/GettingStarted.md This Swift code demonstrates how to create an asynchronous command-line utility using `AsyncParsableCommand`. It parses a file path and iterates over its lines asynchronously. Remember to use `AsyncParsableCommand` for async `run` functions. ```swift @main struct FileUtility: AsyncParsableCommand { @Argument( help: "File to be parsed.", transform: URL.init(fileURLWithPath:) ) var file: URL mutating func run() async throws { let handle = try FileHandle(forReadingFrom: file) for try await line in handle.bytes.lines { // do something with each line } try handle.close() } } ``` -------------------------------- ### Single Arguments Source: https://github.com/apple/swift-argument-parser/blob/main/Sources/ArgumentParser/Documentation.docc/Extensions/Argument.md Initializers for defining single arguments, including options for help text, completion handlers, and value transformation. ```APIDOC ## Argument Initializers (Single Arguments) ### Description Initializers for creating single arguments with various configuration options. ### Initializers - `init(help:completion:)` - `init(help:completion:transform:)` - `init(wrappedValue:help:completion:)` - `init(wrappedValue:help:completion:transform:)` ``` -------------------------------- ### Build repeat executable with ArgumentParser Source: https://github.com/apple/swift-argument-parser/blob/main/Examples/CMakeLists.txt Sets up a CMake executable named 'repeat' that depends on the Swift Argument Parser. It also specifies the '-parse-as-library' compile option. ```cmake add_executable(repeat repeat/Repeat.swift) target_compile_options(repeat PRIVATE -parse-as-library) target_link_libraries(repeat PRIVATE ArgumentParser) ``` -------------------------------- ### Build math executable with ArgumentParser Source: https://github.com/apple/swift-argument-parser/blob/main/Examples/CMakeLists.txt Configures a CMake executable named 'math' that uses the Swift Argument Parser library. It also includes a platform-specific compile option for parsing as a library. ```cmake add_executable(math math/Math.swift) target_compile_options(math PRIVATE -parse-as-library) target_link_libraries(math PRIVATE ArgumentParser $<\:m>) ``` -------------------------------- ### Repeat Command Usage Source: https://github.com/apple/swift-argument-parser/blob/main/Tests/ArgumentParserGenerateDoccReferenceTests/Snapshots/testRepeatDoccReference().md This section describes how to use the 'repeat' command, including its arguments and options. ```APIDOC ## POST /repeat ### Description Repeats a given phrase a specified number of times, with an option to include a counter. ### Method POST ### Endpoint /repeat ### Parameters #### Query Parameters - **phrase** (string) - Required - The phrase to repeat. - **count** (integer) - Optional - How many times to repeat 'phrase'. Defaults to 1. - **include-counter** (boolean) - Optional - Include a counter with each repetition. Defaults to false. ### Request Example ```json { "phrase": "Hello, World!", "count": 3, "include-counter": true } ``` ### Response #### Success Response (200) - **repeated_text** (string) - The repeated phrase with optional counters. #### Response Example ```json { "repeated_text": "1. Hello, World!\n2. Hello, World!\n3. Hello, World!" } ``` ``` -------------------------------- ### Define Basic Flags, Options, and Arguments Source: https://github.com/apple/swift-argument-parser/blob/main/Sources/ArgumentParser/Documentation.docc/Articles/DeclaringArguments.md Define a boolean flag, a required string option, and an optional string argument for your command-line tool. The `run` function demonstrates how to access these parsed values. ```swift struct Example: ParsableCommand { @Flag var verbose = false @Option var name: String @Argument var file: String? mutating func run() throws { print("Verbose: \(verbose), name: \(name), file: \(file ?? \"none\")") } } ``` -------------------------------- ### Customizing the Help Screen Source: https://github.com/apple/swift-argument-parser/blob/main/Sources/ArgumentParser/Documentation.docc/Extensions/CommandConfiguration.md Properties for customizing the help screen output. ```APIDOC ## Customizing the Help Screen ### Description These properties allow for customization of the help screen displayed to the user. ### Properties - **abstract** (String) - A short description of the command, displayed in help output. - **discussion** (String) - A detailed explanation of the command, displayed in help output. - **usage** (String) - Custom usage information for the command. - **helpNames** (OptionSet) - Custom names that can be used to invoke the help screen (e.g., `--help`, `-h`). ``` -------------------------------- ### math Source: https://github.com/apple/swift-argument-parser/blob/main/Tests/ArgumentParserGenerateDoccReferenceTests/Snapshots/testMathMarkdownReference().md The main math utility command. ```APIDOC ## math ### Description A utility for performing maths. ### Method N/A (Command-line utility) ### Endpoint N/A ### Parameters #### Query Parameters - **--version** (flag) - Optional - Show the version. - **--help** (flag) - Optional - Show help information. ``` -------------------------------- ### Repeat Command Help Source: https://github.com/apple/swift-argument-parser/blob/main/Tests/ArgumentParserGenerateDoccReferenceTests/Snapshots/testRepeatDoccReference().md Displays help information for the 'repeat' command and its subcommands. ```APIDOC ## GET /repeat/help ### Description Shows help information for the 'repeat' command and its subcommands. ### Method GET ### Endpoint /repeat/help ### Parameters #### Query Parameters - **subcommands** (string) - Optional - Specify a subcommand to get detailed help for. ### Response #### Success Response (200) - **help_text** (string) - The help information. #### Response Example ```json { "help_text": "Usage: repeat [--count=] [--include-counter] [--help]\n\n Repeats a given phrase a specified number of times.\n\nArguments:\n The phrase to repeat.\n\nOptions:\n --count= How many times to repeat 'phrase'.\n --include-counter Include a counter with each repetition.\n --help Show help information." } ``` ``` -------------------------------- ### Declare Arguments, Options, and Flags Source: https://github.com/apple/swift-argument-parser/blob/main/Sources/ArgumentParser/Documentation.docc/Articles/DeclaringArguments.md Use `@Argument`, `@Option`, and `@Flag` property wrappers to define the command-line interface for your command. Option and flag names are derived from property names, and input validation is based on property types and default values. ```swift struct Example: ParsableCommand { @Argument var files: [String] = [] @Option var count: Int? @Option var index = 0 @Flag var verbose = false @Flag var stripWhitespace = false } ``` -------------------------------- ### Array Arguments Source: https://github.com/apple/swift-argument-parser/blob/main/Sources/ArgumentParser/Documentation.docc/Extensions/Argument.md Initializers and strategies for defining arguments that accept multiple values (arrays). ```APIDOC ## Argument Initializers (Array Arguments) ### Description Initializers and strategies for defining arguments that accept an array of values. ### Initializers - `init(parsing:help:completion:)` - `init(parsing:help:completion:transform:)` - `init(wrappedValue:parsing:help:completion:)` - `init(wrappedValue:parsing:help:completion:transform:)` ### Related Types - `ArgumentArrayParsingStrategy` ``` -------------------------------- ### Specifying Default Values for Arguments Source: https://github.com/apple/swift-argument-parser/blob/main/Sources/ArgumentParser/Documentation.docc/Articles/DeclaringArguments.md Demonstrates how to set default values for various argument types using standard Swift property initialization. This applies to flags, options, and arguments. ```swift enum CustomFlag: String, EnumerableFlag { case foo, bar, baz } struct Example: ParsableCommand { @Flag var booleanFlag = false @Flag var arrayFlag: [CustomFlag] = [.foo, .baz] @Option var singleOption = 0 @Option var arrayOption = ["bar", "qux"] @Argument var singleArgument = "quux" @Argument var arrayArgument = ["quux", "quuz"] } ``` -------------------------------- ### Generate Shell-Specific Completion Candidates Source: https://github.com/apple/swift-argument-parser/blob/main/Sources/ArgumentParser/Documentation.docc/Articles/CustomizingCompletions.md Use .custom with a function that checks CompletionShell.requesting and CompletionShell.requestingVersion to provide tailored completion candidates for different shells and versions. ```swift /// Runs during completion while user is typing command line to use your tool /// Note that the `Version` struct is not included in Swift Argument Parser func generateCompletionCandidatesPerShell(_ arguments: [String]) -> [String] { switch CompletionShell.requesting { case CompletionShell.bash: if Version(CompletionShell.requestingVersion).major >= 4 { return ["A:in:bash4+:syntax", "B:in:bash4+:syntax", "C:in:bash4+:syntax"] } else { return ["A:in:bash:syntax", "B:in:bash:syntax", "C:in:bash:syntax"] } case CompletionShell.fish: return ["A:in:fish:syntax", "B:in:bash:syntax", "C:in:bash:syntax"] case CompletionShell.zsh: return ["A:in:zsh:syntax", "B:in:zsh:syntax", "C:in:zsh:syntax"] default: return [] } } ``` -------------------------------- ### Math Utility - Root Command Source: https://github.com/apple/swift-argument-parser/blob/main/Tests/ArgumentParserGenerateDoccReferenceTests/Snapshots/testMathDoccReference().md The root command for the math utility, providing version and help information. ```APIDOC ## math ### Description A utility for performing maths. ### Method N/A (CLI Tool) ### Endpoint N/A (CLI Tool) ### Parameters #### Query Parameters - **--version** (flag) - Optional - Show the version. - **--help** (flag) - Optional - Show help information. ``` -------------------------------- ### Up To Next Option Array Parsing - ArgumentParser Source: https://github.com/apple/swift-argument-parser/blob/main/Sources/ArgumentParser/Documentation.docc/Articles/DeclaringArguments.md Utilize `.upToNextOption` to parse inputs following an option key until a dash-prefixed input is encountered. This allows specifying multiple array elements without repeating the option key. ```swift @Option(parsing: .upToNextOption) var file: [String] ``` -------------------------------- ### Repeat Command Usage Source: https://github.com/apple/swift-argument-parser/blob/main/Tests/ArgumentParserGenerateDoccReferenceTests/Snapshots/testRepeatDoccReference().md Defines the structure and options for the 'repeat' command. Use this to repeat a given phrase. ```swift repeat [--count=] [--include-counter] [--help] ``` -------------------------------- ### Define a Basic ParsableCommand with Positional Arguments Source: https://github.com/apple/swift-argument-parser/blob/main/Sources/ArgumentParser/Documentation.docc/Articles/GettingStarted.md Implement a command-line tool by conforming to ParsableCommand and using the @Argument property wrapper for positional inputs. The @main attribute designates this struct as the program's entry point. ```swift import ArgumentParser @main struct Count: ParsableCommand { @Argument var inputFile: String @Argument var outputFile: String mutating func run() throws { print(""" Counting words in '\(inputFile)' \ and writing the result into '\(outputFile)'. """) // Read 'inputFile', count the words, and save to 'outputFile'. } } ``` -------------------------------- ### Boolean Flags Source: https://github.com/apple/swift-argument-parser/blob/main/Sources/ArgumentParser/Documentation.docc/Extensions/Flag.md Initializers for creating simple boolean flags. ```APIDOC ## Initializers for Boolean Flags ### Description Provides initializers for creating boolean flags. ### Method `init(wrappedValue:name:help:)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Implement Add Subcommand with OptionGroup Source: https://github.com/apple/swift-argument-parser/blob/main/Sources/ArgumentParser/Documentation.docc/Articles/CommandsAndSubcommands.md Implement the 'Add' subcommand, using `@OptionGroup` to include shared arguments. This subcommand calculates and prints the sum of the provided values. ```swift extension Math { struct Add: ParsableCommand { static let configuration = CommandConfiguration(abstract: "Print the sum of the values.") @OptionGroup var options: Math.Options mutating func run() { let result = options.values.reduce(0, +) print(format(result: result, usingHex: options.hexadecimalOutput)) } } } ``` -------------------------------- ### Dependency Finding Source: https://github.com/apple/swift-argument-parser/blob/main/CMakeLists.txt Finds necessary packages like dispatch, Foundation, and XCTest, conditionally based on the operating system and build settings. ```cmake if(NOT APPLE) find_package(dispatch CONFIG) find_package(Foundation CONFIG) if(BUILD_TESTING) find_package(XCTest CONFIG) endif() endif() ``` -------------------------------- ### OptionGroup Creation and Properties Source: https://github.com/apple/swift-argument-parser/blob/main/Sources/ArgumentParser/Documentation.docc/Extensions/OptionGroup.md APIs related to creating and accessing properties of an OptionGroup. ```APIDOC ## OptionGroup ### Description Provides functionality for creating and managing option groups within the Swift Argument Parser. ### Creating an Option Group #### Method `init(title:visibility:)` #### Description Initializes a new OptionGroup with a specified title and visibility. ### Option Group Properties - **title** (String) - The title of the option group. ### Infrequently Used APIs - ``init()``: Default initializer. - ``wrappedValue``: Accesses the wrapped value of the option group. - ``description``: Provides a description for the option group. ``` -------------------------------- ### Enumerating Possible Values for Arguments Source: https://github.com/apple/swift-argument-parser/blob/main/Sources/ArgumentParser/Documentation.docc/Articles/CustomizingHelp.md Implement `ExpressibleByArgument.allValueStrings` to list possible values for an argument or option. This improves usability by showing users the valid choices directly in the help screen. ```swift enum Fruit: String, ExpressibleByArgument { case apple case banana case coconut case dragonFruit = "dragon-fruit" static var allValueStrings: [String] { ["apple", "banana", "coconut", "dragon-fruit"] } } struct FruitStore: ParsableCommand { @Argument(help: "The fruit to purchase") var fruit: Fruit @Option(help: "The number of fruit to purchase") var quantity: Int = 1 } ``` -------------------------------- ### color Command Source: https://github.com/apple/swift-argument-parser/blob/main/Tests/ArgumentParserGenerateDoccReferenceTests/Snapshots/testColorMarkdownReference().md This section describes the 'color' command and its available options. ```APIDOC ## color ### Description This command allows users to specify their favorite colors. ### Method N/A (Command-line tool) ### Endpoint N/A (Command-line tool) ### Parameters #### Query Parameters - **--fav** (string) - Required - Your favorite color. - **--second** (string) - Optional - Your second favorite color. - **--help** (boolean) - Optional - Show help information. ### Request Example ``` color --fav=blue --second=green ``` ### Response #### Success Response (200) N/A (Command-line tool output is printed to the console) #### Response Example (Output depends on the arguments provided, typically shows help or processes input) ``` -------------------------------- ### Repeat Command Usage Source: https://github.com/apple/swift-argument-parser/blob/main/Tests/ArgumentParserGenerateDoccReferenceTests/Snapshots/testRepeatMarkdownReference().md This snippet shows the basic usage and available options for the 'repeat' command. ```APIDOC ## repeat ### Description Repeats a given phrase a specified number of times. ### Method N/A (Command-line tool) ### Endpoint N/A (Command-line tool) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Command Line Usage ``` repeat [--count=] [--include-counter] [--help] ``` ### Options - **--count=\** (String) - Required - The phrase to repeat. - **--help** (Flag) - Show help information. ### Request Example ```bash repeat --count=3 "Hello" --include-counter ``` ### Response #### Success Response (Output) - The repeated phrase, optionally prefixed with a counter. #### Response Example ``` 1: Hello 2: Hello 3: Hello ``` ``` -------------------------------- ### Calculate Quantiles with Math Utility Source: https://github.com/apple/swift-argument-parser/blob/main/Tests/ArgumentParserGenerateDoccReferenceTests/Snapshots/testMathDoccReference().md Prints the quantiles of floating-point values. Supports various custom arguments, file/directory inputs, shell options, and version/help flags. ```bash math stats quantiles [] [] [] [...] [--file=] [--directory=] [--shell=] [--custom=] [--custom-deprecated=] [--version] [--help] ``` -------------------------------- ### Color Command Source: https://github.com/apple/swift-argument-parser/blob/main/Tests/ArgumentParserGenerateDoccReferenceTests/Snapshots/testColorDoccReference().md This section describes the 'color' command, its arguments, and their purposes. ```APIDOC ## color ### Description This command allows users to specify their favorite colors. ### Method Not applicable (CLI command) ### Endpoint Not applicable (CLI command) ### Parameters #### Query Parameters - **--fav** (string) - Required - Your favorite color. - **--second** (string) - Optional - Your second favorite color. - **--help** (boolean) - Optional - Show help information. ### Request Example ``` color --fav=blue --second=green ``` ### Response #### Success Response (200) Not applicable (CLI command) #### Response Example Not applicable (CLI command) ``` -------------------------------- ### Configure Shell-Specific Completion Commands Source: https://github.com/apple/swift-argument-parser/blob/main/Sources/ArgumentParser/Documentation.docc/Articles/CustomizingCompletions.md Use .shellCommand with a function that returns shell-specific scripts based on CompletionShell.requesting. This is for generating completion scripts. ```swift struct Tool { @Option(completion: .shellCommand(generateCommandPerShell())) var x: String? @Option(completion: .custom(generateCompletionCandidatesPerShell)) var y: String? } /// Runs when a completion script is generated; results hardcoded into script. func generateCommandPerShell() -> String { switch CompletionShell.requesting { case CompletionShell.bash: return "bash-specific script" case CompletionShell.fish: return "fish-specific script" case CompletionShell.zsh: return "zsh-specific script" default: // return a universal no-op for unknown shells return ":" } } ``` -------------------------------- ### Customizing Option and Flag Names Source: https://github.com/apple/swift-argument-parser/blob/main/Sources/ArgumentParser/Documentation.docc/Articles/DeclaringArguments.md Define custom command-line names for options and flags using various `name` specifiers. ```swift struct Example: ParsableCommand { @Flag(name: .long) // Same as the default var stripWhitespace = false @Flag(name: .short) var verbose = false @Flag(name: "--jitter -j") var includeJitter = false @Option(name: .customLong("count")) var iterationCount: Int @Option(name: [.customShort("I"), .long]) var inputFile: String } ``` -------------------------------- ### Count Lines Help Subcommand Source: https://github.com/apple/swift-argument-parser/blob/main/Tests/ArgumentParserGenerateDoccReferenceTests/Snapshots/testCountLinesMarkdownReference().md Documentation for the 'help' subcommand of 'count-lines'. ```APIDOC ## count-lines help [...] ### Description Shows help information for the 'count-lines' command or its subcommands. ### Method N/A (Command-line tool) ### Endpoint N/A (Command-line tool) ### Parameters #### Path Parameters - **subcommands** (string) - Optional - The specific subcommands to show help for. ### Request Example ```bash count-lines help count-lines help count-lines ``` ### Response #### Success Response (0) * Displays help text for the specified command or subcommand. ``` -------------------------------- ### Math Statistics Command Source: https://github.com/apple/swift-argument-parser/blob/main/Tests/ArgumentParserGenerateDoccReferenceTests/Snapshots/testMathDoccReference().md The base command for calculating descriptive statistics. Use --version to show the version and --help for usage information. ```bash math stats [--version] [--help] ``` -------------------------------- ### math.add Source: https://github.com/apple/swift-argument-parser/blob/main/Tests/ArgumentParserGenerateDoccReferenceTests/Snapshots/testMathDoccReference().md Adds a list of values and prints the sum. Supports hexadecimal output. ```APIDOC ## math.add ### Description Print the sum of the values. ### Method N/A (CLI Tool) ### Endpoint N/A (CLI Tool) ### Parameters #### Query Parameters - **--hex-output** (flag) - Optional - Use hexadecimal notation for the result. - **--version** (flag) - Optional - Show the version. - **--help** (flag) - Optional - Show help information. #### Path Parameters - **values** (array of integers) - Required - A group of integers to operate on. ``` -------------------------------- ### Count Lines Help Command Usage Source: https://github.com/apple/swift-argument-parser/blob/main/Tests/ArgumentParserGenerateDoccReferenceTests/Snapshots/testCountLinesDoccReference().md This command displays help information for the count-lines command and its subcommands. It's useful for understanding available options and arguments. ```bash count-lines help [...] ``` -------------------------------- ### Calculate Quantiles with Various Options Source: https://github.com/apple/swift-argument-parser/blob/main/Tests/ArgumentParserGenerateDoccReferenceTests/Snapshots/testMathMarkdownReference().md Calculates quantiles for floating-point values. Supports various options including file, directory, shell, custom arguments, and deprecated arguments. ```bash math stats quantiles [] [] [] [...] [--file=] [--directory=] [--shell=] [--custom=] [--custom-deprecated=] [--version] [--help] ``` -------------------------------- ### Custom Enumerable Flags Source: https://github.com/apple/swift-argument-parser/blob/main/Sources/ArgumentParser/Documentation.docc/Extensions/Flag.md Initializers for creating custom enumerable flags. ```APIDOC ## Initializers for Custom Enumerable Flags ### Description Provides initializers for creating custom enumerable flags. ### Method `init(help:)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` ```APIDOC ## Initializers for Custom Enumerable Flags (with Exclusivity) ### Description Provides initializers for creating custom enumerable flags with exclusivity. ### Method `init(exclusivity:help:)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` ```APIDOC ## Initializers for Custom Enumerable Flags (with Wrapped Value and Exclusivity) ### Description Provides initializers for creating custom enumerable flags with a wrapped value and exclusivity. ### Method `init(wrappedValue:exclusivity:help:)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` ```APIDOC ## Initializers for Custom Enumerable Flags (with Wrapped Value) ### Description Provides initializers for creating custom enumerable flags with a wrapped value. ### Method `init(wrappedValue:help:)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Boolean Flags with Inversions Source: https://github.com/apple/swift-argument-parser/blob/main/Sources/ArgumentParser/Documentation.docc/Extensions/Flag.md Initializers for boolean flags that support inversions and exclusivity. ```APIDOC ## Initializers for Boolean Flags with Inversions ### Description Provides initializers for creating boolean flags that can have inversions and exclusivity. ### Method `init(wrappedValue:name:inversion:exclusivity:help:)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` ```APIDOC ## Initializers for Boolean Flags with Inversions (Overloads) ### Description Provides overloads for creating boolean flags with inversions and exclusivity. ### Method `init(name:inversion:exclusivity:help:)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Define Custom Completions for Options Source: https://github.com/apple/swift-argument-parser/blob/main/Sources/ArgumentParser/Documentation.docc/Articles/CustomizingCompletions.md Use CompletionKind to specify file, directory, or a list of strings for option completions. Default completions are used for CaseIterable types. ```swift 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 } ``` -------------------------------- ### Implement Custom Completion Function Source: https://github.com/apple/swift-argument-parser/blob/main/Sources/ArgumentParser/Documentation.docc/Articles/CustomizingCompletions.md Use .custom completion kind with a function to dynamically generate completion candidates. This function receives arguments provided so far. ```swift 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? } ``` -------------------------------- ### Async Command with File Reading Source: https://github.com/apple/swift-argument-parser/blob/main/Sources/ArgumentParser/Documentation.docc/Extensions/AsyncParsableCommand.md Use this snippet for commands that perform asynchronous operations like reading files. Ensure your command conforms to AsyncParsableCommand and mark the run() method with 'async'. ```swift import Foundation @main struct CountLines: AsyncParsableCommand { @Argument(transform: URL.init(fileURLWithPath:)) var inputFile: URL mutating func run() async throws { let fileHandle = try FileHandle(forReadingFrom: inputFile) let lineCount = try await fileHandle.bytes.lines.reduce(into: 0) { count, _ in count += 1 } print(lineCount) } } ``` -------------------------------- ### Implement Multiply Subcommand with Aliases Source: https://github.com/apple/swift-argument-parser/blob/main/Sources/ArgumentParser/Documentation.docc/Articles/CommandsAndSubcommands.md Implement the 'Multiply' subcommand, which calculates the product of values. It demonstrates using `aliases` in `CommandConfiguration` for alternative invocation names. ```swift extension Math { struct Multiply: ParsableCommand { static let configuration = CommandConfiguration( abstract: "Print the product of the values.", aliases: ["mul"]) @OptionGroup var options: Math.Options mutating func run() { let result = options.values.reduce(1, *) print(format(result: result, usingHex: options.hexadecimalOutput)) } } } ``` -------------------------------- ### Supporting Types Source: https://github.com/apple/swift-argument-parser/blob/main/Sources/ArgumentParser/Documentation.docc/Extensions/Flag.md Documentation for supporting types used with flags. ```APIDOC ## Flag Exclusivity ### Description Defines the exclusivity behavior for flags. ### Method `FlagExclusivity` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` ```APIDOC ## Flag Inversion ### Description Defines the inversion behavior for boolean flags. ### Method `FlagInversion` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Defining Command Properties Source: https://github.com/apple/swift-argument-parser/blob/main/Sources/ArgumentParser/Documentation.docc/Extensions/CommandConfiguration.md Properties for defining core command attributes. ```APIDOC ## Defining Command Properties ### Description Set fundamental properties of the command. ### Properties - **commandName** (String) - The name used to invoke this command. - **version** (String) - The version string for this command. - **shouldDisplay** (Bool) - Controls whether this command is shown in the help output. - **aliases** ([String]) - Alternative names that can be used to invoke this command. ```