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.
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.
- 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.
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.
* 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.
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
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
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.
* 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.
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)
When a property wrapper is applied to a property, the property's
storage is given a name with a prefixed underscore. That is,
for a property named `x`, the actual storage is named `_x`.
That prefixed storage is what is visible through reflection, so
when building an ArgumentSet from a command type's Mirror, we
need to remove the leading underscore. This is done when creating
an InputKey for each property.
However, InputKeys are also created from CodingKeys during
decoding of a ParsableCommand. These CodingKeys _do not_ have
the leading underscore that is visible, so any underscores
that appear are actually from the declaration of the property
with an underscored name. Removing leading underscores from
CodingKey names results in a mismatch when trying to find
the decoded value.
This change simplifies the InputKey type to use an array
path instead of an indirect enum and removes the leading
underscore dropping when creating an InputKey from a CodingKey.
rdar://104928743
- Changes uses of import Foundation in ArgumentParser to only expose the
symbols needed to avoid growing unintentional dependencies.
- Replaces direct usage of EXIT_FAILURE in MessageInfo with ExitCode,
exposed as a result of the above change.
This change lets you provide a title for option groups, which is used
when generating the help screen. Titled option groups, when they exist,
are placed between the ARGUMENTS and OPTIONS section of the help.
Multiple option groups with the same title are coalesced into a single
group.
For example, this command declaration:
struct Extras: ParsableArguments {
@Flag(help: "Print extra output while processing.")
var verbose: Bool = false
@Flag(help: "Include details no one asked for.")
var oversharing: Bool = false
}
@main
struct Example: ParsableCommand {
@OptionGroup(title: "Extras")
var extras: Extras
@Argument var name: String?
@Option var title: String?
}
yields this help screen:
USAGE: example [--verbose] [--oversharing] [<name>] [--title <title>]
ARGUMENTS:
<name>
EXTRAS:
--verbose Print extra output while processing.
--oversharing Include details no one asked for.
OPTIONS:
--title <title>
-h, --help Show help information.
- 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.
- Fixes a bug where built-in flags such as --help and --version were not
properly marked with isOptional which resulted in them appearing in
generated content (such as completion scripts and manuals) as required
arguments.
- Make ArgumentSet(_:visibility:) filter correctly
The ArgumentSet initializer was previously only filtering out option
groups with visibility lower than requested. With this change, the
resulting ArgumentSet only includes values that are valid for display.
In addition, this moves the visibility parameter out of
UsageGenerator.synopsis(); that type needs to have the correct
visibility level at initialization.
- Mark non-parsed properties as private
This applies to properties that are defined without a property
wrapper. This kind of property should never be included in the help,
since they aren't included in the command-line tool's UI.
- Changes ArgumentVisibility from an enum to a struct. This will allow
ArgumentParser to add cases in the future without breaking clients
that could have been exhaustively switching across all cases. It also
allows us to implement protocol conformances on the internal type and
avoid exposing them on the public type.
- Replaces `ArgumentSet.init(_:creatingHelp:includeHidden:)` with
`ArgumentSet.init(_:visibility:)`. `visibility` intentionally does not
have a default value to ensure that callers only have the correct
arguments. As part of this change `includeHidden` has been replaced
throughout the codebase with `visibility`. This change also fixes a
bug where arguments with hidden `visibility` were being displayed in the
generated command usage string.
- Updates helpMessage(columns:) and helpMessage(for:columns:) with an
includeHidden argument defaulted to false to allow for clients to
programmatically generate hidden help.
- Renames ArgumentHelp.Visibility to ArgumentVisibility.
- Replaces ArgumentDefinition.shouldDisplay with a visibility property
whose value is derived from ArgumentHelp.visibility.
Swift Package Manager adopted _hiddenFromHelp, the resulting help is
much more approachable for basic usage, but leaves no way to view
all the advanced options it accepts. This takes from swiftc's + clang's
playbook and adds a hidden `--help-hidden` flag that prints all help,
including those using `_hiddenFromHelp`
- Adds check to ensure that `wrapped(to:wrappingIndent:)` doesn't
attempt to retrieve a negative prefix.
- The Usage struct was composed of an array of strings which always
contained exact one string at runtime. This struct has been removed
and replaced with a single usage string.
- Removes HelpGenerator._screenWidthOverride in favor of explicitly
setting the screen width in generateHelp calls.
- Fixes#369
- Adds an error check for the return value of GetConsoleScreenBufferInfo
Windows. If GetConsoleScreenBufferInfo a default size of 80 by 25 is
used.
When an option value fails to parse, no custom error message is
provided, and a list of valid candidate values is available, include the
list as part of the error message.
Addresses #344.
- Removes `HelpInfo` in favor of a recursively defined `CommandInfo`
which contains more raw metadata about the source command.
Additionally, introduces a top level `ToolInfo` type with a
serialization version to aid future tooling.
- Updates tests to match the new serialized format.
- Renames `DumpHelpInfoGenerator` to `DumpHelpGenerator` to align the
type with the `--dump-help` flag.
- Removes unused codepaths.
- Simplifies synopsis string codepaths by removing optionality. This
complexity is moved to the caller who is now responsible for filtering
out hidden arguments and options. This change is desirable as it
allows the caller to determine if the argument should be hidden. For
example, while it makes sense to hide arguments in help text, it may
not make sense to hide them when dumping the arguments for another
tool to consume.
- Removes one layer of help properties by directly including the members
of ArgumentHelp in ArgumentDefinition.Help. This also results in the
discussion field which previously existed in both structures, now
having a single source of truth. Adds helper method for setting each
of these members using an instance of ArgumentHelp. Makes previously
optional Strings into plain Strings and updates points of use to check
for the empty string case.