285 Commits
Author SHA1 Message Date
Nate Cook 10b123ce4a Beginning support for sets of flags
This is based on SetAlgebra conformance, so both sets of enums and
option sets can be used as the type of an `@Flag` property.
2025-02-13 09:37:19 -06:00
Ross Goldberg 5b1320e9d6 Make CommandParser.swift import Swift version consistent with other files. (#724) 2025-02-12 19:19:40 -08:00
Rauhul Varma fd8ea096da Remove @_implementationOnly imports (#666)
The `@_implementationOnly` attribute does not work correctly without
library evolution enabled. The only possible client with this enabled is
Apple, however they have updated to the Swift 6 compiler and can use
`internal import` instead of this attribute. Therefore there is no need
for this package to use the attribute anymore.
2025-02-12 13:01:44 -08:00
Ross Goldberg 23d8d3a522 Prevent implementation-only import build warnings on older Swift. (#720)
Resolve #719

Signed-off-by: Ross Goldberg <484615+rgoldberg@users.noreply.github.com>
2025-02-12 11:00:23 -06:00
Rauhul Varma 47fe00c4fe Enable more ci (#712)
Enables and fixes issues with additional platform tests 
and the formatter with these additional rules:

- UseLetInEveryBoundCaseVariable
- NeverForceUnwrap
- BeginDocumentationCommentWithOneLineSummary
- ValidateDocumentationComments
- AlwaysUseCamelCase
2025-02-12 08:52:17 -06:00
Ross Goldberg 462737a8f1 Fix swift-format violations. (#714)
Resolve #713

Signed-off-by: Ross Goldberg <484615+rgoldberg@users.noreply.github.com>
2025-02-11 16:44:28 -08:00
Rauhul Varma 10d80282e5 Enable swift-format checking (#711)
Adopts the common swift-mmio and swift-argument-parser format and enables CI checking.

Fixes: #702
2025-02-10 14:58:19 -08:00
Rauhul Varma a01856b49f Enable Documentation check (#708)
Enables the documentation check from the swiftlang soundness workflow
and resolves errors/notes emitted by the check.

Fixes: #704
2025-02-07 22:02:25 -06:00
Ross Goldberg aefbb6e28d Fix Swift 5.7 build errors. (#707) 2025-02-06 20:28:38 -08:00
Rauhul Varma 1248cc4bda Fix concurrency warnings (#705)
Moves static read-only vars behind a mutex so they are currency safe.
Users of the api don't need to worry about this because the mutex is
hidden behind an accessor.
2025-02-06 15:02:53 -08:00
Rauhul Varma d3630e3190 Move additional tests to snapshots (#700)
Moves some examples test to use snapshot files instead of inline
multiline strings.
2025-02-06 10:28:22 -08:00
Rauhul Varma cea1a0837e Extend snapshot testing to completion scripts (#698)
As the title suggests this commit moves the completion script tests to
use the snapshot testing recently introduced.
2025-02-06 09:40:18 -08:00
Rauhul Varma b551ec8c04 Add completion kind and help command to ToolInfo (#697)
Updates ToolInfo to include the built-in `help` subcommand and also
include details on each argument's completion method if any.
2025-02-06 08:55:56 -08:00
Rauhul Varma c2d8414653 Refactor dump help tests (#696)
The dump help tests previously included the json text in the Swift
source files as multiline strings. This made updating them very tedious
and made diffs hard to follow. This commit moves each of the json dumps
into their own files and adds an easy way of recording new ones as
needed.
2025-02-05 20:25:05 -08:00
Rauhul Varma 9289e315f8 Add generate-docc-reference plugin (#694)
Upstreams swiftly's generate-docs-plugin with minimal changes. Adds
tests against argument-parser's built in example tools.

The initial version of this tool is extremely minimal and should be
extended to output much more information contained in tool info, like
generate-manual does.
2025-02-05 10:05:45 -08:00
Rauhul Varma 25db036b71 Refactor serialization of dump help descriptions (#693)
Cleans up some lingering odds and ends from #647. Specifically switches
CommandInfoV0 to use the old style description and updates
ArgumentInfoV0 to emit value descriptions as a separate dictionary.
2025-02-04 17:04:42 -08:00
Rauhul Varma 1fdca83051 Add tests parsing dump help output (#692)
Adds a new test target called ArgumentParserToolInfoTests which contains
example json output from dump-help. The test code attempts to parse all
json files in the 'Examples' subdirectory. This will help us catch cases
where ArgumentParser is unable to parse json generated by older versions.

We still need to add a test that asserts old ArgumentParser versions can
parse the output of new versions.
2025-02-04 14:53:18 -08:00
Ross Goldberg 5f48a1614f Add singleton to indicate which shell version is requesting completion candidates (#690)
Create a `String?` singleton named `CompletionShell.requestingVersion` that
indicates which shell version is requesting completion candidates.

It will be set to the correct value while a Swift custom completion function is
executing to offer completions for a word from a command line (e.g., while
`customCompletion` from `@Option(completion: .custom(customCompletion))`
executes). Otherwise, it will be set to `nil`.

The requesting shell version is communicated to the Swift app via an environment
variable named `SAP_SHELL_VERSION`, which is exported by each of the generated
completion scripts.

Improve some nearby DocC.

Resolve #689

Signed-off-by: Ross Goldberg <484615+rgoldberg@users.noreply.github.com>
2025-01-22 09:22:35 -06:00
Ross Goldberg 2edadce25d Add singleton to indicate which shell is requesting completion candidates (#680)
A CompletionShell singleton named CompletionShell.requesting has been created
that indicates which shell is requesting completion candidates.

The singleton is populated when a completion script is generated, so functions
used to generate arguments for CompletionKind creation functions can return
completion candidate syntax / shell commands tailored for that shell.

For the custom(:) CompletionKind creation function, the singleton is populated
at runtime (when a completion script requests completions from the Swift app
after a user types tab while composing a command line to call the app).

The requesting shell is communicated to the Swift app via an environment variable
named SAP_SHELL, which is exported by each of the generated completion scripts.

Resolve #672

Signed-off-by: Ross Goldberg <484615+rgoldberg@users.noreply.github.com>
2025-01-21 23:57:36 -06:00
Ross Goldberg 41d58ffe70 Fix incorrect or confusing documentation about Swift versions (#678)
Rewrote Markdown to properly specify Swift 5.7 instead of 5.5,
and to clarify other information related to Swift versions.

Resolve #677

Signed-off-by: Ross Goldberg <484615+rgoldberg@users.noreply.github.com>
2024-12-04 17:44:38 -08:00
Saleem Abdulrasool d6836f4508 build: repair the CMake based build (#684)
Add the missing source file to the package to allow building with CMake
again.
2024-11-19 16:19:04 -08:00
Ross Goldberg e4009c1616 Fix Swift 5.7 build errors (#676)
Insert missing comma in targets array in Package.swift to fix Swift 5.7 build
break from commit 83c5134a24.

Replace 2 if expressions (which are not supported by Swift 5.7) that were added
to ToolInfo.swift by commit 83c5134a24.

Replace switch expression (which is not supported by Swift 5.7) that was added
to GenerateManual.swift by commit 44dd206a85.

Replace switch expression (which is not supported by Swift 5.7) that was added
to DumpHelpGenerationTests.swift by commit 83c5134a24.

Fixes #675

Signed-off-by: Ross Goldberg <484615+rgoldberg@users.noreply.github.com>
2024-11-06 08:57:16 -08:00
Joseph Heck 72bf21248f extend ToolInfoV0 with command visibility (#669)
- resolves https://github.com/apple/swift-argument-parser/issues/668
  by extending the ToolInfoV0 (help dump) struct to include visibility
  information for commands (already exists for arguments).
- updates test output to verify existing examples extend with the
  additional key.
2024-10-07 13:03:07 -05:00
Bri Peticca 83c5134a24 Add ability to provide descriptions for CaseEnumerable @Option values (#647)
Since `ExpressibleByArgument` already maintains a list of
enumerable values for an argument, we can extend this to serve
as an ordered list for a new dictionary property that maps the
value name to its description, if applicable. The new property
is a static variable on `ExpressibleByArgument` labelled
`allValueDescriptions`.

If the description string for a value is the same as the value
string, it's assumed that the description is not implemented.

The new value strings are used in the help screen, in the 
dump-help JSON output, and in the generated manual.
2024-09-30 14:17:48 -05:00
Christian GoetzeandChristian Goetze e3d8a3dd42 Add missing @Flag initializer in example (#657)
The documentation as presented doesn't compile. An initializer is
required for a boolean flag.

rdar://132579907

Co-authored-by: Christian Goetze <cgoetze@apple.com>
2024-07-29 13:55:30 -07:00
finagolfin 4a2e245ad5 Import new Android overlay (#651) 2024-07-16 16:38:41 -05:00
Nate Cook bb10ca8b70 Updates to support Swift 6 language version (#650)
Some minor NFC changes to resolve strict concurrency checking
warnings/errors and the warning about the change in meaning for
`#file`.
2024-07-15 15:37:38 -07:00
Craig Siemens d66d015418 Fix zsh/bash completions for arguments in option groups with a custom completion (#648)
* Added conversion for InputKey to/from fullPathString.

* Updated custom completions to use the IndexKey.fullPathString.

This resolves an issue where custom completion for arguments in an OptionGroup would fail to match the argument. It was caused by:
- the completion script only using the name of the argument (instead of the full path)
- the CommandParser looking for the matching argument by comparing a name only IndexKey with the “full” IndexKeys

* Updated BashCompletionsGenerator to use customCompletionCall.

The zsh completions already uses this function. The function’s implementation is the same as what the BashCompletionsGenerator is doing. This removes the duplicated logic.

* Updated completion tests to include nested arguments with custom completions.

* Switched to using the split method from the stdlib.

Prevously was using .components(seperatedBy:) from Foundation.

* Updated the fish completions to include arguments
2024-07-04 00:52:58 -05:00
Doug Gregor 81ac872186 Update CMake for new file CommandGroup.swift (#645) 2024-06-04 18:43:25 -07:00
Doug Gregor 516c2f80f7 Introduce subcommand grouping into the command configuration to improve help (#644)
* Introduce subcommand grouping into the command configuration to improve help

Add optional support for grouping subcommands into named groups, to
help bring order to commands with many subcommands without requiring
additional structure. For example, here's the help for a
"subgroupings" command that has an ungrouped subcommand (m), and two
groups of subcommands ("broken" and "complicated").

    USAGE: subgroupings <subcommand>

    OPTIONS:
      -h, --help              Show help information.

    SUBCOMMANDS:
      m

    BROKEN SUBCOMMANDS:
      foo                     Perform some foo
      bar                     Perform bar operations

    COMPLICATED SUBCOMMANDS:
      n

      See 'subgroupings help <subcommand>' for detailed help.

To be able freely mix subcommands and subcommand groups, CommandConfiguration
has a new initializer that takes a result builder. The help output
above is created like this:

    struct WithSubgroups: ParsableCommand {
      static let configuration = CommandConfiguration(
        commandName: "subgroupings"
      ) {
        CommandGroup(name: "Broken") {
          Foo.self
          Bar.self
        }

        M.self

        CommandGroup(name: "Complicated") {
          N.self
        }
      }
    }

Each `CommandGroup` names a new group and is given commands (there are
no groups within groups). The other entries are arbitrary
ParsableCommands.

This structure is only cosmetic, and only affects help generation by
providing more structure for the reader. It doesn't impact existing
clients, who can still reason about the flattened list of subcommands
if they prefer.

* Add an optional abstract to command groups

* Expand subcommand group result builders to handle all result-builder syntax

Adds support for if, if-else, if #available, and for..in loops.

* Revert "Add an optional abstract to command groups"

This reverts commit ab563a22c0.

* Eliminate result builders in favor of a second "groupedSubcommands" array

Introduce subcommand groups with a more modest extension to the API that
adds another array of subcommand groups alongside the (ungrouped)
subcommands array. We can consider introducing result builders as a
separate step later, if there's more to be gained from it.

* Drop the (ungrouped) "subcommands" heading when there are none.
2024-06-04 14:33:42 -07:00
Austin 29b3d39e16 Support passing arguments to async main (#568)
* Support passing arguments to async main

* Add test for AsyncParsableCommand.main()
2024-05-17 13:47:01 -05:00
Nate Cook 7f4ce2deef Eliminate warnings re: CommandConfiguration init (#636)
When the old (pre-aliases) initializer has all its default parameter
values, it is selected as the overload because it has fewer parameters
overall. Removing the default parameters allows it to still satisfy
(very niche) source compat requirements without actually being
available as an overload.

(Also resolves an extra warning in the tests)
2024-05-01 11:23:18 -05:00
Rauhul Varma cfac15f2cd Add ParsableArguments/Command.usageString (#634)
Adds a new API to ParsableArguments and ParsableCommand for getting the
usage string. This allows clients to use argument-parser in a more
piecemeal way to construct their own error screens.
2024-04-30 17:12:01 -07:00
Danny Canter 2b962934d1 Add aliases support for sub commands (#627)
This adds support for aliases for subcommands via a new parameter to
CommandConfigurations constructors. The aliases are passed as an array
of strings, where the default is just an empty array that signifies there
are no aliases. The aliases are supported regardless of if a different
commandName is chosen or not. This also updates how subcommands show up
in the help text. Any aliases are now displayed to the right of the original
command.

In addition to the functionality itself, this change:

1. Updates some of the EndToEnd parsing tests to make sure they function
while using aliases.
2. Sprinkles mentions where I saw fit in the documentation.
3. Updates the Math example to have aliases for `math stats average`
(`math stats avg`), and `math multiply` (`math mul`).

`math`'s help text now looks like the below:

```
~ math --help
OVERVIEW: A utility for performing maths.

USAGE: math <subcommand>

OPTIONS:
  --version               Show the version.
  -h, --help              Show help information.

SUBCOMMANDS:
  add (default)           Print the sum of the values.
  multiply, mul           Print the product of the values.
  stats                   Calculate descriptive statistics.

  See 'math help <subcommand>' for detailed help.

~ math stats --help
OVERVIEW: Calculate descriptive statistics.

USAGE: math stats <subcommand>

OPTIONS:
  --version               Show the version.
  -h, --help              Show help information.

SUBCOMMANDS:
  average, avg            Print the average of the values.
  stdev                   Print the standard deviation of the values.
  quantiles               Print the quantiles of the values (TBD).

  See 'math help stats <subcommand>' for detailed help.
```

and use of the aliases:

```
~ math mul 10 10
100

~ math stats avg 10 20
15.0
```

This change does NOT add any updates to the shell completion logic for
this feature.

Fixes #248
2024-04-30 18:20:03 -05:00
Nate Cook 3dcbdb06ff Clarify postTerminator parsing strategy behavior (#621)
Fixes #597.
2024-03-05 11:53:49 -08:00
Nate Cook 7191549c88 Fix for @Option(transform:) with optional type (#619)
Due to the restructuring in #477, there was ambiguity between the
unconstrained `@Option` initializer that uses a transform (but no
initial value) and the one that is constrained to the property being
optional. This marks the unconstrained version as disfavored, which
allows overload resolution to select the optional version when
appropriate.

Also fixes this for `@Argument` and improves documentation
consistency for `@Option`.

Fixes #618.
2024-03-05 11:20:13 -08:00
Cœur 1c8215f18a Prefer let for private configurations (#617) 2024-02-28 11:29:01 -06:00
Rob Mayoff 76466cc870 Improve zsh completion for repeatable options (#614)
Some commands allow an option to be repeated to provide multiple values.
For example, ssh allows the -L flag to be repeated to establish multiple
port forwardings.

ArgumentParser supports this style when the Option value is an Array
and the parsingStrategy is ArrayParsingStrategy.singleValue or
.unconditionalSingleValue.

Without this patch, ArgumentParser generates a zsh completion script
that does not handle repeatable options correctly. The generated script
suppresses completion of any option after that option's first use, even
if the option is repeatable.

With this patch, ArgumentParser generates a zsh completion script that
allows a repeatable option to be completed each time it is used.

The relevant zsh _arguments syntax is documented here:
https://zsh.sourceforge.io/Doc/Release/Completion-System.html#Completion-Functions

Specifically, a repeatable option's optspec needs to start with '*'.
Furthermore, a repeatable argument must not list itself or its synonyms
in its own parenthesized suppression list. (This is not clearly
documented.)

fixes #564

* Add test for repeated flag completions
2024-02-24 11:36:22 -08:00
Keith Smiley c4138099b4 Remove @_implementationOnly annotations (#616)
These annotations produce warnings when compiling swift-syntax without library evolution using Swift ≥5.10.

Replace them by `private import` when compiling using Swift ≥5.11.

Mirrors https://github.com/apple/swift-syntax/pull/2429
2024-02-24 13:12:52 -06:00
Max Desiatov a0f43bb719 Mark CommandConfiguration as Sendable (#615)
Lack of this marker protocol conformance causes warnings with strict concurrency checks, such as `Static property 'configuration' is not concurrency-safe because it is not either conforming to 'Sendable' or isolated to a global actor; this is an error in Swift 6`
2024-02-06 23:17:14 -06:00
Nate Cook 6c7ec363da Fix unrecognized -help flag with default command (#612)
When there's a default subcommand that captures pass-through args,
only a standalone help flag should trigger help (since the flag should
otherwise go to the subcommand). This fix makes that true for single-
dash help flag names, which were previously being skipped, due to
single-dash flags being lexed as both one whole flag and as a group of
individual short flags.

Re: https://github.com/apple/swift-package-manager/issues/7218
Re: rdar://120422808
2024-01-04 14:49:48 -06:00
Nate Cook a3d53a7597 Allow single, attached value with .upToNextOption (#610)
Fixes an issue where a single attached value triggered an error on
`.upToNextOption` options.

Fixes #609.
2023-12-12 17:30:14 -08:00
Nate Cook c8ed701b51 Update changelog with latest changes (#600) 2023-12-06 09:30:44 -08:00
Nate Cook c769981ed8 Update documentation (#602)
Update some documentation, mark some code samples as being
Swift so that syntax highlighting works properly, and hide some
other infrequently-used symbols by adding internal parameter
name underscores.
2023-11-20 13:30:19 -06:00
Kenny YorkandKenny York 9eded54997 Bash does not like '-' in function names (#573)
Co-authored-by: Kenny York <kenny_york@apple.com>
2023-11-20 08:41:23 -06:00
Nate Cook ac615d40c2 Workarounds for remaining concurrency warnings (#601) 2023-11-18 22:05:20 -06:00
Lev Walkin 511a72aea8 Add Sendable conformance (#582)
This change adds conditional `Sendable` conformance to all
property wrapper types when their `Value` is `Sendable`, enabling
commands to be used in concurrent contexts. Some notes on
the implementation:

* Fix flag exclusivity issues

This derives the `hasUpdated` check from the parsed values data type,
rather than storing it in the closure (which breaks sendability) or
passing it through the closure invocation (which wasn't finished
enough to actually work).

* Mark all `transform` methods as `@Sendable`

This allows for a stronger, compiler-supported guarantee of
sendability when a compound `ParsableArguments` or `ParsableCommand`
type is marked `Sendable`. Most transformations shouldn't be a
problem, since the general case is that these are pure string ->
value transformations.

In cases where making such a transformation sendable is impossible,
an author can always change the property to be just a string and
perform the transformation within the context of the command's
execution, in either the `run()` or `validate()` methods.

* Add `@preconcurrency` to Sendable closure APIs

This adds the `@preconcurrency` attribute to all public APIs that
have changed to take a `@Sendable` closure. This will ease the
migration path for sendable adoption for ArgumentParser users, since
a warning will only appear for using these APIs (like the `transform`
parameter in an @Option or @Argument) once they've turned on strict
concurrency checking.

I'm also backing out changes that avoided those warnings in the tests
and examples, since in most cases those warnings are spurious;
unapplied functions don't capture state. See
https://forums.swift.org/t/pitch-inferring-sendable-for-methods-and-key-path-literals/68011
for more on this and hopefully an upcoming fix for these issues.

* Raise minimum Swift version to 5.7

In order to provide `@preconcurrency` support, the package needs to
have a minimum Swift requirement of 5.7. This makes that change and
updates the README to indicate this for the next version.
2023-11-17 10:06:47 -06:00
Rob Ryan 51ec3ed103 Add AsyncParsableCommand to README (#565)
* See issue https://github.com/apple/swift-argument-parser/issues/561
2023-11-16 11:47:16 -08:00
Gwynne Raskind c10af98655 Respect the COLUMNS and LINES environment variables when present (#596)
* Respect the `COLUMNS` and `LINES` environment variables, if set, when determining screen size.
* Add test for COLUMNS environment override
* Make columns test idempotent against there being a COLUMNS value already set in the environment
* Make help tests be more explicit about screen widths.
2023-11-14 21:17:06 -08:00
Rauhul Varma 75dae3dfd0 Display possible option values in help (#594)
Updates HelpGenerator to print possible value options as a suffix to the
user defined help string. In practice this looks like:

> Set diagnostic level to report public declarations without an
> availability attribute. (values: error, warn, ignore; default: warn)
2023-11-14 09:30:31 -08:00