37 Commits
Author SHA1 Message Date
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 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
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
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
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
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
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
Gwynne Raskind ecac862002 [Bash completion]: Respects .file() extensions, uses _filedir (#590)
Bash completion scripts: Respects the `extensions` array for `CompletionKind.file()`
and uses `_filedir` when available for `.file` and `.directory`.
2023-11-14 10:51:03 -06:00
matsuji 99e2e97fd9 Improve fish completion (#376, #534) (#535)
A generated fish script didn't complete an option after an argument.

The cause is the generated fish script doesn't accept an input text which already has arguments.
For example, when the input is `repeat -`, the script can complete `--count`, but when the text is `repeat foo -`, the script cannot complete `repeat foo --count`, because the input text already has the argument "foo".

To fix the issue, `FishCompletionsGenerator` got a capability that can accept a text which has arguments.
2023-01-09 10:55:41 -06:00
Nate Cook 5535a95838 Fix some Swift 5.6 compatibility issues (#516)
* Use existential CodingKey parameters consistently

Swift 5.7 supports implicit opening for existentials, so these
conversions from `CodingKey` parameters to pass to methods that
are generic over `CodingKey` work fine. Prior to Swift 5.7, however,
these don't compile, with the message that `CodingKey` doesn't conform
to itself.

* Bump the required Swift version for the count-lines test

The overload resolution for the `static func main()` in an `@main`
type still had issues in Swift 5.6, such that a package with a min.
platform below that which works for concurrency backdeployment doesn't
properly resolve the AsyncParsableCommand `main()` function. In
Swift 5.7, this is properly resolved, so just the availability on
the main type is sufficient.

This change just skips the test of `count-lines` prior to Swift 5.7,
so that we can maintain the open platform minimum for the package
as a whole.
2022-11-04 16:18:24 -05:00
Rauhul Varma 607021b737 Unify @Argument and @Option initialization paths (#477)
- Fixes #466.
- Adds initializers to ArgumentDefinition generic over a Container type.
  The Container type must conform to a new internal protocol
  ArgumentDefinitionContainer which describes functionality like default
  set of help options for the argument defined by the property wrapper,
  etc.
- Adds overloads for Optional @Arguments and @Options with default
  values which emit deprecation warning to guide users towards using the
  non-Optional versions.
2022-09-10 18:40:31 -05:00
KthandNate Cook 18b0039973 Fix Repeat's endless printing (#437)
Co-authored-by: Nate Cook <natecook@apple.com>
2022-04-02 15:13:09 -05:00
Nate Cook 1141ed1e1b Support an async entry point for commands (#404)
Adds a new `AsyncParsableCommand` protocol, which provides a
`static func main() async` entry point and can call through to the root
command's or a subcommand's asynchronous `run()` method. For this
asynchronous execution, the root command must conform to `AsyncParsableCommand`,
but its subcommands can be a mix of asynchronous and synchronous commands.

Due to an issue in Swift 5.5, you can only use `@main` on an
`AsyncParsableCommand` root command starting in Swift 5.6.
This change also includes a workaround for clients that are using Swift 5.5.
Declare a separate type that conforms to `AsyncMainProtocol` and add the `@main`
attribute to that type.

```
@main enum Main: AsyncMain {
    typealias Command = <#command#>
}
```
2022-03-14 18:14:09 -05:00
Aaron Gyes 7e04f56c1d Rename ...using_command fish function, set $cmd in local scope (#377)
__fish_* should not be used by external projects.
set -l cmd in case user has a global or universal `cmd` defined.
2021-12-10 13:31:20 -06:00
Jake Petroules b2e411887e Fix compile failure on iOS for Mac Catalyst support (#372) 2021-11-08 19:50:43 -06:00
Nate Cook 685341f629 Use standard path for --dump-help help/completions, remove completions (#339) 2021-07-20 12:59:36 -05:00
Kotaro Suto cfcb9cb0cd Add new built-in flag --dump-help (#310)
This commit will add a new builtin option named `--dump-help-info` which
outputs help information in JSON.
2021-07-07 13:09:21 -05:00
François Lamboley 37610bc875 Fix executable path when calling custom completion in bash (#323) 2021-06-10 11:07:02 -05:00
Gonzalo RH 530a754555 Included help message when a required value is missing. (#324) 2021-06-09 11:28:00 -05:00
François Lamboley e566395765 Fix custom completion args for bash (#320) 2021-06-04 09:53:48 -05:00
Nate Cook 167704f261 Ignore extra help flags when given with the 'help' subcommand (#309) 2021-05-14 17:28:32 -05:00
Nate Cook 267f707294 Use custom help flags in completion scripts (#308)
* Standardize the help and version flag generation
* Simplify some help generation code
* Support custom help flags in completion scripts
2021-05-14 10:27:05 -05:00
Alfredo Delli Bovi 4793b0f4b9 Include help text in error message when validation fails (#283) 2021-03-06 13:11:58 -06:00
Nate Cook 605a2330c5 Suppress hidden arguments from completion scripts (#271) 2021-02-11 10:41:46 -06:00
Daniel Duan 2104b1a314 Add Fish completion generator (#226) 2020-08-13 12:11:08 -05:00
Nate Cook b905f5c777 Improve the completion tests a bit (#228) 2020-08-12 14:17:58 -05:00
Brandon Evans 115cacd4a1 Improve support for multi-word completion strings in ZSH (#216)
* Improve support for multi-word completions in Z shell

I will not pretend to fully understand why this new "expand string into array" expression works when the other didn't, but it does. The new expression is based on this SO answer: https://unix.stackexchange.com/a/29748.

The motivation for this change was for the install command of xcodes (https://github.com/RobotsAndPencils/xcodes) to support Xcode version completion strings with multiple words, like "11.6 Beta". The previous version of this expression would split this string into two, so that "11.6" and "Beta" were independent options in the ZSH completion UI, which didn't make sense for this use case.
2020-08-05 11:49:05 -05:00
Stuart Carnie 163211e2e4 fix: Improve zsh completion script generator (#219)
* `shellCommand` stores output in a local array that is passed
  to `_describe` to handle spaces and other punctuation in
  the shell command output

* elide the help abstract if it is empty, as it confuses
  the zsh completion system

* set the `_<commandName>_commandname` to `$words[1]`, which
  is the full name of the command used to invoke the completion.
  This ensures invocations like `./build/debug/math` ...
  as passed on to the `_custom_completion` command.
2020-08-03 14:26:25 -05:00
Nate Cook 280700d361 Add completion script generation (#123)
Support for generating shell completion scripts for `ParsableCommand`
types, with customization points for `ExpressibleByArgument` types and
individual arguments and options. Zsh and Bash are supported in this
initial release.
2020-07-29 17:58:44 -05:00
Artem Novichkov 02a95bdaea Help message for default subcommands (#183)
* Update label for default subcommand

* Add test for default subcommand

* Fix test fixtures with default subcommand help message
2020-06-11 11:09:26 -05:00
Nate Cook 85196ee1d8 Additional help messages (#165)
* Add 'see help' messages to usage messages and the help screen

* Update tests for new help messages.

* Update guide examples with additional help messages
2020-05-22 17:04:14 -05:00
John Mueller 501bf60536 Display help when no arguments results in error (#140)
If a command cannot successfully run with zero arguments, print the error and the full help message instead of the short usage message.

This closes #134.
2020-05-14 09:08:19 -05:00
Nate Cook 31799bc1b4 Add built-in support for --version flag (#102)
* Add built-in support for --version flag

* Test that command-defined --version overrides the built-in.

* Document the `version:` parameter in CommandConfiguration

* Include --version in the generated help.
2020-03-30 12:36:21 -05:00
Nate Cook ddc828f8cb Add an API for converting an error to an exit code (#79)
* Add an API for converting an error to an exit code

* Make ExitCode more useful as a value type

* Update tests to use ExitCode values

* Typo fix

* Add a test for ExitCode.isSuccess

* Switch to just using ExitCode for tests
2020-03-21 12:44:32 -05:00
Elliott Williams 34300696f5 Prefix test target names with "ArgumentParser" (#74)
* Prefix testing and test helper targets with ArgumentParser

* Replace SAP with ArgumentParser in imports and CMakeLists
2020-03-10 12:44:07 -05:00