43 Commits

Author SHA1 Message Date
dependabot[bot]
110c390a7b Bump the nuget group with 5 updates (#164)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-10-02 16:12:23 +03:00
dependabot[bot]
63f57025e8 Bump the nuget group with 5 updates (#163)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-08-04 14:13:09 +03:00
dependabot[bot]
7f2c00fe3a Bump the nuget group with 7 updates (#162)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-07-01 18:58:48 +03:00
Tyrrrz
7638b997ff Reorganize dependency conditions 2025-06-08 21:15:32 +03:00
dependabot[bot]
d80d012938 Bump Basic.Reference.Assemblies.Net80 and 5 others (#160)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-06-02 01:41:55 +03:00
Oleksii Holub
2a02d39dba Allow user-defined options to shadow implicit ones (--help, --version) (#159) 2025-05-12 22:53:08 +03:00
dependabot[bot]
c40b4f3501 Bump Microsoft.Extensions.DependencyInjection in the nuget group (#158)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-05-03 23:23:58 +03:00
dependabot[bot]
3fb2a2319b Bump the nuget group with 3 updates (#155)
Bumps the nuget group with 3 updates: [FluentAssertions](https://github.com/fluentassertions/fluentassertions), [Microsoft.Extensions.DependencyInjection](https://github.com/dotnet/runtime) and [CliWrap](https://github.com/Tyrrrz/CliWrap).


Updates `FluentAssertions` from 8.1.1 to 8.2.0
- [Release notes](https://github.com/fluentassertions/fluentassertions/releases)
- [Changelog](https://github.com/fluentassertions/fluentassertions/blob/main/AcceptApiChanges.ps1)
- [Commits](https://github.com/fluentassertions/fluentassertions/compare/8.1.1...8.2.0)

Updates `Microsoft.Extensions.DependencyInjection` from 9.0.2 to 9.0.3
- [Release notes](https://github.com/dotnet/runtime/releases)
- [Commits](https://github.com/dotnet/runtime/compare/v9.0.2...v9.0.3)

Updates `CliWrap` from 3.8.1 to 3.8.2
- [Release notes](https://github.com/Tyrrrz/CliWrap/releases)
- [Commits](https://github.com/Tyrrrz/CliWrap/compare/3.8.1...3.8.2)

---
updated-dependencies:
- dependency-name: FluentAssertions
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: nuget
- dependency-name: Microsoft.Extensions.DependencyInjection
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: nuget
- dependency-name: CliWrap
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: nuget
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-04-01 18:35:54 +03:00
dependabot[bot]
1a5a0374c7 Bump the nuget group with 6 updates (#153)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-03-03 21:47:10 +02:00
Tyrrrz
078ddeaf07 Handle breaking changes 2025-02-02 21:49:30 +02:00
dependabot[bot]
c79a8c6502 Bump the nuget group with 8 updates (#152)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-02-02 21:36:15 +02:00
dependabot[bot]
cfbd8f9e76 Bump the nuget group with 4 updates (#151)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-01-01 18:18:20 +02:00
dependabot[bot]
e329f0fc78 Bump the nuget group with 6 updates (#150)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-12-01 18:44:30 +02:00
Tyrrrz
bc2164499b Disable NuGet audit in benchmarks 2024-11-12 22:47:27 +02:00
Tyrrrz
f5ff6193e8 Use .NET 9 2024-11-12 22:38:15 +02:00
dependabot[bot]
36b2b07a1d Bump the nuget group with 7 updates (#149)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-11-02 00:46:43 +02:00
Tyrrrz
73bf19d766 Add readme note about keyed services with M.E.DI
Related to #148
2024-10-26 21:51:37 +03:00
Tyrrrz
093b6767c4 Resolve dependency conflicts 2024-10-01 21:49:03 +03:00
dependabot[bot]
e4671e50bb Bump the nuget group with 3 updates (#147)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-10-01 21:35:02 +03:00
dependabot[bot]
ab48098e06 Bump the nuget group with 5 updates (#146)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-09-01 19:05:41 +03:00
dependabot[bot]
e99a95ef7c Bump the nuget group with 2 updates (#145)
Bumps the nuget group with 2 updates: [xunit](https://github.com/xunit/xunit) and [xunit.runner.visualstudio](https://github.com/xunit/visualstudio.xunit).


Updates `xunit` from 2.8.1 to 2.9.0
- [Commits](https://github.com/xunit/xunit/compare/2.8.1...2.9.0)

Updates `xunit.runner.visualstudio` from 2.8.1 to 2.8.2
- [Release notes](https://github.com/xunit/visualstudio.xunit/releases)
- [Commits](https://github.com/xunit/visualstudio.xunit/compare/2.8.1...2.8.2)

---
updated-dependencies:
- dependency-name: xunit
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: nuget
- dependency-name: xunit.runner.visualstudio
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: nuget
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-08-01 22:54:53 +03:00
Tyrrrz
bcb34055ac Fix System.Command.Line usage 2024-05-31 18:56:49 +03:00
dependabot[bot]
fe935b5775 Bump the nuget group across 1 directory with 6 updates (#144)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-05-31 18:48:56 +03:00
Oleksii Holub
7dcd523bfe Create dependabot.yml 2024-05-31 03:32:15 +03:00
Tyrrrz
30bc1d3330 Clean up 2024-05-20 22:42:04 +03:00
Tyrrrz
a5a4ad05a0 Remove missing file references 2024-05-20 18:07:19 +03:00
Tyrrrz
0b77895ca5 Remove changelog 2024-04-28 19:00:24 +03:00
Tyrrrz
54994755b1 Update issue forms 2024-04-28 18:59:11 +03:00
Oleksii Holub
aee63cb9f2 Add Write(...), ``WriteLine(...), Read() and ReadLine() extension methods for IConsole (#140) 2024-01-23 23:57:33 +02:00
Tyrrrz
4bdd3ccc6c Refactor 2024-01-23 23:31:48 +02:00
Tyrrrz
6aa72e45e8 Use latest C# features 2024-01-12 00:10:27 +02:00
Tyrrrz
76e8d47e03 Update license 2024-01-01 03:09:19 +02:00
Tyrrrz
6304b8ab9c Update package release notes link 2023-12-31 16:29:15 +02:00
Tyrrrz
98b50d0e8e Fix typo 2023-12-27 19:24:40 +02:00
Tyrrrz
5aea869c2a Set default version for use during local development 2023-12-27 16:24:32 +02:00
Tyrrrz
425c8f4022 Standardize exception messages 2023-12-25 18:59:30 +02:00
Tyrrrz
490398f773 Refactor with C# 12 features 2023-12-10 22:51:57 +02:00
Tyrrrz
5854f36756 Fix workflows 2023-11-30 00:31:36 +02:00
Tyrrrz
ec6c72e6a3 Don't run the same job for both push and pull_request 2023-11-25 18:58:15 +02:00
Tyrrrz
41bc64be4a Suffix unstable packages with git hash 2023-11-24 20:54:28 +02:00
Tyrrrz
7df0e77e4d Fix typo 2023-11-23 18:44:56 +02:00
Tyrrrz
914e8e17cd Switch to a new versioning strategy 2023-11-23 18:39:03 +02:00
Tyrrrz
40f106d0b0 Update workflows 2023-11-16 21:34:22 +02:00
117 changed files with 1251 additions and 1714 deletions

View File

@@ -62,12 +62,14 @@ body:
required: true
- label: I have provided a descriptive title for this issue
required: true
- label: I have made sure that that this bug is reproducible on the latest version of the package
- label: I have made sure that this bug is reproducible on the latest version of the package
required: true
- label: I have provided all the information needed to reproduce this bug as efficiently as possible
required: true
- label: I have sponsored this project
required: false
- label: I have not read any of the above and just checked all the boxes to submit the issue
required: false
- type: markdown
attributes:

22
.github/dependabot.yml vendored Normal file
View File

@@ -0,0 +1,22 @@
version: 2
updates:
- package-ecosystem: github-actions
directory: "/"
schedule:
interval: monthly
labels:
- enhancement
groups:
actions:
patterns:
- "*"
- package-ecosystem: nuget
directory: "/"
schedule:
interval: monthly
labels:
- enhancement
groups:
nuget:
patterns:
- "*"

View File

@@ -13,16 +13,21 @@ on:
required: false
default: false
push:
branches:
- master
tags:
- "*"
pull_request:
branches:
- master
jobs:
main:
uses: Tyrrrz/.github/.github/workflows/nuget.yml@master
with:
dotnet-version: 8.0.x
package-version: ${{ inputs.package-version }}
# Deploy only on tags by default, unless deploy is explicitly requested
deploy-on-tags-only: ${{ !(github.event_name == 'workflow_dispatch' && inputs.deploy) }}
deploy: ${{ inputs.deploy || github.ref_type == 'tag' }}
package-version: ${{ inputs.package-version || (github.ref_type == 'tag' && github.ref_name) || format('0.0.0-ci-{0}', github.sha) }}
dotnet-version: 9.0.x
secrets:
CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}
NUGET_TOKEN: ${{ secrets.NUGET_TOKEN }}

View File

@@ -1,185 +0,0 @@
# Changelog
## v2.3.5 (16-Nov-2023)
- Fixed an issue where calling `CliApplication.RunAsync(IReadOnlyList<string>)` could fail in very specific scenarios on Windows, if there were two global environment variables with the same name but different casing. (Thanks [@alirezanet](https://github.com/alirezanet))
## v2.3.4 (18-May-2023)
- Added an overload of `CliApplicationBuilder.UseTypeActivator(...)` that accepts a `Func<IReadOnlyList<Type>, IServiceProvider>` delegate. The first parameter in the delegate is the list of all command types registered in the application. You can use this overload to more easily add the commands to a DI container. See the readme for an [updated example](https://github.com/Tyrrrz/CliFx/tree/2.3.4#type-activation).
## v2.3.3 (28-Apr-2023)
- Fixed an issue where the analyzers failed to load in some projects, due to targeting a Roslyn version that was too high.
## v2.3.2 (06-Apr-2023)
- Added name-based ordering to subcommands when displayed in the help text. (Thanks [@CartBlanche](https://github.com/CartBlanche))
## v2.3.1 (08-Dec-2022)
- Added support for the `required` keyword introduced in C# 11. Command options bound to required properties are now marked as required by default (equivalent to setting `IsRequired = true` on the attribute). Also added analyzers that prevent marking an option or parameter non-required if it's bound to a required property.
## v2.3 (12-Jul-2022)
- Added console dimension properties `WindowWidth` and `WindowHeight` to `IConsole` interface and implementing classes.
- Improved inline documentation for members of `IConsole` interface.
## v2.2.6 (14-Jun-2022)
- Added an overload of `CliApplicationBuilder.UseTypeActivator(...)` that accepts an instance of `IServiceProvider`. This slightly simplifies integration with many DI containers.
- Fixed minor grammar mistakes in user-facing error messages.
## v2.2.5 (10-May-2022)
- Updated default value resolution for the application executable name. It will now resolve to `myapp.exe` instead of `dotnet myapp.dll` when the application is launched through the EXE apphost on Windows. On other platforms, or when running the application through the .NET CLI, the behavior will be the same as before.
## v2.2.4 (22-Apr-2022)
- Added more contextual information to analyzer diagnostics.
- Fixed an issue where the analyzer incorrectly reported an error on converters that didn't directly match the target type but were compatible through known built-in conversions.
- Fixed an issue where MSBuild produced a lot of analyzer-related warnings in certain circumstances.
## v2.2.3 (17-Apr-2022)
- Changed method signature of `IConsole.ReadKey()` to return `ConsoleKeyInfo` instead of `void`. The return type was originally defined as `void` by mistake. This change is source-backwards-compatible but may break on binary level if you were previously calling this method indirectly (i.e. through a library).
- Added `FakeConsole.EnqueueKey(...)` to facilitate the testing of `IConsole.ReadKey()`. You can use this method to simulate key presses in your application.
- Extended analyzers that verify the correctness of specified converters and validators. They now also ensure that the specified types are compatible with the type of the underlying property.
- Improved diagnostics produced by analyzers. Where relevant, highlighted code is now limited to the property or type identifier, instead of the whole property or type declaration. Also extended the diagnostic messages with additional information.
- Fixed an issue where throwing an exception inside a constructor of a command type resulted in an unrelated error message about the absence of a parameterless constructor.
## v2.2.2 (30-Jan-2022)
- Fixed an issue where `ConsoleWriter` and `ConsoleReader` were not properly thread-safe.
- Fixed an issue where the analyzer failed to load under certain circumstances when running inside Visual Studio.
## v2.2.1 (16-Jan-2022)
- Fixed an issue which caused help text to not show default values for optional parameters. (Thanks [@AliReZa Sabouri](https://github.com/alirezanet))
## v2.2 (11-Jan-2022)
- Added support for optional parameters. A parameter can be marked as optional by setting `IsRequired = false` on the attribute. Only one parameter is allowed to be optional and such parameter must be the last in order. (Thanks [@AliReZa Sabouri](https://github.com/alirezanet))
- Fixed an issue where parameters and options bound to properties implemented as default interface members were not working correctly. (Thanks [@AliReZa Sabouri](https://github.com/alirezanet))
## v2.1 (04-Jan-2022)
- Added `IConsole.Clear()` with corresponding implementations in `SystemConsole`, `FakeConsole`, and `FakeInMemoryConsole`. (Thanks [@Alex Rosenfeld](https://github.com/alexrosenfeld10))
- Added `IConsole.ReadKey()` with corresponding implementations in `SystemConsole`, `FakeConsole`, and `FakeInMemoryConsole`. (Thanks [@Alex Rosenfeld](https://github.com/alexrosenfeld10))
- Fixed an issue that caused parameters to appear out of order in the usage format section of the help text. (Thanks [@David Fallah](https://github.com/TAGC))
## v2.0.6 (17-Jul-2021)
- Fixed an issue where an exception thrown via reflection during parameter or option binding resulted in `Exception has been thrown by the target of an invocation` error instead of a more useful message. Such exceptions will now be unwrapped to provide better user experience.
## v2.0.5 (09-Jul-2021)
- Fixed an issue where calling `IConsole.Output.Encoding.EncodingName` and some other members threw an exception.
- Added readme file to the package.
## v2.0.4 (24-Apr-2021)
- Fixed an issue where output and error streams in `SystemConsole` defaulted to UTF8 encoding with BOM when the application was running with UTF8 codepage. `ConsoleWriter` will now discard preamble from the specified encoding. This fix brings the behavior of `SystemConsole` in line with .NET's own `System.Console` which also discards preamble for output and error streams.
- Fixed an issue where help text tried to show default values for parameters and options whose type does not override `ToString()` method.
- Fixed an issue where help text didn't show default values for parameters and options whose type is an enumerable of nullable enums. (Thanks [@Robert Dailey](https://github.com/rcdailey))
- Fixed an issue where specific parts of the help text weren't legible in some terminals due to low color resolution. Removed the usage of `ConsoleColor.DarkGray` in help text.
## v2.0.3 (09-Apr-2021)
- Improved help text by showing valid values for non-scalar enum parameters and options. (Thanks [@Robert Dailey](https://github.com/rcdailey))
## v2.0.2 (31-Mar-2021)
- Fixed an issue where having a transitive reference to CliFx sometimes resulted in `SystemConsoleShouldBeAvoidedAnalyzer` throwing `NullReferenceException` during build.
- Fixed some documentation typos and inconsistencies.
## v2.0.1 (24-Mar-2021)
- Fixed an issue where some exceptions with async stack traces generated on .NET 3.1 or earlier were not parsed and formatted correctly.
- Fixed an issue where help text applied slightly incorrect formatting when displaying choices for enum-based parameters and properties.
## v2.0 (21-Mar-2021)
> Note: this major release includes many breaking changes.
> Please refer to the readme to find updated instructions and usage examples.
- Renamed property `EnvironmentVariableName` to `EnvironmentVariable` on `CommandOption` attribute.
- Removed most of schema validation checks that used to take place during application startup. Going forward, CliFx will be relying solely on its built-in set of Roslyn analyzers to catch common errors in command configuration.
- Removed `ProgressTicker` utility. The recommended migration path is to use the [Spectre.Console](https://github.com/spectresystems/spectre.console) library which provides a wide array of console widgets and components. See [this wiki page](https://github.com/Tyrrrz/CliFx/wiki/Integrating-with-Spectre.Console) to learn how to integrate Spectre.Console with CliFx.
- Removed `MemoryStreamWriter` utility as it's no longer used within CliFx.
- Improved wording in all error messages.
- Renamed some methods on `CliApplicationBuilder`:
- `UseTitle()` renamed to `SetTitle()`
- `UseExecutableName()` renamed to `SetExecutableName()`
- `UseVersionText()` renamed to `SetVersion()`
- `UseDescription()` renamed to `SetDescription()`
- Changed the behavior of autogenerated help text:
- Changed the color scheme to a more neutral set of tones
- Assigned separate colors to parameters and options to make them visually stand out
- Usage section no longer lists usage formats of all descendant commands
- Command section now also lists available subcommands for each of the current command's subcommands
- Changed the behavior of `[preview]` directive. Running the application with this directive will now also print all resolved environment variables, in addition to parsed command-line arguments.
- Reworked `IArgumentValueConverter`/`ArgumentValueConverter` into `BindingConverter`. Method `ConvertFrom(...)` has been renamed to `Convert(...)`.
- Reworked `ArgumentValueValidator` into `BindingValidator`. This class exposes an abstract `Validate(...)` method that returns a nullable `BindingValidationError`. This class also provides utility methods `Ok()` and `Error(...)` to help create corresponding validation results.
- Changed the type of `IConsole.Output` and `IConsole.Error` from `StreamWriter` to `ConsoleWriter`. This type derives from `StreamWriter` and additionally exposes a `Console` property that refers to the console instance that owns the stream. This change enables you to author extension methods scoped specifically to console output and error streams.
- Changed the type of `IConsole.Input` from `StreamReader` to `ConsoleReader`. This type derives from `StreamReader` and additionally exposes a `Console` property that refers to the console instance that owns the stream. This change enables you to author extension methods scoped specifically to the console input stream.
- Changed methods `IConsole.WithForegroundColor(...)`, `IConsole.WithBackgroundColor(...)`, and `IConsole.WithColors(...)` to return `IDisposable`, replacing the delegate parameter they previously had. You can wrap the returned `IDisposable` in a using statement to ensure that the console colors get reset back to their original values once the execution reaches the end of the block.
- Renamed `IConsole.GetCancellationToken()` to `IConsole.RegisterCancellationHandler()`.
- Reworked `VirtualConsole` into `FakeConsole`. This class no longer takes `CancellationToken` as a constructor parameter, but instead encapsulates its own instance of `CancellationTokenSource` that can be triggered using the provided `RequestCancellation()` method.
- Removed `VirtualConsole.CreateBuffered()` and replaced it with the `FakeInMemoryConsole` class. This class derives from `FakeConsole` and uses in-memory standard input, output, and error streams. It also provides methods to easily read the data written to the streams.
- Moved some types to different namespaces:
- `IConsole`/`FakeConsole`/`FakeInMemoryConsole` moved from `CliFx` to `CliFx.Infrastructure`
- `ITypeActivator`/`DefaultTypeActivator`/`DelegateTypeActivator` moved from `CliFx` to `CliFx.Infrastructure`
- `BindingValidator`/`BindingConverter` moved from `CliFx` to `CliFx.Extensibility`
## v1.6 (06-Dec-2020)
- Added support for custom value validators. You can now create a type that inherits from `CliFx.ArgumentValueValidator<T>` to implement reusable validation logic for command arguments. To use a validator, include it in the `Validators` property on the `CommandOption` or `CommandParameter` attribute. (Thanks [@Oleksandr Shustov](https://github.com/AlexandrShustov))
- Added `CliFx.ArgumentValueConverter<T>` class that you can inherit from to implement custom value converters. `CliFx.IArgumentValueConverter` interface is still available, but it is recommended to inherit from the generic class instead, due to the type safety it provides. The interface may become internal or get removed in one of the future major versions.
- Updated requirements for option names and short names: short names now must be letter characters (lowercase or uppercase), while names must now start with a letter character. This means option names can no longer start with a digit or a special character. This change makes it possible to pass negative number values without the need to quote them, i.e. `--my-number -5`.
## v1.5 (23-Oct-2020)
- Added pretty-printing for unhandled exceptions thrown from within the application. This makes the errors easier to parse visually and should help in troubleshooting. This change does not affect `CommandException`, as it already has special treatment. (Thanks [@Mårten Åsberg](https://github.com/89netraM))
- Added support for custom value converters. You can now create a type that implements `CliFx.IArgumentValueConverter` and specify it as a converter for your parameters or options via the `Converter` named property. This should enable conversion between raw argument values and custom types which are not string-initializable. (Thanks [@Oleksandr Shustov](https://github.com/AlexandrShustov))
- Improved help text so that it also shows minimal usage examples for child and descendant commands, besides the actual command it was requested on. This should improve user experience for applications with many nested commands. (Thanks [@Nikiforov Alexey](https://github.com/NikiforovAll))
## v1.4 (20-Aug-2020)
- Added `VirtualConsole.CreateBuffered()` method to simplify test setup when using in-memory backing stores for output and error streams. Please refer to the readme for updated recommendations on how to test applications built with CliFx.
- Added generic `CliApplicationBuilder.AddCommand<TCommand>()`. This overload simplifies adding commands one-by-one as it also checks that the type implements `ICommand`.
## v1.3.2 (31-Jul-2020)
- Fixed an issue where a command was incorrectly allowed to execute when the user did not specify any value for a non-scalar parameter. Since they are always required, a parameter needs to be bound to at least one value. (Thanks [@Daniel Hix](https://github.com/ADustyOldMuffin))
- Fixed an issue where `CliApplication.RunAsync(...)` threw `ArgumentException` if there were two environment variables, whose names differed only in case. Environment variable names are now treated case-sensitively. (Thanks [@Ron Myers](https://github.com/ron-myers))
## v1.3.1 (19-Jul-2020)
- Running the application with the debug directive (`myapp [debug]`) will now also try to launch a debugger instance. In most cases it will save time as you won't need to attach the debugger manually. (Thanks [@Volodymyr Shkolka](https://github.com/BlackGad))
- Fixed an issue where unhandled generic exceptions (i.e. not `CommandException`) sometimes caused the application to incorrectly return successful exit code due to an overflow issue on Unix systems. Starting from this version, all unhandled generic exceptions will produce `1` as the exit code when thrown. Instances of `CommandException` can still be configured to return any specified exit code, but it's recommended to constrain the values between `1` and `255` to avoid overflow issues. (Thanks [@Ihor Nechyporuk](https://github.com/inech))
## v1.3 (23-May-2020)
- Changed analyzers to report errors instead of warnings. If you find that some analyzer works incorrectly, please report it on GitHub. You can also configure inspection severity overrides in your project if you need to.
- Improved help text by showing default values for non-required options. This only works on types that have a custom override for `ToString()` method. Additionally, if the type implements `IFormattable`, the overload with a format provider will be used instead. (Thanks [@Domn Werner](https://github.com/domn1995))
- Changed default version text to only show 3 version components instead of 4, if the last component (revision) is not specified or is zero. This makes the default version text compliant with semantic versioning.
- Fixed an issue where it was possible to define a command with an option that has the same name or short name as built-in help or version options. Previously it would lead to the user-defined option being ignored in favor of the built-in option. Now this will throw an exception instead.
- Changed the underlying representation of `StreamReader`/`StreamWriter` objects used in `SystemConsole` and `VirtualConsole` to be thread-safe.
## v1.2 (11-May-2020)
- Added built-in Roslyn analyzers that help catch incorrect usage of the library. Currently, all analyzers report issues as warnings so as to not prevent the project from building. In the future that may change.
- Added an optional parameter to `new CommandException(...)` called `showHelp` which can be used to instruct CliFx to show help for the current command after printing the error. (Thanks [@Domn Werner](https://github.com/domn1995))
- Improved help text shown for enum options and parameters by providing the list of valid values that the enum can accept. (Thanks [@Domn Werner](https://github.com/domn1995))
- Fixed an issue where it was possible to set an option without providing a value, while the option was marked as required.
- Fixed an issue where it was possible to configure an option with an empty name or a name consisting of a single character. If you want to use a single character as a name, you should set the option's short name instead.
- Added `CursorLeft` and `CursorTop` properties to `IConsole` and its implementations. In `VirtualConsole`, these are just auto-properties.
- Improved exception messages.
- Improved exceptions related to user input by also showing help text after the error message. (Thanks [@Domn Werner](https://github.com/domn1995))
## v1.1 (16-Mar-2020)
- Changed `IConsole` interface (and as a result, `SystemConsole` and `VirtualConsole`) to support writing binary data. Instead of `TextReader`/`TextWriter` instances, the streams are now exposed as `StreamReader`/`StreamWriter` which provide the `BaseStream` property that allows raw access. Existing usages inside commands should remain the same because `StreamReader`/`StreamWriter` are compatible with their base classes `TextReader`/`TextWriter`, but if you were using `VirtualConsole` in tests, you may have to update it to the new API. Refer to the readme for more info.
- Changed argument binding behavior so that an error is produced if the user provides an argument that doesn't match with any parameter or option. This is done in order to improve user experience, as otherwise the user may make a typo without knowing that their input wasn't taken into account.
- Changed argument binding behavior so that options can be set to multiple argument values while specifying them with mixed naming. For example, `--option value1 -o value2 --option value3` would result in the option being set to corresponding three values, assuming `--option` and `-o` match with the same option.

View File

@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<TargetFramework>net9.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
@@ -9,15 +9,15 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Basic.Reference.Assemblies.Net70" Version="1.4.5" />
<PackageReference Include="coverlet.collector" Version="6.0.0" PrivateAssets="all" />
<PackageReference Include="CSharpier.MsBuild" Version="0.26.1" PrivateAssets="all" />
<PackageReference Include="GitHubActionsTestLogger" Version="2.3.3" PrivateAssets="all" />
<PackageReference Include="FluentAssertions" Version="6.12.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.7.0" />
<PackageReference Include="xunit" Version="2.6.1" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.5.3" PrivateAssets="all" />
<PackageReference Include="Basic.Reference.Assemblies.Net80" Version="1.8.3" />
<PackageReference Include="coverlet.collector" Version="6.0.4" PrivateAssets="all" />
<PackageReference Include="CSharpier.MsBuild" Version="0.30.6" PrivateAssets="all" />
<PackageReference Include="GitHubActionsTestLogger" Version="2.4.1" PrivateAssets="all" />
<PackageReference Include="FluentAssertions" Version="8.7.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.11.0" />
<PackageReference Include="xunit" Version="2.9.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.5" PrivateAssets="all" />
</ItemGroup>
<ItemGroup>

View File

@@ -13,8 +13,7 @@ public class GeneralSpecs
{
// Arrange
var analyzers = typeof(AnalyzerBase)
.Assembly
.GetTypes()
.Assembly.GetTypes()
.Where(t => !t.IsAbstract && t.IsAssignableTo(typeof(DiagnosticAnalyzer)))
.Select(t => (DiagnosticAnalyzer)Activator.CreateInstance(t)!)
.ToArray();

View File

@@ -83,7 +83,7 @@ public class SystemConsoleShouldBeAvoidedAnalyzerSpecs
{
public ValueTask ExecuteAsync(IConsole console)
{
console.Output.WriteLine("Hello world");
console.WriteLine("Hello world");
return default;
}
}

View File

@@ -13,12 +13,12 @@ using Microsoft.CodeAnalysis.Text;
namespace CliFx.Analyzers.Tests.Utils;
internal class AnalyzerAssertions : ReferenceTypeAssertions<DiagnosticAnalyzer, AnalyzerAssertions>
internal class AnalyzerAssertions(DiagnosticAnalyzer analyzer, AssertionChain assertionChain)
: ReferenceTypeAssertions<DiagnosticAnalyzer, AnalyzerAssertions>(analyzer, assertionChain)
{
protected override string Identifier { get; } = "analyzer";
private readonly AssertionChain _assertionChain = assertionChain;
public AnalyzerAssertions(DiagnosticAnalyzer analyzer)
: base(analyzer) { }
protected override string Identifier => "analyzer";
private Compilation Compile(string sourceCode)
{
@@ -27,13 +27,12 @@ internal class AnalyzerAssertions : ReferenceTypeAssertions<DiagnosticAnalyzer,
{
"System",
"System.Collections.Generic",
"System.Threading.Tasks"
"System.Threading.Tasks",
};
// Get default CliFx namespaces
var defaultCliFxNamespaces = typeof(ICommand)
.Assembly
.GetTypes()
.Assembly.GetTypes()
.Where(t => t.IsPublic)
.Select(t => t.Namespace)
.Distinct()
@@ -49,17 +48,16 @@ internal class AnalyzerAssertions : ReferenceTypeAssertions<DiagnosticAnalyzer,
// Parse the source code
var ast = SyntaxFactory.ParseSyntaxTree(
SourceText.From(sourceCodeWithUsings),
CSharpParseOptions.Default
CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.Preview)
);
// Compile the code to IL
var compilation = CSharpCompilation.Create(
"CliFxTests_DynamicAssembly_" + Guid.NewGuid(),
new[] { ast },
Net70
.References
.All
.Append(MetadataReference.CreateFromFile(typeof(ICommand).Assembly.Location)),
[ast],
Net80.References.All.Append(
MetadataReference.CreateFromFile(typeof(ICommand).Assembly.Location)
),
// DLL to avoid having to define the Main() method
new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)
);
@@ -106,8 +104,7 @@ internal class AnalyzerAssertions : ReferenceTypeAssertions<DiagnosticAnalyzer,
expectedDiagnosticIds.Intersect(producedDiagnosticIds).Count()
== expectedDiagnosticIds.Length;
Execute
.Assertion
_assertionChain
.ForCondition(isSuccessfulAssertion)
.FailWith(() =>
{
@@ -151,8 +148,7 @@ internal class AnalyzerAssertions : ReferenceTypeAssertions<DiagnosticAnalyzer,
var producedDiagnostics = GetProducedDiagnostics(sourceCode);
var isSuccessfulAssertion = !producedDiagnostics.Any();
Execute
.Assertion
_assertionChain
.ForCondition(isSuccessfulAssertion)
.FailWith(() =>
{
@@ -176,5 +172,6 @@ internal class AnalyzerAssertions : ReferenceTypeAssertions<DiagnosticAnalyzer,
internal static class AnalyzerAssertionsExtensions
{
public static AnalyzerAssertions Should(this DiagnosticAnalyzer analyzer) => new(analyzer);
public static AnalyzerAssertions Should(this DiagnosticAnalyzer analyzer) =>
new(analyzer, AssertionChain.GetOrCreate());
}

View File

@@ -17,11 +17,11 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="CSharpier.MsBuild" Version="0.26.1" PrivateAssets="all" />
<PackageReference Include="CSharpier.MsBuild" Version="0.30.6" PrivateAssets="all" />
<!-- Make sure to target the lowest possible version of the compiler for wider support -->
<PackageReference Include="Microsoft.CodeAnalysis" Version="3.0.0" PrivateAssets="all" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="3.0.0" PrivateAssets="all" />
<PackageReference Include="PolyShim" Version="1.8.0" PrivateAssets="all" />
<PackageReference Include="PolyShim" Version="1.15.0" PrivateAssets="all" />
</ItemGroup>
</Project>

View File

@@ -8,14 +8,12 @@ using Microsoft.CodeAnalysis.Diagnostics;
namespace CliFx.Analyzers;
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class CommandMustBeAnnotatedAnalyzer : AnalyzerBase
{
public CommandMustBeAnnotatedAnalyzer()
: base(
public class CommandMustBeAnnotatedAnalyzer()
: AnalyzerBase(
$"Commands must be annotated with `{SymbolNames.CliFxCommandAttribute}`",
$"This type must be annotated with `{SymbolNames.CliFxCommandAttribute}` in order to be a valid command."
) { }
)
{
private void Analyze(
SyntaxNodeAnalysisContext context,
ClassDeclarationSyntax classDeclaration,
@@ -28,8 +26,8 @@ public class CommandMustBeAnnotatedAnalyzer : AnalyzerBase
if (type.IsAbstract)
return;
var implementsCommandInterface = type.AllInterfaces.Any(
i => i.DisplayNameMatches(SymbolNames.CliFxCommandInterface)
var implementsCommandInterface = type.AllInterfaces.Any(i =>
i.DisplayNameMatches(SymbolNames.CliFxCommandInterface)
);
var hasCommandAttribute = type.GetAttributes()

View File

@@ -8,14 +8,12 @@ using Microsoft.CodeAnalysis.Diagnostics;
namespace CliFx.Analyzers;
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class CommandMustImplementInterfaceAnalyzer : AnalyzerBase
{
public CommandMustImplementInterfaceAnalyzer()
: base(
public class CommandMustImplementInterfaceAnalyzer()
: AnalyzerBase(
$"Commands must implement `{SymbolNames.CliFxCommandInterface}` interface",
$"This type must implement `{SymbolNames.CliFxCommandInterface}` interface in order to be a valid command."
) { }
)
{
private void Analyze(
SyntaxNodeAnalysisContext context,
ClassDeclarationSyntax classDeclaration,
@@ -26,8 +24,8 @@ public class CommandMustImplementInterfaceAnalyzer : AnalyzerBase
.Select(a => a.AttributeClass)
.Any(c => c.DisplayNameMatches(SymbolNames.CliFxCommandAttribute));
var implementsCommandInterface = type.AllInterfaces.Any(
i => i.DisplayNameMatches(SymbolNames.CliFxCommandInterface)
var implementsCommandInterface = type.AllInterfaces.Any(i =>
i.DisplayNameMatches(SymbolNames.CliFxCommandInterface)
);
// If the attribute is present, but the interface is not implemented,

View File

@@ -5,36 +5,26 @@ using Microsoft.CodeAnalysis;
namespace CliFx.Analyzers.ObjectModel;
internal partial class CommandOptionSymbol : ICommandMemberSymbol
{
public IPropertySymbol Property { get; }
public string? Name { get; }
public char? ShortName { get; }
public bool? IsRequired { get; }
public ITypeSymbol? ConverterType { get; }
public IReadOnlyList<ITypeSymbol> ValidatorTypes { get; }
public CommandOptionSymbol(
internal partial class CommandOptionSymbol(
IPropertySymbol property,
string? name,
char? shortName,
bool? isRequired,
ITypeSymbol? converterType,
IReadOnlyList<ITypeSymbol> validatorTypes
)
) : ICommandMemberSymbol
{
Property = property;
Name = name;
ShortName = shortName;
IsRequired = isRequired;
ConverterType = converterType;
ValidatorTypes = validatorTypes;
}
public IPropertySymbol Property { get; } = property;
public string? Name { get; } = name;
public char? ShortName { get; } = shortName;
public bool? IsRequired { get; } = isRequired;
public ITypeSymbol? ConverterType { get; } = converterType;
public IReadOnlyList<ITypeSymbol> ValidatorTypes { get; } = validatorTypes;
}
internal partial class CommandOptionSymbol
@@ -42,8 +32,7 @@ internal partial class CommandOptionSymbol
private static AttributeData? TryGetOptionAttribute(IPropertySymbol property) =>
property
.GetAttributes()
.FirstOrDefault(
a =>
.FirstOrDefault(a =>
a.AttributeClass?.DisplayNameMatches(SymbolNames.CliFxCommandOptionAttribute)
== true
);
@@ -56,35 +45,30 @@ internal partial class CommandOptionSymbol
var name =
attribute
.ConstructorArguments
.Where(a => a.Type?.SpecialType == SpecialType.System_String)
.ConstructorArguments.Where(a => a.Type?.SpecialType == SpecialType.System_String)
.Select(a => a.Value)
.FirstOrDefault() as string;
var shortName =
attribute
.ConstructorArguments
.Where(a => a.Type?.SpecialType == SpecialType.System_Char)
.ConstructorArguments.Where(a => a.Type?.SpecialType == SpecialType.System_Char)
.Select(a => a.Value)
.FirstOrDefault() as char?;
var isRequired =
attribute
.NamedArguments
.Where(a => a.Key == "IsRequired")
.NamedArguments.Where(a => a.Key == "IsRequired")
.Select(a => a.Value.Value)
.FirstOrDefault() as bool?;
var converter = attribute
.NamedArguments
.Where(a => a.Key == "Converter")
.NamedArguments.Where(a => a.Key == "Converter")
.Select(a => a.Value.Value)
.Cast<ITypeSymbol?>()
.FirstOrDefault();
var validators = attribute
.NamedArguments
.Where(a => a.Key == "Validators")
.NamedArguments.Where(a => a.Key == "Validators")
.SelectMany(a => a.Value.Values)
.Select(c => c.Value)
.Cast<ITypeSymbol>()

View File

@@ -5,36 +5,26 @@ using Microsoft.CodeAnalysis;
namespace CliFx.Analyzers.ObjectModel;
internal partial class CommandParameterSymbol : ICommandMemberSymbol
{
public IPropertySymbol Property { get; }
public int Order { get; }
public string? Name { get; }
public bool? IsRequired { get; }
public ITypeSymbol? ConverterType { get; }
public IReadOnlyList<ITypeSymbol> ValidatorTypes { get; }
public CommandParameterSymbol(
internal partial class CommandParameterSymbol(
IPropertySymbol property,
int order,
string? name,
bool? isRequired,
ITypeSymbol? converterType,
IReadOnlyList<ITypeSymbol> validatorTypes
)
) : ICommandMemberSymbol
{
Property = property;
Order = order;
Name = name;
IsRequired = isRequired;
ConverterType = converterType;
ValidatorTypes = validatorTypes;
}
public IPropertySymbol Property { get; } = property;
public int Order { get; } = order;
public string? Name { get; } = name;
public bool? IsRequired { get; } = isRequired;
public ITypeSymbol? ConverterType { get; } = converterType;
public IReadOnlyList<ITypeSymbol> ValidatorTypes { get; } = validatorTypes;
}
internal partial class CommandParameterSymbol
@@ -42,8 +32,7 @@ internal partial class CommandParameterSymbol
private static AttributeData? TryGetParameterAttribute(IPropertySymbol property) =>
property
.GetAttributes()
.FirstOrDefault(
a =>
.FirstOrDefault(a =>
a.AttributeClass?.DisplayNameMatches(SymbolNames.CliFxCommandParameterAttribute)
== true
);
@@ -58,28 +47,24 @@ internal partial class CommandParameterSymbol
var name =
attribute
.NamedArguments
.Where(a => a.Key == "Name")
.NamedArguments.Where(a => a.Key == "Name")
.Select(a => a.Value.Value)
.FirstOrDefault() as string;
var isRequired =
attribute
.NamedArguments
.Where(a => a.Key == "IsRequired")
.NamedArguments.Where(a => a.Key == "IsRequired")
.Select(a => a.Value.Value)
.FirstOrDefault() as bool?;
var converter = attribute
.NamedArguments
.Where(a => a.Key == "Converter")
.NamedArguments.Where(a => a.Key == "Converter")
.Select(a => a.Value.Value)
.Cast<ITypeSymbol?>()
.FirstOrDefault();
var validators = attribute
.NamedArguments
.Where(a => a.Key == "Validators")
.NamedArguments.Where(a => a.Key == "Validators")
.SelectMany(a => a.Value.Values)
.Select(c => c.Value)
.Cast<ITypeSymbol>()

View File

@@ -8,14 +8,12 @@ using Microsoft.CodeAnalysis.Diagnostics;
namespace CliFx.Analyzers;
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class OptionMustBeInsideCommandAnalyzer : AnalyzerBase
{
public OptionMustBeInsideCommandAnalyzer()
: base(
public class OptionMustBeInsideCommandAnalyzer()
: AnalyzerBase(
"Options must be defined inside commands",
$"This option must be defined inside a class that implements `{SymbolNames.CliFxCommandInterface}`."
) { }
)
{
private void Analyze(
SyntaxNodeAnalysisContext context,
PropertyDeclarationSyntax propertyDeclaration,
@@ -31,10 +29,9 @@ public class OptionMustBeInsideCommandAnalyzer : AnalyzerBase
if (!CommandOptionSymbol.IsOptionProperty(property))
return;
var isInsideCommand = property
.ContainingType
.AllInterfaces
.Any(i => i.DisplayNameMatches(SymbolNames.CliFxCommandInterface));
var isInsideCommand = property.ContainingType.AllInterfaces.Any(i =>
i.DisplayNameMatches(SymbolNames.CliFxCommandInterface)
);
if (!isInsideCommand)
{

View File

@@ -7,14 +7,12 @@ using Microsoft.CodeAnalysis.Diagnostics;
namespace CliFx.Analyzers;
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class OptionMustBeRequiredIfPropertyRequiredAnalyzer : AnalyzerBase
{
public OptionMustBeRequiredIfPropertyRequiredAnalyzer()
: base(
public class OptionMustBeRequiredIfPropertyRequiredAnalyzer()
: AnalyzerBase(
"Options bound to required properties cannot be marked as non-required",
"This option cannot be marked as non-required because it's bound to a required property."
) { }
)
{
private void Analyze(
SyntaxNodeAnalysisContext context,
PropertyDeclarationSyntax propertyDeclaration,

View File

@@ -7,14 +7,12 @@ using Microsoft.CodeAnalysis.Diagnostics;
namespace CliFx.Analyzers;
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class OptionMustHaveNameOrShortNameAnalyzer : AnalyzerBase
{
public OptionMustHaveNameOrShortNameAnalyzer()
: base(
public class OptionMustHaveNameOrShortNameAnalyzer()
: AnalyzerBase(
"Options must have either a name or short name specified",
"This option must have either a name or short name specified."
) { }
)
{
private void Analyze(
SyntaxNodeAnalysisContext context,
PropertyDeclarationSyntax propertyDeclaration,

View File

@@ -9,16 +9,14 @@ using Microsoft.CodeAnalysis.Diagnostics;
namespace CliFx.Analyzers;
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class OptionMustHaveUniqueNameAnalyzer : AnalyzerBase
{
public OptionMustHaveUniqueNameAnalyzer()
: base(
public class OptionMustHaveUniqueNameAnalyzer()
: AnalyzerBase(
"Options must have unique names",
"This option's name must be unique within the command (comparison IS NOT case sensitive). "
+ "Specified name: `{0}`. "
+ "Property bound to another option with the same name: `{1}`."
) { }
)
{
private void Analyze(
SyntaxNodeAnalysisContext context,
PropertyDeclarationSyntax propertyDeclaration,
@@ -36,8 +34,7 @@ public class OptionMustHaveUniqueNameAnalyzer : AnalyzerBase
return;
var otherProperties = property
.ContainingType
.GetMembers()
.ContainingType.GetMembers()
.OfType<IPropertySymbol>()
.Where(m => !m.Equals(property))
.ToArray();

View File

@@ -8,16 +8,14 @@ using Microsoft.CodeAnalysis.Diagnostics;
namespace CliFx.Analyzers;
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class OptionMustHaveUniqueShortNameAnalyzer : AnalyzerBase
{
public OptionMustHaveUniqueShortNameAnalyzer()
: base(
public class OptionMustHaveUniqueShortNameAnalyzer()
: AnalyzerBase(
"Options must have unique short names",
"This option's short name must be unique within the command (comparison IS case sensitive). "
+ "Specified short name: `{0}` "
+ "Property bound to another option with the same short name: `{1}`."
) { }
)
{
private void Analyze(
SyntaxNodeAnalysisContext context,
PropertyDeclarationSyntax propertyDeclaration,
@@ -35,8 +33,7 @@ public class OptionMustHaveUniqueShortNameAnalyzer : AnalyzerBase
return;
var otherProperties = property
.ContainingType
.GetMembers()
.ContainingType.GetMembers()
.OfType<IPropertySymbol>()
.Where(m => !m.Equals(property))
.ToArray();

View File

@@ -8,14 +8,12 @@ using Microsoft.CodeAnalysis.Diagnostics;
namespace CliFx.Analyzers;
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class OptionMustHaveValidConverterAnalyzer : AnalyzerBase
{
public OptionMustHaveValidConverterAnalyzer()
: base(
public class OptionMustHaveValidConverterAnalyzer()
: AnalyzerBase(
$"Option converters must derive from `{SymbolNames.CliFxBindingConverterClass}`",
$"Converter specified for this option must derive from a compatible `{SymbolNames.CliFxBindingConverterClass}`."
) { }
)
{
private void Analyze(
SyntaxNodeAnalysisContext context,
PropertyDeclarationSyntax propertyDeclaration,
@@ -30,13 +28,11 @@ public class OptionMustHaveValidConverterAnalyzer : AnalyzerBase
return;
var converterValueType = option
.ConverterType
.GetBaseTypes()
.FirstOrDefault(
t => t.ConstructedFrom.DisplayNameMatches(SymbolNames.CliFxBindingConverterClass)
.ConverterType.GetBaseTypes()
.FirstOrDefault(t =>
t.ConstructedFrom.DisplayNameMatches(SymbolNames.CliFxBindingConverterClass)
)
?.TypeArguments
.FirstOrDefault();
?.TypeArguments.FirstOrDefault();
// Value returned by the converter must be assignable to the property type
var isCompatible =
@@ -47,9 +43,10 @@ public class OptionMustHaveValidConverterAnalyzer : AnalyzerBase
? context.Compilation.IsAssignable(converterValueType, property.Type)
// Non-scalar (assume we can handle all IEnumerable types for simplicity)
: property.Type.TryGetEnumerableUnderlyingType() is { } enumerableUnderlyingType
&& context
.Compilation
.IsAssignable(converterValueType, enumerableUnderlyingType)
&& context.Compilation.IsAssignable(
converterValueType,
enumerableUnderlyingType
)
);
if (!isCompatible)

View File

@@ -7,15 +7,13 @@ using Microsoft.CodeAnalysis.Diagnostics;
namespace CliFx.Analyzers;
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class OptionMustHaveValidNameAnalyzer : AnalyzerBase
{
public OptionMustHaveValidNameAnalyzer()
: base(
public class OptionMustHaveValidNameAnalyzer()
: AnalyzerBase(
"Options must have valid names",
"This option's name must be at least 2 characters long and must start with a letter. "
+ "Specified name: `{0}`."
) { }
)
{
private void Analyze(
SyntaxNodeAnalysisContext context,
PropertyDeclarationSyntax propertyDeclaration,

View File

@@ -7,15 +7,13 @@ using Microsoft.CodeAnalysis.Diagnostics;
namespace CliFx.Analyzers;
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class OptionMustHaveValidShortNameAnalyzer : AnalyzerBase
{
public OptionMustHaveValidShortNameAnalyzer()
: base(
public class OptionMustHaveValidShortNameAnalyzer()
: AnalyzerBase(
"Option short names must be letter characters",
"This option's short name must be a single letter character. "
+ "Specified short name: `{0}`."
) { }
)
{
private void Analyze(
SyntaxNodeAnalysisContext context,
PropertyDeclarationSyntax propertyDeclaration,

View File

@@ -8,14 +8,12 @@ using Microsoft.CodeAnalysis.Diagnostics;
namespace CliFx.Analyzers;
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class OptionMustHaveValidValidatorsAnalyzer : AnalyzerBase
{
public OptionMustHaveValidValidatorsAnalyzer()
: base(
public class OptionMustHaveValidValidatorsAnalyzer()
: AnalyzerBase(
$"Option validators must derive from `{SymbolNames.CliFxBindingValidatorClass}`",
$"Each validator specified for this option must derive from a compatible `{SymbolNames.CliFxBindingValidatorClass}`."
) { }
)
{
private void Analyze(
SyntaxNodeAnalysisContext context,
PropertyDeclarationSyntax propertyDeclaration,
@@ -30,12 +28,10 @@ public class OptionMustHaveValidValidatorsAnalyzer : AnalyzerBase
{
var validatorValueType = validatorType
.GetBaseTypes()
.FirstOrDefault(
t =>
.FirstOrDefault(t =>
t.ConstructedFrom.DisplayNameMatches(SymbolNames.CliFxBindingValidatorClass)
)
?.TypeArguments
.FirstOrDefault();
?.TypeArguments.FirstOrDefault();
// Value passed to the validator must be assignable from the property type
var isCompatible =

View File

@@ -8,14 +8,12 @@ using Microsoft.CodeAnalysis.Diagnostics;
namespace CliFx.Analyzers;
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class ParameterMustBeInsideCommandAnalyzer : AnalyzerBase
{
public ParameterMustBeInsideCommandAnalyzer()
: base(
public class ParameterMustBeInsideCommandAnalyzer()
: AnalyzerBase(
"Parameters must be defined inside commands",
$"This parameter must be defined inside a class that implements `{SymbolNames.CliFxCommandInterface}`."
) { }
)
{
private void Analyze(
SyntaxNodeAnalysisContext context,
PropertyDeclarationSyntax propertyDeclaration,
@@ -31,10 +29,9 @@ public class ParameterMustBeInsideCommandAnalyzer : AnalyzerBase
if (!CommandParameterSymbol.IsParameterProperty(property))
return;
var isInsideCommand = property
.ContainingType
.AllInterfaces
.Any(i => i.DisplayNameMatches(SymbolNames.CliFxCommandInterface));
var isInsideCommand = property.ContainingType.AllInterfaces.Any(i =>
i.DisplayNameMatches(SymbolNames.CliFxCommandInterface)
);
if (!isInsideCommand)
{

View File

@@ -8,15 +8,13 @@ using Microsoft.CodeAnalysis.Diagnostics;
namespace CliFx.Analyzers;
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class ParameterMustBeLastIfNonRequiredAnalyzer : AnalyzerBase
{
public ParameterMustBeLastIfNonRequiredAnalyzer()
: base(
public class ParameterMustBeLastIfNonRequiredAnalyzer()
: AnalyzerBase(
"Parameters marked as non-required must be the last in order",
"This parameter is non-required so it must be the last in order (its order must be highest within the command). "
+ "Property bound to another non-required parameter: `{0}`."
) { }
)
{
private void Analyze(
SyntaxNodeAnalysisContext context,
PropertyDeclarationSyntax propertyDeclaration,
@@ -34,8 +32,7 @@ public class ParameterMustBeLastIfNonRequiredAnalyzer : AnalyzerBase
return;
var otherProperties = property
.ContainingType
.GetMembers()
.ContainingType.GetMembers()
.OfType<IPropertySymbol>()
.Where(m => !m.Equals(property))
.ToArray();

View File

@@ -8,15 +8,13 @@ using Microsoft.CodeAnalysis.Diagnostics;
namespace CliFx.Analyzers;
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class ParameterMustBeLastIfNonScalarAnalyzer : AnalyzerBase
{
public ParameterMustBeLastIfNonScalarAnalyzer()
: base(
public class ParameterMustBeLastIfNonScalarAnalyzer()
: AnalyzerBase(
"Parameters of non-scalar types must be the last in order",
"This parameter has a non-scalar type so it must be the last in order (its order must be highest within the command). "
+ "Property bound to another non-scalar parameter: `{0}`."
) { }
)
{
private void Analyze(
SyntaxNodeAnalysisContext context,
PropertyDeclarationSyntax propertyDeclaration,
@@ -34,8 +32,7 @@ public class ParameterMustBeLastIfNonScalarAnalyzer : AnalyzerBase
return;
var otherProperties = property
.ContainingType
.GetMembers()
.ContainingType.GetMembers()
.OfType<IPropertySymbol>()
.Where(m => !m.Equals(property))
.ToArray();

View File

@@ -7,14 +7,12 @@ using Microsoft.CodeAnalysis.Diagnostics;
namespace CliFx.Analyzers;
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class ParameterMustBeRequiredIfPropertyRequiredAnalyzer : AnalyzerBase
{
public ParameterMustBeRequiredIfPropertyRequiredAnalyzer()
: base(
public class ParameterMustBeRequiredIfPropertyRequiredAnalyzer()
: AnalyzerBase(
"Parameters bound to required properties cannot be marked as non-required",
"This parameter cannot be marked as non-required because it's bound to a required property."
) { }
)
{
private void Analyze(
SyntaxNodeAnalysisContext context,
PropertyDeclarationSyntax propertyDeclaration,

View File

@@ -8,15 +8,13 @@ using Microsoft.CodeAnalysis.Diagnostics;
namespace CliFx.Analyzers;
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class ParameterMustBeSingleIfNonRequiredAnalyzer : AnalyzerBase
{
public ParameterMustBeSingleIfNonRequiredAnalyzer()
: base(
public class ParameterMustBeSingleIfNonRequiredAnalyzer()
: AnalyzerBase(
"Parameters marked as non-required are limited to one per command",
"This parameter is non-required so it must be the only such parameter in the command. "
+ "Property bound to another non-required parameter: `{0}`."
) { }
)
{
private void Analyze(
SyntaxNodeAnalysisContext context,
PropertyDeclarationSyntax propertyDeclaration,
@@ -34,8 +32,7 @@ public class ParameterMustBeSingleIfNonRequiredAnalyzer : AnalyzerBase
return;
var otherProperties = property
.ContainingType
.GetMembers()
.ContainingType.GetMembers()
.OfType<IPropertySymbol>()
.Where(m => !m.Equals(property))
.ToArray();

View File

@@ -8,15 +8,13 @@ using Microsoft.CodeAnalysis.Diagnostics;
namespace CliFx.Analyzers;
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class ParameterMustBeSingleIfNonScalarAnalyzer : AnalyzerBase
{
public ParameterMustBeSingleIfNonScalarAnalyzer()
: base(
public class ParameterMustBeSingleIfNonScalarAnalyzer()
: AnalyzerBase(
"Parameters of non-scalar types are limited to one per command",
"This parameter has a non-scalar type so it must be the only such parameter in the command. "
+ "Property bound to another non-scalar parameter: `{0}`."
) { }
)
{
private void Analyze(
SyntaxNodeAnalysisContext context,
PropertyDeclarationSyntax propertyDeclaration,
@@ -34,8 +32,7 @@ public class ParameterMustBeSingleIfNonScalarAnalyzer : AnalyzerBase
return;
var otherProperties = property
.ContainingType
.GetMembers()
.ContainingType.GetMembers()
.OfType<IPropertySymbol>()
.Where(m => !m.Equals(property))
.ToArray();

View File

@@ -9,16 +9,14 @@ using Microsoft.CodeAnalysis.Diagnostics;
namespace CliFx.Analyzers;
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class ParameterMustHaveUniqueNameAnalyzer : AnalyzerBase
{
public ParameterMustHaveUniqueNameAnalyzer()
: base(
public class ParameterMustHaveUniqueNameAnalyzer()
: AnalyzerBase(
"Parameters must have unique names",
"This parameter's name must be unique within the command (comparison IS NOT case sensitive). "
+ "Specified name: `{0}`. "
+ "Property bound to another parameter with the same name: `{1}`."
) { }
)
{
private void Analyze(
SyntaxNodeAnalysisContext context,
PropertyDeclarationSyntax propertyDeclaration,
@@ -36,8 +34,7 @@ public class ParameterMustHaveUniqueNameAnalyzer : AnalyzerBase
return;
var otherProperties = property
.ContainingType
.GetMembers()
.ContainingType.GetMembers()
.OfType<IPropertySymbol>()
.Where(m => !m.Equals(property))
.ToArray();

View File

@@ -8,16 +8,14 @@ using Microsoft.CodeAnalysis.Diagnostics;
namespace CliFx.Analyzers;
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class ParameterMustHaveUniqueOrderAnalyzer : AnalyzerBase
{
public ParameterMustHaveUniqueOrderAnalyzer()
: base(
public class ParameterMustHaveUniqueOrderAnalyzer()
: AnalyzerBase(
"Parameters must have unique order",
"This parameter's order must be unique within the command. "
+ "Specified order: {0}. "
+ "Property bound to another parameter with the same order: `{1}`."
) { }
)
{
private void Analyze(
SyntaxNodeAnalysisContext context,
PropertyDeclarationSyntax propertyDeclaration,
@@ -32,8 +30,7 @@ public class ParameterMustHaveUniqueOrderAnalyzer : AnalyzerBase
return;
var otherProperties = property
.ContainingType
.GetMembers()
.ContainingType.GetMembers()
.OfType<IPropertySymbol>()
.Where(m => !m.Equals(property))
.ToArray();

View File

@@ -8,14 +8,12 @@ using Microsoft.CodeAnalysis.Diagnostics;
namespace CliFx.Analyzers;
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class ParameterMustHaveValidConverterAnalyzer : AnalyzerBase
{
public ParameterMustHaveValidConverterAnalyzer()
: base(
public class ParameterMustHaveValidConverterAnalyzer()
: AnalyzerBase(
$"Parameter converters must derive from `{SymbolNames.CliFxBindingConverterClass}`",
$"Converter specified for this parameter must derive from a compatible `{SymbolNames.CliFxBindingConverterClass}`."
) { }
)
{
private void Analyze(
SyntaxNodeAnalysisContext context,
PropertyDeclarationSyntax propertyDeclaration,
@@ -30,13 +28,11 @@ public class ParameterMustHaveValidConverterAnalyzer : AnalyzerBase
return;
var converterValueType = parameter
.ConverterType
.GetBaseTypes()
.FirstOrDefault(
t => t.ConstructedFrom.DisplayNameMatches(SymbolNames.CliFxBindingConverterClass)
.ConverterType.GetBaseTypes()
.FirstOrDefault(t =>
t.ConstructedFrom.DisplayNameMatches(SymbolNames.CliFxBindingConverterClass)
)
?.TypeArguments
.FirstOrDefault();
?.TypeArguments.FirstOrDefault();
// Value returned by the converter must be assignable to the property type
var isCompatible =
@@ -47,9 +43,10 @@ public class ParameterMustHaveValidConverterAnalyzer : AnalyzerBase
? context.Compilation.IsAssignable(converterValueType, property.Type)
// Non-scalar (assume we can handle all IEnumerable types for simplicity)
: property.Type.TryGetEnumerableUnderlyingType() is { } enumerableUnderlyingType
&& context
.Compilation
.IsAssignable(converterValueType, enumerableUnderlyingType)
&& context.Compilation.IsAssignable(
converterValueType,
enumerableUnderlyingType
)
);
if (!isCompatible)

View File

@@ -8,14 +8,12 @@ using Microsoft.CodeAnalysis.Diagnostics;
namespace CliFx.Analyzers;
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class ParameterMustHaveValidValidatorsAnalyzer : AnalyzerBase
{
public ParameterMustHaveValidValidatorsAnalyzer()
: base(
public class ParameterMustHaveValidValidatorsAnalyzer()
: AnalyzerBase(
$"Parameter validators must derive from `{SymbolNames.CliFxBindingValidatorClass}`",
$"Each validator specified for this parameter must derive from a compatible `{SymbolNames.CliFxBindingValidatorClass}`."
) { }
)
{
private void Analyze(
SyntaxNodeAnalysisContext context,
PropertyDeclarationSyntax propertyDeclaration,
@@ -30,12 +28,10 @@ public class ParameterMustHaveValidValidatorsAnalyzer : AnalyzerBase
{
var validatorValueType = validatorType
.GetBaseTypes()
.FirstOrDefault(
t =>
.FirstOrDefault(t =>
t.ConstructedFrom.DisplayNameMatches(SymbolNames.CliFxBindingValidatorClass)
)
?.TypeArguments
.FirstOrDefault();
?.TypeArguments.FirstOrDefault();
// Value passed to the validator must be assignable from the property type
var isCompatible =

View File

@@ -9,15 +9,13 @@ using Microsoft.CodeAnalysis.Diagnostics;
namespace CliFx.Analyzers;
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class SystemConsoleShouldBeAvoidedAnalyzer : AnalyzerBase
{
public SystemConsoleShouldBeAvoidedAnalyzer()
: base(
public class SystemConsoleShouldBeAvoidedAnalyzer()
: AnalyzerBase(
$"Avoid calling `System.Console` where `{SymbolNames.CliFxConsoleInterface}` is available",
$"Use the provided `{SymbolNames.CliFxConsoleInterface}` abstraction instead of `System.Console` to ensure that the command can be tested in isolation.",
DiagnosticSeverity.Warning
) { }
)
{
private MemberAccessExpressionSyntax? TryGetSystemConsoleMemberAccess(
SyntaxNodeAnalysisContext context,
SyntaxNode node
@@ -54,8 +52,7 @@ public class SystemConsoleShouldBeAvoidedAnalyzer : AnalyzerBase
// Check if IConsole is available in scope as an alternative to System.Console
var isConsoleInterfaceAvailable = context
.Node
.Ancestors()
.Node.Ancestors()
.OfType<MethodDeclarationSyntax>()
.SelectMany(m => m.ParameterList.Parameters)
.Select(p => p.Type)

View File

@@ -30,9 +30,8 @@ internal static class RoslynExtensions
}
public static ITypeSymbol? TryGetEnumerableUnderlyingType(this ITypeSymbol type) =>
type.AllInterfaces
.FirstOrDefault(
i =>
type
.AllInterfaces.FirstOrDefault(i =>
i.ConstructedFrom.SpecialType
== SpecialType.System_Collections_Generic_IEnumerable_T
)
@@ -44,8 +43,7 @@ internal static class RoslynExtensions
property
// Can't rely on the RequiredMemberAttribute because it's generated by the compiler, not added by the user,
// so we have to check for the presence of the `required` modifier in the syntax tree instead.
.DeclaringSyntaxReferences
.Select(r => r.GetSyntax())
.DeclaringSyntaxReferences.Select(r => r.GetSyntax())
.OfType<PropertyDeclarationSyntax>()
.SelectMany(p => p.Modifiers)
.Any(m => m.IsKind((SyntaxKind)8447));

View File

@@ -8,9 +8,9 @@ public partial class Benchmarks
public class CoconaCommand
{
public void Execute(
[Option("str", new[] { 's' })] string? strOption,
[Option("int", new[] { 'i' })] int intOption,
[Option("bool", new[] { 'b' })] bool boolOption
[Option("str", ['s'])] string? strOption,
[Option("int", ['i'])] int intOption,
[Option("bool", ['b'])] bool boolOption
) { }
}

View File

@@ -1,5 +1,4 @@
using System.CommandLine;
using System.CommandLine.Invocation;
using System.Threading.Tasks;
using BenchmarkDotNet.Attributes;
@@ -9,20 +8,20 @@ public partial class Benchmarks
{
public class SystemCommandLineCommand
{
public static int ExecuteHandler(string s, int i, bool b) => 0;
public static void ExecuteHandler(string s, int i, bool b) { }
public Task<int> ExecuteAsync(string[] args)
{
var command = new RootCommand
{
new Option(new[] { "--str", "-s" }) { Argument = new Argument<string?>() },
new Option(new[] { "--int", "-i" }) { Argument = new Argument<int>() },
new Option(new[] { "--bool", "-b" }) { Argument = new Argument<bool>() }
};
var stringOption = new Option<string>(["--str", "-s"]);
var intOption = new Option<int>(["--int", "-i"]);
var boolOption = new Option<bool>(["--bool", "-b"]);
command.Handler = CommandHandler.Create(
typeof(SystemCommandLineCommand).GetMethod(nameof(ExecuteHandler))!
);
var command = new RootCommand();
command.AddOption(stringOption);
command.AddOption(intOption);
command.AddOption(boolOption);
command.SetHandler(ExecuteHandler, stringOption, intOption, boolOption);
return command.InvokeAsync(args);
}

View File

@@ -9,7 +9,7 @@ namespace CliFx.Benchmarks;
[Orderer(SummaryOrderPolicy.FastestToSlowest)]
public partial class Benchmarks
{
private static readonly string[] Arguments = { "--str", "hello world", "-i", "13", "-b" };
private static readonly string[] Arguments = ["--str", "hello world", "-i", "13", "-b"];
public static void Main() =>
BenchmarkRunner.Run<Benchmarks>(

View File

@@ -1,19 +1,20 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<TargetFramework>net9.0</TargetFramework>
<NuGetAudit>false</NuGetAudit>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="BenchmarkDotNet" Version="0.13.10" />
<PackageReference Include="BenchmarkDotNet" Version="0.15.4" />
<PackageReference Include="clipr" Version="1.6.1" />
<PackageReference Include="Cocona" Version="2.2.0" />
<PackageReference Include="CommandLineParser" Version="2.9.1" />
<PackageReference Include="CSharpier.MsBuild" Version="0.26.1" PrivateAssets="all" />
<PackageReference Include="McMaster.Extensions.CommandLineUtils" Version="4.1.0" />
<PackageReference Include="CSharpier.MsBuild" Version="0.30.6" PrivateAssets="all" />
<PackageReference Include="McMaster.Extensions.CommandLineUtils" Version="4.1.1" />
<PackageReference Include="PowerArgs" Version="4.0.3" />
<PackageReference Include="System.CommandLine" Version="2.0.0-beta1.20574.7" />
<PackageReference Include="System.CommandLine" Version="2.0.0-rc.1.25451.107" />
</ItemGroup>
<ItemGroup>

View File

@@ -1,14 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<TargetFramework>net9.0</TargetFramework>
<ApplicationIcon>../favicon.ico</ApplicationIcon>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="CSharpier.MsBuild" Version="0.26.1" PrivateAssets="all" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0" />
<PackageReference Include="CSharpier.MsBuild" Version="0.30.6" PrivateAssets="all" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="9.0.9" />
</ItemGroup>
<ItemGroup>

View File

@@ -9,10 +9,8 @@ using CliFx.Infrastructure;
namespace CliFx.Demo.Commands;
[Command("book add", Description = "Adds a book to the library.")]
public partial class BookAddCommand : ICommand
public class BookAddCommand(LibraryProvider libraryProvider) : ICommand
{
private readonly LibraryProvider _libraryProvider;
[CommandParameter(0, Name = "title", Description = "Book title.")]
public required string Title { get; init; }
@@ -20,52 +18,38 @@ public partial class BookAddCommand : ICommand
public required string Author { get; init; }
[CommandOption("published", 'p', Description = "Book publish date.")]
public DateTimeOffset Published { get; init; } = CreateRandomDate();
public DateTimeOffset Published { get; init; } =
new(
Random.Shared.Next(1800, 2020),
Random.Shared.Next(1, 12),
Random.Shared.Next(1, 28),
Random.Shared.Next(1, 23),
Random.Shared.Next(1, 59),
Random.Shared.Next(1, 59),
TimeSpan.Zero
);
[CommandOption("isbn", 'n', Description = "Book ISBN.")]
public Isbn Isbn { get; init; } = CreateRandomIsbn();
public BookAddCommand(LibraryProvider libraryProvider)
{
_libraryProvider = libraryProvider;
}
public Isbn Isbn { get; init; } =
new(
Random.Shared.Next(0, 999),
Random.Shared.Next(0, 99),
Random.Shared.Next(0, 99999),
Random.Shared.Next(0, 99),
Random.Shared.Next(0, 9)
);
public ValueTask ExecuteAsync(IConsole console)
{
if (_libraryProvider.TryGetBook(Title) is not null)
throw new CommandException("Book already exists.", 10);
if (libraryProvider.TryGetBook(Title) is not null)
throw new CommandException($"Book '{Title}' already exists.", 10);
var book = new Book(Title, Author, Published, Isbn);
_libraryProvider.AddBook(book);
libraryProvider.AddBook(book);
console.Output.WriteLine("Book added.");
console.Output.WriteBook(book);
console.WriteLine($"Book '{Title}' added.");
console.WriteBook(book);
return default;
}
}
public partial class BookAddCommand
{
private static readonly Random Random = new();
private static DateTimeOffset CreateRandomDate() =>
new(
Random.Next(1800, 2020),
Random.Next(1, 12),
Random.Next(1, 28),
Random.Next(1, 23),
Random.Next(1, 59),
Random.Next(1, 59),
TimeSpan.Zero
);
private static Isbn CreateRandomIsbn() =>
new(
Random.Next(0, 999),
Random.Next(0, 99),
Random.Next(0, 99999),
Random.Next(0, 99),
Random.Next(0, 9)
);
}

View File

@@ -8,26 +8,19 @@ using CliFx.Infrastructure;
namespace CliFx.Demo.Commands;
[Command("book", Description = "Retrieves a book from the library.")]
public class BookCommand : ICommand
public class BookCommand(LibraryProvider libraryProvider) : ICommand
{
private readonly LibraryProvider _libraryProvider;
[CommandParameter(0, Name = "title", Description = "Title of the book to retrieve.")]
public required string Title { get; init; }
public BookCommand(LibraryProvider libraryProvider)
{
_libraryProvider = libraryProvider;
}
public ValueTask ExecuteAsync(IConsole console)
{
var book = _libraryProvider.TryGetBook(Title);
var book = libraryProvider.TryGetBook(Title);
if (book is null)
throw new CommandException("Book not found.", 10);
throw new CommandException($"Book '{Title}' not found.", 10);
console.Output.WriteBook(book);
console.WriteBook(book);
return default;
}

View File

@@ -7,28 +7,21 @@ using CliFx.Infrastructure;
namespace CliFx.Demo.Commands;
[Command("book list", Description = "Lists all books in the library.")]
public class BookListCommand : ICommand
public class BookListCommand(LibraryProvider libraryProvider) : ICommand
{
private readonly LibraryProvider _libraryProvider;
public BookListCommand(LibraryProvider libraryProvider)
{
_libraryProvider = libraryProvider;
}
public ValueTask ExecuteAsync(IConsole console)
{
var library = _libraryProvider.GetLibrary();
var library = libraryProvider.GetLibrary();
for (var i = 0; i < library.Books.Count; i++)
{
// Add margin
if (i != 0)
console.Output.WriteLine();
console.WriteLine();
// Render book
var book = library.Books[i];
console.Output.WriteBook(book);
console.WriteBook(book);
}
return default;

View File

@@ -7,28 +7,21 @@ using CliFx.Infrastructure;
namespace CliFx.Demo.Commands;
[Command("book remove", Description = "Removes a book from the library.")]
public class BookRemoveCommand : ICommand
public class BookRemoveCommand(LibraryProvider libraryProvider) : ICommand
{
private readonly LibraryProvider _libraryProvider;
[CommandParameter(0, Name = "title", Description = "Title of the book to remove.")]
public required string Title { get; init; }
public BookRemoveCommand(LibraryProvider libraryProvider)
{
_libraryProvider = libraryProvider;
}
public ValueTask ExecuteAsync(IConsole console)
{
var book = _libraryProvider.TryGetBook(Title);
var book = libraryProvider.TryGetBook(Title);
if (book is null)
throw new CommandException("Book not found.", 10);
throw new CommandException($"Book '{Title}' not found.", 10);
_libraryProvider.RemoveBook(book);
libraryProvider.RemoveBook(book);
console.Output.WriteLine($"Book {Title} removed.");
console.WriteLine($"Book '{Title}' removed.");
return default;
}

View File

@@ -33,4 +33,7 @@ internal static class ConsoleExtensions
using (writer.Console.WithForegroundColor(ConsoleColor.White))
writer.WriteLine(book.Isbn);
}
public static void WriteBook(this IConsole console, Book book) =>
console.Output.WriteBook(book);
}

View File

@@ -2,12 +2,12 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<TargetFramework>net9.0</TargetFramework>
<ApplicationIcon>../favicon.ico</ApplicationIcon>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="CSharpier.MsBuild" Version="0.26.1" PrivateAssets="all" />
<PackageReference Include="CSharpier.MsBuild" Version="0.30.6" PrivateAssets="all" />
</ItemGroup>
<ItemGroup>

View File

@@ -12,15 +12,15 @@ public class CancellationTestCommand : ICommand
{
try
{
console.Output.WriteLine("Started.");
console.WriteLine("Started.");
await Task.Delay(TimeSpan.FromSeconds(3), console.RegisterCancellationHandler());
console.Output.WriteLine("Completed.");
console.WriteLine("Completed.");
}
catch (OperationCanceledException)
{
console.Output.WriteLine("Cancelled.");
console.WriteLine("Cancelled.");
throw;
}
}

View File

@@ -12,8 +12,7 @@ public class EnvironmentTestCommand : ICommand
public ValueTask ExecuteAsync(IConsole console)
{
console.Output.WriteLine($"Hello {GreetingTarget}!");
console.WriteLine($"Hello {GreetingTarget}!");
return default;
}
}

View File

@@ -8,11 +8,8 @@ using Xunit.Abstractions;
namespace CliFx.Tests;
public class ApplicationSpecs : SpecsBase
public class ApplicationSpecs(ITestOutputHelper testOutput) : SpecsBase(testOutput)
{
public ApplicationSpecs(ITestOutputHelper testOutput)
: base(testOutput) { }
[Fact]
public async Task I_can_create_an_application_with_the_default_configuration()
{
@@ -35,8 +32,8 @@ public class ApplicationSpecs : SpecsBase
var app = new CliApplicationBuilder()
.AddCommand<NoOpCommand>()
.AddCommandsFrom(typeof(NoOpCommand).Assembly)
.AddCommands(new[] { typeof(NoOpCommand) })
.AddCommandsFrom(new[] { typeof(NoOpCommand).Assembly })
.AddCommands([typeof(NoOpCommand)])
.AddCommandsFrom([typeof(NoOpCommand).Assembly])
.AddCommandsFromThisAssembly()
.AllowDebugMode()
.AllowPreviewMode()

View File

@@ -12,11 +12,8 @@ using Xunit.Abstractions;
namespace CliFx.Tests;
public class CancellationSpecs : SpecsBase
public class CancellationSpecs(ITestOutputHelper testOutput) : SpecsBase(testOutput)
{
public CancellationSpecs(ITestOutputHelper testOutput)
: base(testOutput) { }
[Fact(Timeout = 15000)]
public async Task I_can_configure_the_command_to_listen_to_the_interrupt_signal()
{
@@ -69,18 +66,18 @@ public class CancellationSpecs : SpecsBase
{
try
{
console.Output.WriteLine("Started.");
console.WriteLine("Started.");
await Task.Delay(
TimeSpan.FromSeconds(3),
console.RegisterCancellationHandler()
);
console.Output.WriteLine("Completed.");
console.WriteLine("Completed.");
}
catch (OperationCanceledException)
{
console.Output.WriteLine("Cancelled.");
console.WriteLine("Cancelled.");
throw;
}
}

View File

@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<TargetFramework>net9.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
@@ -9,18 +9,18 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Basic.Reference.Assemblies.Net70" Version="1.4.5" />
<PackageReference Include="CliWrap" Version="3.6.4" />
<PackageReference Include="coverlet.collector" Version="6.0.0" PrivateAssets="all" />
<PackageReference Include="CSharpier.MsBuild" Version="0.26.1" PrivateAssets="all" />
<PackageReference Include="FluentAssertions" Version="6.12.0" />
<PackageReference Include="GitHubActionsTestLogger" Version="2.3.3" PrivateAssets="all" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.7.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0" />
<PackageReference Include="PolyShim" Version="1.8.0" PrivateAssets="all" />
<PackageReference Include="xunit" Version="2.6.1" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.5.3" PrivateAssets="all" />
<PackageReference Include="Basic.Reference.Assemblies.Net80" Version="1.8.3" />
<PackageReference Include="CliWrap" Version="3.9.0" />
<PackageReference Include="coverlet.collector" Version="6.0.4" PrivateAssets="all" />
<PackageReference Include="CSharpier.MsBuild" Version="0.30.6" PrivateAssets="all" />
<PackageReference Include="FluentAssertions" Version="8.7.0" />
<PackageReference Include="GitHubActionsTestLogger" Version="2.4.1" PrivateAssets="all" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.11.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="9.0.9" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
<PackageReference Include="PolyShim" Version="1.15.0" PrivateAssets="all" />
<PackageReference Include="xunit" Version="2.9.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.5" PrivateAssets="all" />
</ItemGroup>
<ItemGroup>

View File

@@ -14,11 +14,8 @@ using Xunit.Abstractions;
namespace CliFx.Tests;
public class ConsoleSpecs : SpecsBase
public class ConsoleSpecs(ITestOutputHelper testOutput) : SpecsBase(testOutput)
{
public ConsoleSpecs(ITestOutputHelper testOutput)
: base(testOutput) { }
[Fact(Timeout = 15000)]
public async Task I_can_run_the_application_with_the_default_console_implementation_to_interact_with_the_system_console()
{
@@ -173,9 +170,9 @@ public class ConsoleSpecs : SpecsBase
{
public ValueTask ExecuteAsync(IConsole console)
{
console.Output.WriteLine(console.ReadKey().Key);
console.Output.WriteLine(console.ReadKey().Key);
console.Output.WriteLine(console.ReadKey().Key);
console.WriteLine(console.ReadKey().Key);
console.WriteLine(console.ReadKey().Key);
console.WriteLine(console.ReadKey().Key);
return default;
}

View File

@@ -8,11 +8,8 @@ using Xunit.Abstractions;
namespace CliFx.Tests;
public class ConversionSpecs : SpecsBase
public class ConversionSpecs(ITestOutputHelper testOutput) : SpecsBase(testOutput)
{
public ConversionSpecs(ITestOutputHelper testOutput)
: base(testOutput) { }
[Fact]
public async Task I_can_bind_a_parameter_or_an_option_to_a_string_property()
{
@@ -28,7 +25,7 @@ public class ConversionSpecs : SpecsBase
public ValueTask ExecuteAsync(IConsole console)
{
console.Output.WriteLine(Foo);
console.WriteLine(Foo);
return default;
}
}
@@ -41,10 +38,7 @@ public class ConversionSpecs : SpecsBase
.Build();
// Act
var exitCode = await application.RunAsync(
new[] { "-f", "xyz" },
new Dictionary<string, string>()
);
var exitCode = await application.RunAsync(["-f", "xyz"], new Dictionary<string, string>());
// Assert
exitCode.Should().Be(0);
@@ -68,7 +62,7 @@ public class ConversionSpecs : SpecsBase
public ValueTask ExecuteAsync(IConsole console)
{
console.Output.WriteLine(Foo);
console.WriteLine(Foo);
return default;
}
}
@@ -81,10 +75,7 @@ public class ConversionSpecs : SpecsBase
.Build();
// Act
var exitCode = await application.RunAsync(
new[] { "-f", "xyz" },
new Dictionary<string, string>()
);
var exitCode = await application.RunAsync(["-f", "xyz"], new Dictionary<string, string>());
// Assert
exitCode.Should().Be(0);
@@ -114,9 +105,9 @@ public class ConversionSpecs : SpecsBase
public ValueTask ExecuteAsync(IConsole console)
{
console.Output.WriteLine("Foo = " + Foo);
console.Output.WriteLine("Bar = " + Bar);
console.Output.WriteLine("Baz = " + Baz);
console.WriteLine("Foo = " + Foo);
console.WriteLine("Bar = " + Bar);
console.WriteLine("Baz = " + Baz);
return default;
}
@@ -131,7 +122,7 @@ public class ConversionSpecs : SpecsBase
// Act
var exitCode = await application.RunAsync(
new[] { "-f", "true", "-b", "false", "-c" },
["-f", "true", "-b", "false", "-c"],
new Dictionary<string, string>()
);
@@ -157,7 +148,7 @@ public class ConversionSpecs : SpecsBase
public ValueTask ExecuteAsync(IConsole console)
{
console.Output.WriteLine(Foo);
console.WriteLine(Foo);
return default;
}
}
@@ -170,10 +161,7 @@ public class ConversionSpecs : SpecsBase
.Build();
// Act
var exitCode = await application.RunAsync(
new[] { "-f", "32" },
new Dictionary<string, string>()
);
var exitCode = await application.RunAsync(["-f", "32"], new Dictionary<string, string>());
// Assert
exitCode.Should().Be(0);
@@ -197,7 +185,7 @@ public class ConversionSpecs : SpecsBase
public ValueTask ExecuteAsync(IConsole console)
{
console.Output.WriteLine(Foo.ToString(CultureInfo.InvariantCulture));
console.WriteLine(Foo.ToString(CultureInfo.InvariantCulture));
return default;
}
}
@@ -211,7 +199,7 @@ public class ConversionSpecs : SpecsBase
// Act
var exitCode = await application.RunAsync(
new[] { "-f", "32.14" },
["-f", "32.14"],
new Dictionary<string, string>()
);
@@ -237,7 +225,7 @@ public class ConversionSpecs : SpecsBase
public ValueTask ExecuteAsync(IConsole console)
{
console.Output.WriteLine(Foo.ToString("u", CultureInfo.InvariantCulture));
console.WriteLine(Foo.ToString("u", CultureInfo.InvariantCulture));
return default;
}
}
@@ -251,7 +239,7 @@ public class ConversionSpecs : SpecsBase
// Act
var exitCode = await application.RunAsync(
new[] { "-f", "1995-04-28Z" },
["-f", "1995-04-28Z"],
new Dictionary<string, string>()
);
@@ -277,7 +265,7 @@ public class ConversionSpecs : SpecsBase
public ValueTask ExecuteAsync(IConsole console)
{
console.Output.WriteLine(Foo.ToString(null, CultureInfo.InvariantCulture));
console.WriteLine(Foo.ToString(null, CultureInfo.InvariantCulture));
return default;
}
}
@@ -291,7 +279,7 @@ public class ConversionSpecs : SpecsBase
// Act
var exitCode = await application.RunAsync(
new[] { "-f", "12:34:56" },
["-f", "12:34:56"],
new Dictionary<string, string>()
);
@@ -319,7 +307,7 @@ public class ConversionSpecs : SpecsBase
public ValueTask ExecuteAsync(IConsole console)
{
console.Output.WriteLine((int) Foo);
console.WriteLine((int) Foo);
return default;
}
}
@@ -332,10 +320,7 @@ public class ConversionSpecs : SpecsBase
.Build();
// Act
var exitCode = await application.RunAsync(
new[] { "-f", "two" },
new Dictionary<string, string>()
);
var exitCode = await application.RunAsync(["-f", "two"], new Dictionary<string, string>());
// Assert
exitCode.Should().Be(0);
@@ -362,8 +347,8 @@ public class ConversionSpecs : SpecsBase
public ValueTask ExecuteAsync(IConsole console)
{
console.Output.WriteLine("Foo = " + Foo);
console.Output.WriteLine("Bar = " + Bar);
console.WriteLine("Foo = " + Foo);
console.WriteLine("Bar = " + Bar);
return default;
}
@@ -377,10 +362,7 @@ public class ConversionSpecs : SpecsBase
.Build();
// Act
var exitCode = await application.RunAsync(
new[] { "-b", "123" },
new Dictionary<string, string>()
);
var exitCode = await application.RunAsync(["-b", "123"], new Dictionary<string, string>());
// Assert
exitCode.Should().Be(0);
@@ -409,8 +391,8 @@ public class ConversionSpecs : SpecsBase
public ValueTask ExecuteAsync(IConsole console)
{
console.Output.WriteLine("Foo = " + (int?) Foo);
console.Output.WriteLine("Bar = " + (int?) Bar);
console.WriteLine("Foo = " + (int?) Foo);
console.WriteLine("Bar = " + (int?) Bar);
return default;
}
@@ -424,10 +406,7 @@ public class ConversionSpecs : SpecsBase
.Build();
// Act
var exitCode = await application.RunAsync(
new[] { "-b", "two" },
new Dictionary<string, string>()
);
var exitCode = await application.RunAsync(["-b", "two"], new Dictionary<string, string>());
// Assert
exitCode.Should().Be(0);
@@ -458,7 +437,7 @@ public class ConversionSpecs : SpecsBase
public ValueTask ExecuteAsync(IConsole console)
{
console.Output.WriteLine(Foo.Value);
console.WriteLine(Foo.Value);
return default;
}
}
@@ -471,10 +450,7 @@ public class ConversionSpecs : SpecsBase
.Build();
// Act
var exitCode = await application.RunAsync(
new[] { "-f", "xyz" },
new Dictionary<string, string>()
);
var exitCode = await application.RunAsync(["-f", "xyz"], new Dictionary<string, string>());
// Assert
exitCode.Should().Be(0);
@@ -521,8 +497,8 @@ public class ConversionSpecs : SpecsBase
public ValueTask ExecuteAsync(IConsole console)
{
console.Output.WriteLine("Foo = " + Foo.Value);
console.Output.WriteLine("Bar = " + Bar.Value);
console.WriteLine("Foo = " + Foo.Value);
console.WriteLine("Bar = " + Bar.Value);
return default;
}
@@ -537,7 +513,7 @@ public class ConversionSpecs : SpecsBase
// Act
var exitCode = await application.RunAsync(
new[] { "-f", "hello", "-b", "world" },
["-f", "hello", "-b", "world"],
new Dictionary<string, string>()
);
@@ -569,7 +545,7 @@ public class ConversionSpecs : SpecsBase
public ValueTask ExecuteAsync(IConsole console)
{
console.Output.WriteLine(Foo);
console.WriteLine(Foo);
return default;
}
}
@@ -583,7 +559,7 @@ public class ConversionSpecs : SpecsBase
// Act
var exitCode = await application.RunAsync(
new[] { "-f", "hello world" },
["-f", "hello world"],
new Dictionary<string, string>()
);
@@ -610,7 +586,7 @@ public class ConversionSpecs : SpecsBase
public ValueTask ExecuteAsync(IConsole console)
{
foreach (var i in Foo)
console.Output.WriteLine(i);
console.WriteLine(i);
return default;
}
@@ -625,7 +601,7 @@ public class ConversionSpecs : SpecsBase
// Act
var exitCode = await application.RunAsync(
new[] { "-f", "one", "two", "three" },
["-f", "one", "two", "three"],
new Dictionary<string, string>()
);
@@ -652,7 +628,7 @@ public class ConversionSpecs : SpecsBase
public ValueTask ExecuteAsync(IConsole console)
{
foreach (var i in Foo)
console.Output.WriteLine(i);
console.WriteLine(i);
return default;
}
@@ -667,7 +643,7 @@ public class ConversionSpecs : SpecsBase
// Act
var exitCode = await application.RunAsync(
new[] { "-f", "one", "two", "three" },
["-f", "one", "two", "three"],
new Dictionary<string, string>()
);
@@ -694,7 +670,7 @@ public class ConversionSpecs : SpecsBase
public ValueTask ExecuteAsync(IConsole console)
{
foreach (var i in Foo)
console.Output.WriteLine(i);
console.WriteLine(i);
return default;
}
@@ -709,7 +685,7 @@ public class ConversionSpecs : SpecsBase
// Act
var exitCode = await application.RunAsync(
new[] { "-f", "one", "two", "three" },
["-f", "one", "two", "three"],
new Dictionary<string, string>()
);
@@ -736,7 +712,7 @@ public class ConversionSpecs : SpecsBase
public ValueTask ExecuteAsync(IConsole console)
{
foreach (var i in Foo)
console.Output.WriteLine(i);
console.WriteLine(i);
return default;
}
@@ -751,7 +727,7 @@ public class ConversionSpecs : SpecsBase
// Act
var exitCode = await application.RunAsync(
new[] { "-f", "1", "13", "27" },
["-f", "1", "13", "27"],
new Dictionary<string, string>()
);
@@ -790,10 +766,7 @@ public class ConversionSpecs : SpecsBase
.Build();
// Act
var exitCode = await application.RunAsync(
new[] { "-f", "xyz" },
new Dictionary<string, string>()
);
var exitCode = await application.RunAsync(["-f", "xyz"], new Dictionary<string, string>());
// Assert
exitCode.Should().NotBe(0);
@@ -834,7 +807,7 @@ public class ConversionSpecs : SpecsBase
// Act
var exitCode = await application.RunAsync(
new[] { "-f", "one", "two" },
["-f", "one", "two"],
new Dictionary<string, string>()
);
@@ -870,7 +843,7 @@ public class ConversionSpecs : SpecsBase
// Act
var exitCode = await application.RunAsync(
new[] { "-f", "12.34" },
["-f", "12.34"],
new Dictionary<string, string>()
);
@@ -901,7 +874,7 @@ public class ConversionSpecs : SpecsBase
[Command]
public class Command : ICommand
{
[CommandOption('f', Validators = new[] {typeof(ValidatorA), typeof(ValidatorB)})]
[CommandOption('f', Validators = [typeof(ValidatorA), typeof(ValidatorB)])]
public int Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default;
@@ -915,10 +888,7 @@ public class ConversionSpecs : SpecsBase
.Build();
// Act
var exitCode = await application.RunAsync(
new[] { "-f", "12" },
new Dictionary<string, string>()
);
var exitCode = await application.RunAsync(["-f", "12"], new Dictionary<string, string>());
// Assert
exitCode.Should().NotBe(0);
@@ -960,10 +930,7 @@ public class ConversionSpecs : SpecsBase
.Build();
// Act
var exitCode = await application.RunAsync(
new[] { "-f", "bar" },
new Dictionary<string, string>()
);
var exitCode = await application.RunAsync(["-f", "bar"], new Dictionary<string, string>());
// Assert
exitCode.Should().NotBe(0);

View File

@@ -11,11 +11,8 @@ using Xunit.Abstractions;
namespace CliFx.Tests;
public class DirectivesSpecs : SpecsBase
public class DirectivesSpecs(ITestOutputHelper testOutput) : SpecsBase(testOutput)
{
public DirectivesSpecs(ITestOutputHelper testOutput)
: base(testOutput) { }
[Fact(Timeout = 15000)]
public async Task I_can_use_the_debug_directive_to_make_the_application_wait_for_the_debugger_to_attach()
{
@@ -66,7 +63,7 @@ public class DirectivesSpecs : SpecsBase
// Act
var exitCode = await application.RunAsync(
new[] { "[preview]", "cmd", "param", "-abc", "--option", "foo" },
["[preview]", "cmd", "param", "-abc", "--option", "foo"],
new Dictionary<string, string> { ["ENV_QOP"] = "hello", ["ENV_KIL"] = "world" }
);

View File

@@ -12,11 +12,8 @@ using Xunit.Abstractions;
namespace CliFx.Tests;
public class EnvironmentSpecs : SpecsBase
public class EnvironmentSpecs(ITestOutputHelper testOutput) : SpecsBase(testOutput)
{
public EnvironmentSpecs(ITestOutputHelper testOutput)
: base(testOutput) { }
[Fact]
public async Task I_can_configure_an_option_to_fall_back_to_an_environment_variable_if_the_user_does_not_provide_the_corresponding_argument()
{
@@ -35,8 +32,8 @@ public class EnvironmentSpecs : SpecsBase
public ValueTask ExecuteAsync(IConsole console)
{
console.Output.WriteLine(Foo);
console.Output.WriteLine(Bar);
console.WriteLine(Foo);
console.WriteLine(Bar);
return default;
}
@@ -51,7 +48,7 @@ public class EnvironmentSpecs : SpecsBase
// Act
var exitCode = await application.RunAsync(
new[] { "--foo", "42" },
["--foo", "42"],
new Dictionary<string, string> { ["ENV_FOO"] = "100", ["ENV_BAR"] = "200" }
);
@@ -78,7 +75,7 @@ public class EnvironmentSpecs : SpecsBase
public ValueTask ExecuteAsync(IConsole console)
{
foreach (var i in Foo)
console.Output.WriteLine(i);
console.WriteLine(i);
return default;
}
@@ -119,7 +116,7 @@ public class EnvironmentSpecs : SpecsBase
public ValueTask ExecuteAsync(IConsole console)
{
console.Output.WriteLine(Foo);
console.WriteLine(Foo);
return default;
}
}

View File

@@ -9,11 +9,8 @@ using Xunit.Abstractions;
namespace CliFx.Tests;
public class ErrorReportingSpecs : SpecsBase
public class ErrorReportingSpecs(ITestOutputHelper testOutput) : SpecsBase(testOutput)
{
public ErrorReportingSpecs(ITestOutputHelper testOutput)
: base(testOutput) { }
[Fact]
public async Task I_can_throw_an_exception_in_a_command_to_report_an_error_with_a_stacktrace()
{

View File

@@ -9,11 +9,8 @@ using Xunit.Abstractions;
namespace CliFx.Tests;
public class HelpTextSpecs : SpecsBase
public class HelpTextSpecs(ITestOutputHelper testOutput) : SpecsBase(testOutput)
{
public HelpTextSpecs(ITestOutputHelper testOutput)
: base(testOutput) { }
[Fact]
public async Task I_can_request_the_help_text_by_running_the_application_without_arguments_if_the_default_command_is_not_defined()
{
@@ -37,7 +34,7 @@ public class HelpTextSpecs : SpecsBase
}
[Fact]
public async Task I_can_request_the_help_text_by_running_the_application_with_the_help_option()
public async Task I_can_request_the_help_text_by_running_the_application_with_the_implicit_help_option()
{
// Arrange
var commandType = DynamicCommandBuilder.Compile(
@@ -58,10 +55,7 @@ public class HelpTextSpecs : SpecsBase
.Build();
// Act
var exitCode = await application.RunAsync(
new[] { "--help" },
new Dictionary<string, string>()
);
var exitCode = await application.RunAsync(["--help"], new Dictionary<string, string>());
// Assert
exitCode.Should().Be(0);
@@ -71,7 +65,7 @@ public class HelpTextSpecs : SpecsBase
}
[Fact]
public async Task I_can_request_the_help_text_by_running_the_application_with_the_help_option_even_if_the_default_command_is_not_defined()
public async Task I_can_request_the_help_text_by_running_the_application_with_the_implicit_help_option_even_if_the_default_command_is_not_defined()
{
// Arrange
var commandTypes = DynamicCommandBuilder.CompileMany(
@@ -98,10 +92,7 @@ public class HelpTextSpecs : SpecsBase
.Build();
// Act
var exitCode = await application.RunAsync(
new[] { "--help" },
new Dictionary<string, string>()
);
var exitCode = await application.RunAsync(["--help"], new Dictionary<string, string>());
// Assert
exitCode.Should().Be(0);
@@ -111,7 +102,7 @@ public class HelpTextSpecs : SpecsBase
}
[Fact]
public async Task I_can_request_the_help_text_for_a_specific_command_by_running_the_application_and_specifying_its_name_with_the_help_option()
public async Task I_can_request_the_help_text_for_a_specific_command_by_running_the_application_and_specifying_its_name_with_the_implicit_help_option()
{
// Arrange
var commandTypes = DynamicCommandBuilder.CompileMany(
@@ -144,7 +135,7 @@ public class HelpTextSpecs : SpecsBase
// Act
var exitCode = await application.RunAsync(
new[] { "cmd", "--help" },
["cmd", "--help"],
new Dictionary<string, string>()
);
@@ -156,7 +147,7 @@ public class HelpTextSpecs : SpecsBase
}
[Fact]
public async Task I_can_request_the_help_text_for_a_specific_nested_command_by_running_the_application_and_specifying_its_name_with_the_help_option()
public async Task I_can_request_the_help_text_for_a_specific_nested_command_by_running_the_application_and_specifying_its_name_with_the_implicit_help_option()
{
// Arrange
var commandTypes = DynamicCommandBuilder.CompileMany(
@@ -189,7 +180,7 @@ public class HelpTextSpecs : SpecsBase
// Act
var exitCode = await application.RunAsync(
new[] { "cmd", "sub", "--help" },
["cmd", "sub", "--help"],
new Dictionary<string, string>()
);
@@ -212,7 +203,7 @@ public class HelpTextSpecs : SpecsBase
// Act
var exitCode = await application.RunAsync(
new[] { "invalid-command", "--invalid-option" },
["invalid-command", "--invalid-option"],
new Dictionary<string, string>()
);
@@ -238,10 +229,7 @@ public class HelpTextSpecs : SpecsBase
.Build();
// Act
var exitCode = await application.RunAsync(
new[] { "--help" },
new Dictionary<string, string>()
);
var exitCode = await application.RunAsync(["--help"], new Dictionary<string, string>());
// Assert
exitCode.Should().Be(0);
@@ -271,10 +259,7 @@ public class HelpTextSpecs : SpecsBase
.Build();
// Act
var exitCode = await application.RunAsync(
new[] { "--help" },
new Dictionary<string, string>()
);
var exitCode = await application.RunAsync(["--help"], new Dictionary<string, string>());
// Assert
exitCode.Should().Be(0);
@@ -310,10 +295,7 @@ public class HelpTextSpecs : SpecsBase
.Build();
// Act
var exitCode = await application.RunAsync(
new[] { "--help" },
new Dictionary<string, string>()
);
var exitCode = await application.RunAsync(["--help"], new Dictionary<string, string>());
// Assert
exitCode.Should().Be(0);
@@ -352,10 +334,7 @@ public class HelpTextSpecs : SpecsBase
.Build();
// Act
var exitCode = await application.RunAsync(
new[] { "--help" },
new Dictionary<string, string>()
);
var exitCode = await application.RunAsync(["--help"], new Dictionary<string, string>());
// Assert
exitCode.Should().Be(0);
@@ -401,10 +380,7 @@ public class HelpTextSpecs : SpecsBase
.Build();
// Act
var exitCode = await application.RunAsync(
new[] { "--help" },
new Dictionary<string, string>()
);
var exitCode = await application.RunAsync(["--help"], new Dictionary<string, string>());
// Assert
exitCode.Should().Be(0);
@@ -443,10 +419,7 @@ public class HelpTextSpecs : SpecsBase
.Build();
// Act
var exitCode = await application.RunAsync(
new[] { "--help" },
new Dictionary<string, string>()
);
var exitCode = await application.RunAsync(["--help"], new Dictionary<string, string>());
// Assert
exitCode.Should().Be(0);
@@ -484,10 +457,7 @@ public class HelpTextSpecs : SpecsBase
.Build();
// Act
var exitCode = await application.RunAsync(
new[] { "--help" },
new Dictionary<string, string>()
);
var exitCode = await application.RunAsync(["--help"], new Dictionary<string, string>());
// Assert
exitCode.Should().Be(0);
@@ -506,7 +476,7 @@ public class HelpTextSpecs : SpecsBase
}
[Fact]
public async Task I_can_request_the_help_text_to_see_the_help_and_version_options()
public async Task I_can_request_the_help_text_to_see_the_help_and_implicit_version_options()
{
// Arrange
var commandType = DynamicCommandBuilder.Compile(
@@ -526,10 +496,7 @@ public class HelpTextSpecs : SpecsBase
.Build();
// Act
var exitCode = await application.RunAsync(
new[] { "--help" },
new Dictionary<string, string>()
);
var exitCode = await application.RunAsync(["--help"], new Dictionary<string, string>());
// Assert
exitCode.Should().Be(0);
@@ -548,7 +515,7 @@ public class HelpTextSpecs : SpecsBase
}
[Fact]
public async Task I_can_request_the_help_text_on_a_named_command_to_see_the_help_option()
public async Task I_can_request_the_help_text_on_a_named_command_to_see_the_implicit_help_option()
{
// Arrange
var commandType = DynamicCommandBuilder.Compile(
@@ -569,7 +536,7 @@ public class HelpTextSpecs : SpecsBase
// Act
var exitCode = await application.RunAsync(
new[] { "cmd", "--help" },
["cmd", "--help"],
new Dictionary<string, string>()
);
@@ -612,10 +579,7 @@ public class HelpTextSpecs : SpecsBase
.Build();
// Act
var exitCode = await application.RunAsync(
new[] { "--help" },
new Dictionary<string, string>()
);
var exitCode = await application.RunAsync(["--help"], new Dictionary<string, string>());
// Assert
exitCode.Should().Be(0);
@@ -668,10 +632,7 @@ public class HelpTextSpecs : SpecsBase
.Build();
// Act
var exitCode = await application.RunAsync(
new[] { "--help" },
new Dictionary<string, string>()
);
var exitCode = await application.RunAsync(["--help"], new Dictionary<string, string>());
// Assert
exitCode.Should().Be(0);
@@ -724,10 +685,7 @@ public class HelpTextSpecs : SpecsBase
.Build();
// Act
var exitCode = await application.RunAsync(
new[] { "--help" },
new Dictionary<string, string>()
);
var exitCode = await application.RunAsync(["--help"], new Dictionary<string, string>());
// Assert
exitCode.Should().Be(0);
@@ -780,10 +738,7 @@ public class HelpTextSpecs : SpecsBase
.Build();
// Act
var exitCode = await application.RunAsync(
new[] { "--help" },
new Dictionary<string, string>()
);
var exitCode = await application.RunAsync(["--help"], new Dictionary<string, string>());
// Assert
exitCode.Should().Be(0);
@@ -849,10 +804,7 @@ public class HelpTextSpecs : SpecsBase
.Build();
// Act
var exitCode = await application.RunAsync(
new[] { "--help" },
new Dictionary<string, string>()
);
var exitCode = await application.RunAsync(["--help"], new Dictionary<string, string>());
// Assert
exitCode.Should().Be(0);
@@ -930,10 +882,7 @@ public class HelpTextSpecs : SpecsBase
.Build();
// Act
var exitCode = await application.RunAsync(
new[] { "--help" },
new Dictionary<string, string>()
);
var exitCode = await application.RunAsync(["--help"], new Dictionary<string, string>());
// Assert
exitCode.Should().Be(0);
@@ -1004,10 +953,7 @@ public class HelpTextSpecs : SpecsBase
.Build();
// Act
var exitCode = await application.RunAsync(
new[] { "--help" },
new Dictionary<string, string>()
);
var exitCode = await application.RunAsync(["--help"], new Dictionary<string, string>());
// Assert
exitCode.Should().Be(0);
@@ -1028,7 +974,7 @@ public class HelpTextSpecs : SpecsBase
}
[Fact]
public async Task I_can_request_the_version_text_by_running_the_application_with_the_version_option()
public async Task I_can_request_the_version_text_by_running_the_application_with_the_implicit_version_option()
{
// Arrange
var application = new CliApplicationBuilder()
@@ -1038,10 +984,7 @@ public class HelpTextSpecs : SpecsBase
.Build();
// Act
var exitCode = await application.RunAsync(
new[] { "--version" },
new Dictionary<string, string>()
);
var exitCode = await application.RunAsync(["--version"], new Dictionary<string, string>());
// Assert
exitCode.Should().Be(0);
@@ -1049,4 +992,72 @@ public class HelpTextSpecs : SpecsBase
var stdOut = FakeConsole.ReadOutputString();
stdOut.Trim().Should().Be("v6.9");
}
[Fact]
public async Task I_cannot_request_the_help_text_by_running_the_application_with_the_implicit_help_option_if_there_is_an_option_with_the_same_identifier()
{
// Arrange
var commandType = DynamicCommandBuilder.Compile(
// lang=csharp
"""
[Command]
public class DefaultCommand : ICommand
{
[CommandOption("help", 'h')]
public string? Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default;
}
"""
);
var application = new CliApplicationBuilder()
.AddCommand(commandType)
.UseConsole(FakeConsole)
.SetDescription("This will be in help text")
.Build();
// Act
var exitCode = await application.RunAsync(["--help"], new Dictionary<string, string>());
// Assert
exitCode.Should().Be(0);
var stdOut = FakeConsole.ReadOutputString();
stdOut.Should().NotContain("This will be in help text");
}
[Fact]
public async Task I_cannot_request_the_version_text_by_running_the_application_with_the_implicit_version_option_if_there_is_an_option_with_the_same_identifier()
{
// Arrange
var commandType = DynamicCommandBuilder.Compile(
// lang=csharp
"""
[Command]
public class DefaultCommand : ICommand
{
[CommandOption("version")]
public string? Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default;
}
"""
);
var application = new CliApplicationBuilder()
.AddCommand(commandType)
.SetVersion("v6.9")
.UseConsole(FakeConsole)
.Build();
// Act
var exitCode = await application.RunAsync(["--version"], new Dictionary<string, string>());
// Assert
exitCode.Should().Be(0);
var stdOut = FakeConsole.ReadOutputString();
stdOut.Trim().Should().NotBe("v6.9");
}
}

View File

@@ -9,11 +9,8 @@ using Xunit.Abstractions;
namespace CliFx.Tests;
public class OptionBindingSpecs : SpecsBase
public class OptionBindingSpecs(ITestOutputHelper testOutput) : SpecsBase(testOutput)
{
public OptionBindingSpecs(ITestOutputHelper testOutput)
: base(testOutput) { }
[Fact]
public async Task I_can_bind_an_option_to_a_property_and_get_the_value_from_the_corresponding_argument_by_name()
{
@@ -29,7 +26,7 @@ public class OptionBindingSpecs : SpecsBase
public ValueTask ExecuteAsync(IConsole console)
{
console.Output.WriteLine(Foo);
console.WriteLine(Foo);
return default;
}
}
@@ -42,10 +39,7 @@ public class OptionBindingSpecs : SpecsBase
.Build();
// Act
var exitCode = await application.RunAsync(
new[] { "--foo" },
new Dictionary<string, string>()
);
var exitCode = await application.RunAsync(["--foo"], new Dictionary<string, string>());
// Assert
exitCode.Should().Be(0);
@@ -69,7 +63,7 @@ public class OptionBindingSpecs : SpecsBase
public ValueTask ExecuteAsync(IConsole console)
{
console.Output.WriteLine(Foo);
console.WriteLine(Foo);
return default;
}
}
@@ -82,7 +76,7 @@ public class OptionBindingSpecs : SpecsBase
.Build();
// Act
var exitCode = await application.RunAsync(new[] { "-f" }, new Dictionary<string, string>());
var exitCode = await application.RunAsync(["-f"], new Dictionary<string, string>());
// Assert
exitCode.Should().Be(0);
@@ -109,8 +103,8 @@ public class OptionBindingSpecs : SpecsBase
public ValueTask ExecuteAsync(IConsole console)
{
console.Output.WriteLine("Foo = " + Foo);
console.Output.WriteLine("Bar = " + Bar);
console.WriteLine("Foo = " + Foo);
console.WriteLine("Bar = " + Bar);
return default;
}
@@ -125,7 +119,7 @@ public class OptionBindingSpecs : SpecsBase
// Act
var exitCode = await application.RunAsync(
new[] { "--foo", "one", "--bar", "two" },
["--foo", "one", "--bar", "two"],
new Dictionary<string, string>()
);
@@ -154,8 +148,8 @@ public class OptionBindingSpecs : SpecsBase
public ValueTask ExecuteAsync(IConsole console)
{
console.Output.WriteLine("Foo = " + Foo);
console.Output.WriteLine("Bar = " + Bar);
console.WriteLine("Foo = " + Foo);
console.WriteLine("Bar = " + Bar);
return default;
}
@@ -170,7 +164,7 @@ public class OptionBindingSpecs : SpecsBase
// Act
var exitCode = await application.RunAsync(
new[] { "-f", "one", "-b", "two" },
["-f", "one", "-b", "two"],
new Dictionary<string, string>()
);
@@ -199,8 +193,8 @@ public class OptionBindingSpecs : SpecsBase
public ValueTask ExecuteAsync(IConsole console)
{
console.Output.WriteLine("Foo = " + Foo);
console.Output.WriteLine("Bar = " + Bar);
console.WriteLine("Foo = " + Foo);
console.WriteLine("Bar = " + Bar);
return default;
}
@@ -215,7 +209,7 @@ public class OptionBindingSpecs : SpecsBase
// Act
var exitCode = await application.RunAsync(
new[] { "-fb", "value" },
["-fb", "value"],
new Dictionary<string, string>()
);
@@ -242,7 +236,7 @@ public class OptionBindingSpecs : SpecsBase
public ValueTask ExecuteAsync(IConsole console)
{
foreach (var i in Foo)
console.Output.WriteLine(i);
console.WriteLine(i);
return default;
}
@@ -257,7 +251,7 @@ public class OptionBindingSpecs : SpecsBase
// Act
var exitCode = await application.RunAsync(
new[] { "--foo", "one", "two", "three" },
["--foo", "one", "two", "three"],
new Dictionary<string, string>()
);
@@ -284,7 +278,7 @@ public class OptionBindingSpecs : SpecsBase
public ValueTask ExecuteAsync(IConsole console)
{
foreach (var i in Foo)
console.Output.WriteLine(i);
console.WriteLine(i);
return default;
}
@@ -299,7 +293,7 @@ public class OptionBindingSpecs : SpecsBase
// Act
var exitCode = await application.RunAsync(
new[] { "-f", "one", "two", "three" },
["-f", "one", "two", "three"],
new Dictionary<string, string>()
);
@@ -326,7 +320,7 @@ public class OptionBindingSpecs : SpecsBase
public ValueTask ExecuteAsync(IConsole console)
{
foreach (var i in Foo)
console.Output.WriteLine(i);
console.WriteLine(i);
return default;
}
@@ -341,7 +335,7 @@ public class OptionBindingSpecs : SpecsBase
// Act
var exitCode = await application.RunAsync(
new[] { "--foo", "one", "--foo", "two", "--foo", "three" },
["--foo", "one", "--foo", "two", "--foo", "three"],
new Dictionary<string, string>()
);
@@ -368,7 +362,7 @@ public class OptionBindingSpecs : SpecsBase
public ValueTask ExecuteAsync(IConsole console)
{
foreach (var i in Foo)
console.Output.WriteLine(i);
console.WriteLine(i);
return default;
}
@@ -383,7 +377,7 @@ public class OptionBindingSpecs : SpecsBase
// Act
var exitCode = await application.RunAsync(
new[] { "-f", "one", "-f", "two", "-f", "three" },
["-f", "one", "-f", "two", "-f", "three"],
new Dictionary<string, string>()
);
@@ -410,7 +404,7 @@ public class OptionBindingSpecs : SpecsBase
public ValueTask ExecuteAsync(IConsole console)
{
foreach (var i in Foo)
console.Output.WriteLine(i);
console.WriteLine(i);
return default;
}
@@ -425,7 +419,7 @@ public class OptionBindingSpecs : SpecsBase
// Act
var exitCode = await application.RunAsync(
new[] { "--foo", "one", "-f", "two", "--foo", "three" },
["--foo", "one", "-f", "two", "--foo", "three"],
new Dictionary<string, string>()
);
@@ -454,8 +448,8 @@ public class OptionBindingSpecs : SpecsBase
public ValueTask ExecuteAsync(IConsole console)
{
console.Output.WriteLine("Foo = " + Foo);
console.Output.WriteLine("Bar = " + Bar);
console.WriteLine("Foo = " + Foo);
console.WriteLine("Bar = " + Bar);
return default;
}
@@ -470,7 +464,7 @@ public class OptionBindingSpecs : SpecsBase
// Act
var exitCode = await application.RunAsync(
new[] { "--foo", "one" },
["--foo", "one"],
new Dictionary<string, string>()
);
@@ -528,9 +522,9 @@ public class OptionBindingSpecs : SpecsBase
public ValueTask ExecuteAsync(IConsole console)
{
console.Output.WriteLine("Foo = " + SharedContext.Foo);
console.Output.WriteLine("Bar = " + SharedContext.Bar);
console.Output.WriteLine("Baz = " + Baz);
console.WriteLine("Foo = " + SharedContext.Foo);
console.WriteLine("Bar = " + SharedContext.Bar);
console.WriteLine("Baz = " + Baz);
return default;
}
@@ -544,7 +538,7 @@ public class OptionBindingSpecs : SpecsBase
.Build();
// Act
var exitCode = await application.RunAsync(new[] { "--foo", "42", "--bar", "--baz", "xyz" });
var exitCode = await application.RunAsync(["--foo", "42", "--bar", "--baz", "xyz"]);
// Assert
exitCode.Should().Be(0);
@@ -568,7 +562,7 @@ public class OptionBindingSpecs : SpecsBase
public ValueTask ExecuteAsync(IConsole console)
{
console.Output.WriteLine(Foo);
console.WriteLine(Foo);
return default;
}
}
@@ -582,7 +576,7 @@ public class OptionBindingSpecs : SpecsBase
// Act
var exitCode = await application.RunAsync(
new[] { "--foo", "-13" },
["--foo", "-13"],
new Dictionary<string, string>()
);
@@ -593,6 +587,86 @@ public class OptionBindingSpecs : SpecsBase
stdOut.Trim().Should().Be("-13");
}
[Fact]
public async Task I_can_bind_an_option_to_a_property_with_the_same_identifier_as_the_implicit_help_option_and_get_the_correct_value()
{
// Arrange
var commandType = DynamicCommandBuilder.Compile(
// lang=csharp
"""
[Command]
public class Command : ICommand
{
[CommandOption("help", 'h')]
public string? Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console)
{
console.WriteLine(Foo);
return default;
}
}
"""
);
var application = new CliApplicationBuilder()
.AddCommand(commandType)
.UseConsole(FakeConsole)
.Build();
// Act
var exitCode = await application.RunAsync(
["--help", "me"],
new Dictionary<string, string>()
);
// Assert
exitCode.Should().Be(0);
var stdOut = FakeConsole.ReadOutputString();
stdOut.Trim().Should().Be("me");
}
[Fact]
public async Task I_can_bind_an_option_to_a_property_with_the_same_identifier_as_the_implicit_version_option_and_get_the_correct_value()
{
// Arrange
var commandType = DynamicCommandBuilder.Compile(
// lang=csharp
"""
[Command]
public class Command : ICommand
{
[CommandOption("version")]
public string? Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console)
{
console.WriteLine(Foo);
return default;
}
}
"""
);
var application = new CliApplicationBuilder()
.AddCommand(commandType)
.UseConsole(FakeConsole)
.Build();
// Act
var exitCode = await application.RunAsync(
["--version", "1.2.0"],
new Dictionary<string, string>()
);
// Assert
exitCode.Should().Be(0);
var stdOut = FakeConsole.ReadOutputString();
stdOut.Trim().Should().Be("1.2.0");
}
[Fact]
public async Task I_can_try_to_bind_a_required_option_to_a_property_and_get_an_error_if_the_user_does_not_provide_the_corresponding_argument()
{
@@ -653,10 +727,7 @@ public class OptionBindingSpecs : SpecsBase
.Build();
// Act
var exitCode = await application.RunAsync(
new[] { "--foo" },
new Dictionary<string, string>()
);
var exitCode = await application.RunAsync(["--foo"], new Dictionary<string, string>());
// Assert
exitCode.Should().NotBe(0);
@@ -689,10 +760,7 @@ public class OptionBindingSpecs : SpecsBase
.Build();
// Act
var exitCode = await application.RunAsync(
new[] { "--foo" },
new Dictionary<string, string>()
);
var exitCode = await application.RunAsync(["--foo"], new Dictionary<string, string>());
// Assert
exitCode.Should().NotBe(0);
@@ -726,7 +794,7 @@ public class OptionBindingSpecs : SpecsBase
// Act
var exitCode = await application.RunAsync(
new[] { "--foo", "one", "--bar", "two" },
["--foo", "one", "--bar", "two"],
new Dictionary<string, string>()
);
@@ -762,7 +830,7 @@ public class OptionBindingSpecs : SpecsBase
// Act
var exitCode = await application.RunAsync(
new[] { "--foo", "one", "two", "three" },
["--foo", "one", "two", "three"],
new Dictionary<string, string>()
);

View File

@@ -8,11 +8,8 @@ using Xunit.Abstractions;
namespace CliFx.Tests;
public class ParameterBindingSpecs : SpecsBase
public class ParameterBindingSpecs(ITestOutputHelper testOutput) : SpecsBase(testOutput)
{
public ParameterBindingSpecs(ITestOutputHelper testOutput)
: base(testOutput) { }
[Fact]
public async Task I_can_bind_a_parameter_to_a_property_and_get_the_value_from_the_corresponding_argument()
{
@@ -31,8 +28,8 @@ public class ParameterBindingSpecs : SpecsBase
public ValueTask ExecuteAsync(IConsole console)
{
console.Output.WriteLine("Foo = " + Foo);
console.Output.WriteLine("Bar = " + Bar);
console.WriteLine("Foo = " + Foo);
console.WriteLine("Bar = " + Bar);
return default;
}
@@ -46,10 +43,7 @@ public class ParameterBindingSpecs : SpecsBase
.Build();
// Act
var exitCode = await application.RunAsync(
new[] { "one", "two" },
new Dictionary<string, string>()
);
var exitCode = await application.RunAsync(["one", "two"], new Dictionary<string, string>());
// Assert
exitCode.Should().Be(0);
@@ -82,11 +76,11 @@ public class ParameterBindingSpecs : SpecsBase
public ValueTask ExecuteAsync(IConsole console)
{
console.Output.WriteLine("Foo = " + Foo);
console.Output.WriteLine("Bar = " + Bar);
console.WriteLine("Foo = " + Foo);
console.WriteLine("Bar = " + Bar);
foreach (var i in Baz)
console.Output.WriteLine("Baz = " + i);
console.WriteLine("Baz = " + i);
return default;
}
@@ -101,7 +95,7 @@ public class ParameterBindingSpecs : SpecsBase
// Act
var exitCode = await application.RunAsync(
new[] { "one", "two", "three", "four", "five", "--boo", "xxx" },
["one", "two", "three", "four", "five", "--boo", "xxx"],
new Dictionary<string, string>()
);
@@ -141,10 +135,7 @@ public class ParameterBindingSpecs : SpecsBase
.Build();
// Act
var exitCode = await application.RunAsync(
new[] { "one" },
new Dictionary<string, string>()
);
var exitCode = await application.RunAsync(["one"], new Dictionary<string, string>());
// Assert
exitCode.Should().NotBe(0);
@@ -180,10 +171,7 @@ public class ParameterBindingSpecs : SpecsBase
.Build();
// Act
var exitCode = await application.RunAsync(
new[] { "one" },
new Dictionary<string, string>()
);
var exitCode = await application.RunAsync(["one"], new Dictionary<string, string>());
// Assert
exitCode.Should().NotBe(0);
@@ -210,8 +198,8 @@ public class ParameterBindingSpecs : SpecsBase
public ValueTask ExecuteAsync(IConsole console)
{
console.Output.WriteLine("Foo = " + Foo);
console.Output.WriteLine("Bar = " + Bar);
console.WriteLine("Foo = " + Foo);
console.WriteLine("Bar = " + Bar);
return default;
}
@@ -225,10 +213,7 @@ public class ParameterBindingSpecs : SpecsBase
.Build();
// Act
var exitCode = await application.RunAsync(
new[] { "abc" },
new Dictionary<string, string>()
);
var exitCode = await application.RunAsync(["abc"], new Dictionary<string, string>());
// Assert
exitCode.Should().Be(0);
@@ -265,7 +250,7 @@ public class ParameterBindingSpecs : SpecsBase
// Act
var exitCode = await application.RunAsync(
new[] { "one", "two", "three" },
["one", "two", "three"],
new Dictionary<string, string>()
);

View File

@@ -8,11 +8,8 @@ using Xunit.Abstractions;
namespace CliFx.Tests;
public class RoutingSpecs : SpecsBase
public class RoutingSpecs(ITestOutputHelper testOutput) : SpecsBase(testOutput)
{
public RoutingSpecs(ITestOutputHelper testOutput)
: base(testOutput) { }
[Fact]
public async Task I_can_configure_a_command_to_be_executed_by_default_when_the_user_does_not_specify_a_command_name()
{
@@ -25,7 +22,7 @@ public class RoutingSpecs : SpecsBase
{
public ValueTask ExecuteAsync(IConsole console)
{
console.Output.WriteLine("default");
console.WriteLine("default");
return default;
}
}
@@ -35,7 +32,7 @@ public class RoutingSpecs : SpecsBase
{
public ValueTask ExecuteAsync(IConsole console)
{
console.Output.WriteLine("cmd");
console.WriteLine("cmd");
return default;
}
}
@@ -45,7 +42,7 @@ public class RoutingSpecs : SpecsBase
{
public ValueTask ExecuteAsync(IConsole console)
{
console.Output.WriteLine("cmd child");
console.WriteLine("cmd child");
return default;
}
}
@@ -82,7 +79,7 @@ public class RoutingSpecs : SpecsBase
{
public ValueTask ExecuteAsync(IConsole console)
{
console.Output.WriteLine("default");
console.WriteLine("default");
return default;
}
}
@@ -92,7 +89,7 @@ public class RoutingSpecs : SpecsBase
{
public ValueTask ExecuteAsync(IConsole console)
{
console.Output.WriteLine("cmd");
console.WriteLine("cmd");
return default;
}
}
@@ -102,7 +99,7 @@ public class RoutingSpecs : SpecsBase
{
public ValueTask ExecuteAsync(IConsole console)
{
console.Output.WriteLine("cmd child");
console.WriteLine("cmd child");
return default;
}
}
@@ -115,10 +112,7 @@ public class RoutingSpecs : SpecsBase
.Build();
// Act
var exitCode = await application.RunAsync(
new[] { "cmd" },
new Dictionary<string, string>()
);
var exitCode = await application.RunAsync(["cmd"], new Dictionary<string, string>());
// Assert
exitCode.Should().Be(0);
@@ -139,7 +133,7 @@ public class RoutingSpecs : SpecsBase
{
public ValueTask ExecuteAsync(IConsole console)
{
console.Output.WriteLine("default");
console.WriteLine("default");
return default;
}
}
@@ -149,7 +143,7 @@ public class RoutingSpecs : SpecsBase
{
public ValueTask ExecuteAsync(IConsole console)
{
console.Output.WriteLine("cmd");
console.WriteLine("cmd");
return default;
}
}
@@ -159,7 +153,7 @@ public class RoutingSpecs : SpecsBase
{
public ValueTask ExecuteAsync(IConsole console)
{
console.Output.WriteLine("cmd child");
console.WriteLine("cmd child");
return default;
}
}
@@ -173,7 +167,7 @@ public class RoutingSpecs : SpecsBase
// Act
var exitCode = await application.RunAsync(
new[] { "cmd", "child" },
["cmd", "child"],
new Dictionary<string, string>()
);

View File

@@ -5,14 +5,12 @@ using Xunit.Abstractions;
namespace CliFx.Tests;
public abstract class SpecsBase : IDisposable
public abstract class SpecsBase(ITestOutputHelper testOutput) : IDisposable
{
public ITestOutputHelper TestOutput { get; }
public ITestOutputHelper TestOutput { get; } = testOutput;
public FakeInMemoryConsole FakeConsole { get; } = new();
protected SpecsBase(ITestOutputHelper testOutput) => TestOutput = testOutput;
public void Dispose()
{
FakeConsole.DumpToTestOutput(TestOutput);

View File

@@ -10,11 +10,8 @@ using Xunit.Abstractions;
namespace CliFx.Tests;
public class TypeActivationSpecs : SpecsBase
public class TypeActivationSpecs(ITestOutputHelper testOutput) : SpecsBase(testOutput)
{
public TypeActivationSpecs(ITestOutputHelper testOutput)
: base(testOutput) { }
[Fact]
public async Task I_can_configure_the_application_to_use_the_default_type_activator_to_initialize_types_through_parameterless_constructors()
{
@@ -27,7 +24,7 @@ public class TypeActivationSpecs : SpecsBase
{
public ValueTask ExecuteAsync(IConsole console)
{
console.Output.WriteLine("foo");
console.WriteLine("foo");
return default;
}
}
@@ -105,7 +102,7 @@ public class TypeActivationSpecs : SpecsBase
public ValueTask ExecuteAsync(IConsole console)
{
console.Output.WriteLine(_foo);
console.WriteLine(_foo);
return default;
}
}
@@ -147,7 +144,7 @@ public class TypeActivationSpecs : SpecsBase
public ValueTask ExecuteAsync(IConsole console)
{
console.Output.WriteLine(_foo);
console.WriteLine(_foo);
return default;
}
}
@@ -198,7 +195,7 @@ public class TypeActivationSpecs : SpecsBase
{
public ValueTask ExecuteAsync(IConsole console)
{
console.Output.WriteLine("foo");
console.WriteLine("foo");
return default;
}
}

View File

@@ -27,13 +27,12 @@ internal static class DynamicCommandBuilder
"System.Collections.Generic",
"System.Linq",
"System.Threading.Tasks",
"System.Globalization"
"System.Globalization",
};
// Get default CliFx namespaces
var defaultCliFxNamespaces = typeof(ICommand)
.Assembly
.GetTypes()
.Assembly.GetTypes()
.Where(t => t.IsPublic)
.Select(t => t.Namespace)
.Distinct()
@@ -49,17 +48,17 @@ internal static class DynamicCommandBuilder
// Parse the source code
var ast = SyntaxFactory.ParseSyntaxTree(
SourceText.From(sourceCodeWithUsings),
CSharpParseOptions.Default
CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.Preview)
);
// Compile the code to IL
var compilation = CSharpCompilation.Create(
"CliFxTests_DynamicAssembly_" + Guid.NewGuid(),
new[] { ast },
Net70
.References
.All
.Append(MetadataReference.CreateFromFile(typeof(ICommand).Assembly.Location))
[ast],
Net80
.References.All.Append(
MetadataReference.CreateFromFile(typeof(ICommand).Assembly.Location)
)
.Append(
MetadataReference.CreateFromFile(
typeof(DynamicCommandBuilder).Assembly.Location
@@ -88,8 +87,8 @@ internal static class DynamicCommandBuilder
using var buffer = new MemoryStream();
var emit = compilation.Emit(buffer);
var emitErrors = emit.Diagnostics
.Where(d => d.Severity >= DiagnosticSeverity.Error)
var emitErrors = emit
.Diagnostics.Where(d => d.Severity >= DiagnosticSeverity.Error)
.ToArray();
if (emitErrors.Any())

View File

@@ -1,7 +1,6 @@
using System;
using System.Collections.Generic;
using FluentAssertions;
using FluentAssertions.Execution;
using FluentAssertions.Primitives;
namespace CliFx.Tests.Utils.Extensions;
@@ -10,17 +9,13 @@ internal static class AssertionExtensions
{
public static void ConsistOfLines(
this StringAssertions assertions,
IEnumerable<string> lines
params IEnumerable<string> lines
) =>
assertions
.Subject
.Split(new[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries)
.Subject.Split(['\n', '\r'], StringSplitOptions.RemoveEmptyEntries)
.Should()
.Equal(lines);
public static void ConsistOfLines(this StringAssertions assertions, params string[] lines) =>
assertions.ConsistOfLines((IEnumerable<string>)lines);
public static AndConstraint<StringAssertions> ContainAllInOrder(
this StringAssertions assertions,
IEnumerable<string> values
@@ -34,9 +29,7 @@ internal static class AssertionExtensions
if (index < 0)
{
Execute
.Assertion
.FailWith(
assertions.CurrentAssertionChain.FailWith(
$"Expected string '{assertions.Subject}' to contain '{value}' after position {lastIndex}."
);
}

View File

@@ -7,9 +7,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CliFx", "CliFx\CliFx.csproj
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CliFx.Tests", "CliFx.Tests\CliFx.Tests.csproj", "{268CF863-65A5-49BB-93CF-08972B7756DC}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{3AAE8166-BB8E-49DA-844C-3A0EE6BD40A0}"
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Misc", "Misc", "{3AAE8166-BB8E-49DA-844C-3A0EE6BD40A0}"
ProjectSection(SolutionItems) = preProject
Changelog.md = Changelog.md
Directory.Build.props = Directory.Build.props
License.txt = License.txt
Readme.md = Readme.md

View File

@@ -6,34 +6,24 @@ namespace CliFx;
/// <summary>
/// Configuration of an application.
/// </summary>
public class ApplicationConfiguration
{
/// <summary>
/// Command types defined in the application.
/// </summary>
public IReadOnlyList<Type> CommandTypes { get; }
/// <summary>
/// Whether debug mode is allowed in the application.
/// </summary>
public bool IsDebugModeAllowed { get; }
/// <summary>
/// Whether preview mode is allowed in the application.
/// </summary>
public bool IsPreviewModeAllowed { get; }
/// <summary>
/// Initializes an instance of <see cref="ApplicationConfiguration" />.
/// </summary>
public ApplicationConfiguration(
public class ApplicationConfiguration(
IReadOnlyList<Type> commandTypes,
bool isDebugModeAllowed,
bool isPreviewModeAllowed
)
{
CommandTypes = commandTypes;
IsDebugModeAllowed = isDebugModeAllowed;
IsPreviewModeAllowed = isPreviewModeAllowed;
}
/// <summary>
/// Command types defined in the application.
/// </summary>
public IReadOnlyList<Type> CommandTypes { get; } = commandTypes;
/// <summary>
/// Whether debug mode is allowed in the application.
/// </summary>
public bool IsDebugModeAllowed { get; } = isDebugModeAllowed;
/// <summary>
/// Whether preview mode is allowed in the application.
/// </summary>
public bool IsPreviewModeAllowed { get; } = isPreviewModeAllowed;
}

View File

@@ -3,41 +3,30 @@
/// <summary>
/// Metadata associated with an application.
/// </summary>
public class ApplicationMetadata
{
/// <summary>
/// Application title.
/// </summary>
public string Title { get; }
/// <summary>
/// Application executable name.
/// </summary>
public string ExecutableName { get; }
/// <summary>
/// Application version.
/// </summary>
public string Version { get; }
/// <summary>
/// Application description.
/// </summary>
public string? Description { get; }
/// <summary>
/// Initializes an instance of <see cref="ApplicationMetadata" />.
/// </summary>
public ApplicationMetadata(
public class ApplicationMetadata(
string title,
string executableName,
string version,
string? description
)
{
Title = title;
ExecutableName = executableName;
Version = version;
Description = description;
}
/// <summary>
/// Application title.
/// </summary>
public string Title { get; } = title;
/// <summary>
/// Application executable name.
/// </summary>
public string ExecutableName { get; } = executableName;
/// <summary>
/// Application version.
/// </summary>
public string Version { get; } = version;
/// <summary>
/// Application description.
/// </summary>
public string? Description { get; } = description;
}

View File

@@ -8,6 +8,16 @@ namespace CliFx.Attributes;
[AttributeUsage(AttributeTargets.Class, Inherited = false)]
public sealed class CommandAttribute : Attribute
{
/// <summary>
/// Initializes an instance of <see cref="CommandAttribute" />.
/// </summary>
public CommandAttribute(string name) => Name = name;
/// <summary>
/// Initializes an instance of <see cref="CommandAttribute" />.
/// </summary>
public CommandAttribute() { }
/// <summary>
/// Command name.
/// </summary>
@@ -23,17 +33,4 @@ public sealed class CommandAttribute : Attribute
/// This is shown to the user in the help text.
/// </summary>
public string? Description { get; set; }
/// <summary>
/// Initializes an instance of <see cref="CommandAttribute" />.
/// </summary>
public CommandAttribute(string name)
{
Name = name;
}
/// <summary>
/// Initializes an instance of <see cref="CommandAttribute" />.
/// </summary>
public CommandAttribute() { }
}

View File

@@ -9,6 +9,33 @@ namespace CliFx.Attributes;
[AttributeUsage(AttributeTargets.Property)]
public sealed class CommandOptionAttribute : Attribute
{
/// <summary>
/// Initializes an instance of <see cref="CommandOptionAttribute" />.
/// </summary>
private CommandOptionAttribute(string? name, char? shortName)
{
Name = name;
ShortName = shortName;
}
/// <summary>
/// Initializes an instance of <see cref="CommandOptionAttribute" />.
/// </summary>
public CommandOptionAttribute(string name, char shortName)
: this(name, (char?)shortName) { }
/// <summary>
/// Initializes an instance of <see cref="CommandOptionAttribute" />.
/// </summary>
public CommandOptionAttribute(string name)
: this(name, null) { }
/// <summary>
/// Initializes an instance of <see cref="CommandOptionAttribute" />.
/// </summary>
public CommandOptionAttribute(char shortName)
: this(null, (char?)shortName) { }
/// <summary>
/// Option name.
/// </summary>
@@ -67,31 +94,4 @@ public sealed class CommandOptionAttribute : Attribute
/// Validators must derive from <see cref="BindingValidator{T}" />.
/// </remarks>
public Type[] Validators { get; set; } = Array.Empty<Type>();
/// <summary>
/// Initializes an instance of <see cref="CommandOptionAttribute" />.
/// </summary>
private CommandOptionAttribute(string? name, char? shortName)
{
Name = name;
ShortName = shortName;
}
/// <summary>
/// Initializes an instance of <see cref="CommandOptionAttribute" />.
/// </summary>
public CommandOptionAttribute(string name, char shortName)
: this(name, (char?)shortName) { }
/// <summary>
/// Initializes an instance of <see cref="CommandOptionAttribute" />.
/// </summary>
public CommandOptionAttribute(string name)
: this(name, null) { }
/// <summary>
/// Initializes an instance of <see cref="CommandOptionAttribute" />.
/// </summary>
public CommandOptionAttribute(char shortName)
: this(null, (char?)shortName) { }
}

View File

@@ -7,7 +7,7 @@ namespace CliFx.Attributes;
/// Annotates a property that defines a command parameter.
/// </summary>
[AttributeUsage(AttributeTargets.Property)]
public sealed class CommandParameterAttribute : Attribute
public sealed class CommandParameterAttribute(int order) : Attribute
{
/// <summary>
/// Parameter order.
@@ -18,7 +18,7 @@ public sealed class CommandParameterAttribute : Attribute
/// Parameter whose type is a non-scalar (e.g. array), must always be the last in order.
/// Only one non-scalar parameter is allowed in a command.
/// </remarks>
public int Order { get; }
public int Order { get; } = order;
/// <summary>
/// Whether this parameter is required (default: <c>true</c>).
@@ -62,12 +62,4 @@ public sealed class CommandParameterAttribute : Attribute
/// Validators must derive from <see cref="BindingValidator{T}" />.
/// </remarks>
public Type[] Validators { get; set; } = Array.Empty<Type>();
/// <summary>
/// Initializes an instance of <see cref="CommandParameterAttribute" />.
/// </summary>
public CommandParameterAttribute(int order)
{
Order = order;
}
}

View File

@@ -2,7 +2,6 @@ using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using CliFx.Exceptions;
using CliFx.Formatting;
@@ -17,40 +16,24 @@ namespace CliFx;
/// <summary>
/// Command-line application facade.
/// </summary>
public class CliApplication
{
/// <summary>
/// Application metadata.
/// </summary>
public ApplicationMetadata Metadata { get; }
/// <summary>
/// Application configuration.
/// </summary>
public ApplicationConfiguration Configuration { get; }
private readonly IConsole _console;
private readonly ITypeActivator _typeActivator;
private readonly CommandBinder _commandBinder;
/// <summary>
/// Initializes an instance of <see cref="CliApplication" />.
/// </summary>
public CliApplication(
public class CliApplication(
ApplicationMetadata metadata,
ApplicationConfiguration configuration,
IConsole console,
ITypeActivator typeActivator
)
{
Metadata = metadata;
Configuration = configuration;
_console = console;
_typeActivator = typeActivator;
private readonly CommandBinder _commandBinder = new(typeActivator);
_commandBinder = new CommandBinder(typeActivator);
}
/// <summary>
/// Application metadata.
/// </summary>
public ApplicationMetadata Metadata { get; } = metadata;
/// <summary>
/// Application configuration.
/// </summary>
public ApplicationConfiguration Configuration { get; } = configuration;
private bool IsDebugModeEnabled(CommandInput commandInput) =>
Configuration.IsDebugModeAllowed && commandInput.IsDebugDirectiveSpecified;
@@ -59,22 +42,20 @@ public class CliApplication
Configuration.IsPreviewModeAllowed && commandInput.IsPreviewDirectiveSpecified;
private bool ShouldShowHelpText(CommandSchema commandSchema, CommandInput commandInput) =>
commandSchema.IsHelpOptionAvailable && commandInput.IsHelpOptionSpecified
commandSchema.IsImplicitHelpOptionAvailable && commandInput.IsHelpOptionSpecified
||
// Show help text also if the fallback default command is executed without any arguments
commandSchema == FallbackDefaultCommand.Schema
&& !commandInput.HasArguments;
private bool ShouldShowVersionText(CommandSchema commandSchema, CommandInput commandInput) =>
commandSchema.IsVersionOptionAvailable && commandInput.IsVersionOptionSpecified;
commandSchema.IsImplicitVersionOptionAvailable && commandInput.IsVersionOptionSpecified;
private async ValueTask PromptDebuggerAsync()
{
using (_console.WithForegroundColor(ConsoleColor.Green))
using (console.WithForegroundColor(ConsoleColor.Green))
{
_console
.Output
.WriteLine(
console.Output.WriteLine(
$"Attach the debugger to process with ID {ProcessEx.GetCurrentProcessId()} to continue."
);
}
@@ -93,7 +74,7 @@ public class CliApplication
{
// Console colors may have already been overridden by the parent process,
// so we need to reset it to make sure that everything we write looks properly.
_console.ResetColor();
console.ResetColor();
// Handle the debug directive
if (IsDebugModeEnabled(commandInput))
@@ -104,7 +85,7 @@ public class CliApplication
// Handle the preview directive
if (IsPreviewModeEnabled(commandInput))
{
_console.Output.WriteCommandInput(commandInput);
console.WriteCommandInput(commandInput);
return 0;
}
@@ -128,7 +109,7 @@ public class CliApplication
var commandInstance =
commandSchema == FallbackDefaultCommand.Schema
? new FallbackDefaultCommand() // bypass the activator
: _typeActivator.CreateInstance<ICommand>(commandSchema.Type);
: typeActivator.CreateInstance<ICommand>(commandSchema.Type);
// Assemble the help context
var helpContext = new HelpContext(
@@ -141,14 +122,14 @@ public class CliApplication
// Handle the help option
if (ShouldShowHelpText(commandSchema, commandInput))
{
_console.Output.WriteHelpText(helpContext);
console.WriteHelpText(helpContext);
return 0;
}
// Handle the version option
if (ShouldShowVersionText(commandSchema, commandInput))
{
_console.Output.WriteLine(Metadata.Version);
console.WriteLine(Metadata.Version);
return 0;
}
@@ -160,18 +141,18 @@ public class CliApplication
{
// Bind and execute the command
_commandBinder.Bind(commandInput, commandSchema, commandInstance);
await commandInstance.ExecuteAsync(_console);
await commandInstance.ExecuteAsync(console);
return 0;
}
catch (CliFxException ex)
{
_console.Error.WriteException(ex);
console.WriteException(ex);
if (ex.ShowHelp)
{
_console.Output.WriteLine();
_console.Output.WriteHelpText(helpContext);
console.WriteLine();
console.WriteHelpText(helpContext);
}
return ex.ExitCode;
@@ -211,7 +192,7 @@ public class CliApplication
// developer, so we don't swallow them in that case.
catch (Exception ex) when (!Debugger.IsAttached)
{
_console.Error.WriteException(ex);
console.WriteException(ex);
return 1;
}
}

View File

@@ -16,7 +16,7 @@ namespace CliFx;
/// </summary>
public partial class CliApplicationBuilder
{
private readonly HashSet<Type> _commandTypes = new();
private readonly HashSet<Type> _commandTypes = [];
private bool _isDebugModeAllowed = true;
private bool _isPreviewModeAllowed = true;
@@ -186,7 +186,8 @@ public partial class CliApplicationBuilder
/// Configures the application to use the specified service provider for activating types.
/// </summary>
public CliApplicationBuilder UseTypeActivator(IServiceProvider serviceProvider) =>
UseTypeActivator(serviceProvider.GetService);
// Null returns are handled by DelegateTypeActivator
UseTypeActivator(serviceProvider.GetService!);
/// <summary>
/// Configures the application to use the specified service provider for activating types.

View File

@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>netstandard2.0;netstandard2.1</TargetFrameworks>
<TargetFrameworks>netstandard2.0;netstandard2.1;net8.0</TargetFrameworks>
<IsPackable>true</IsPackable>
</PropertyGroup>
@@ -10,7 +10,7 @@
<Description>Class-first framework for building command-line interfaces</Description>
<PackageTags>command line executable interface framework parser arguments cli app application net core</PackageTags>
<PackageProjectUrl>https://github.com/Tyrrrz/CliFx</PackageProjectUrl>
<PackageReleaseNotes>https://github.com/Tyrrrz/CliFx/blob/master/Changelog.md</PackageReleaseNotes>
<PackageReleaseNotes>https://github.com/Tyrrrz/CliFx/releases</PackageReleaseNotes>
<PackageIcon>favicon.png</PackageIcon>
<PackageLicenseExpression>MIT</PackageLicenseExpression>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
@@ -21,10 +21,10 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="CSharpier.MsBuild" Version="0.26.1" PrivateAssets="all" />
<PackageReference Include="CSharpier.MsBuild" Version="0.30.6" PrivateAssets="all" />
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="8.0.0" PrivateAssets="all" />
<PackageReference Include="PolyShim" Version="1.8.0" PrivateAssets="all" />
<PackageReference Include="System.Threading.Tasks.Extensions" Version="4.5.4" Condition="'$(TargetFramework)' == 'netstandard2.0'" />
<PackageReference Include="PolyShim" Version="1.15.0" PrivateAssets="all" />
<PackageReference Include="System.Threading.Tasks.Extensions" Version="4.6.0" Condition="!$([MSBuild]::IsTargetFrameworkCompatible('$(TargetFramework)', 'netstandard2.1'))" />
</ItemGroup>
<!-- Embed the analyzer inside the package -->

View File

@@ -12,22 +12,16 @@ using CliFx.Utils.Extensions;
namespace CliFx;
internal class CommandBinder
internal class CommandBinder(ITypeActivator typeActivator)
{
private readonly ITypeActivator _typeActivator;
private readonly IFormatProvider _formatProvider = CultureInfo.InvariantCulture;
public CommandBinder(ITypeActivator typeActivator)
{
_typeActivator = typeActivator;
}
private object? ConvertSingle(IMemberSchema memberSchema, string? rawValue, Type targetType)
{
// Custom converter
if (memberSchema.ConverterType is not null)
{
var converter = _typeActivator.CreateInstance<IBindingConverter>(
var converter = typeActivator.CreateInstance<IBindingConverter>(
memberSchema.ConverterType
);
return converter.Convert(rawValue);
@@ -48,13 +42,15 @@ internal class CommandBinder
// Special case for DateTimeOffset
if (targetType == typeof(DateTimeOffset))
{
return DateTimeOffset.Parse(rawValue, _formatProvider);
// Null reference exception will be handled upstream
return DateTimeOffset.Parse(rawValue!, _formatProvider);
}
// Special case for TimeSpan
if (targetType == typeof(TimeSpan))
{
return TimeSpan.Parse(rawValue, _formatProvider);
// Null reference exception will be handled upstream
return TimeSpan.Parse(rawValue!, _formatProvider);
}
// Enum
@@ -80,27 +76,24 @@ internal class CommandBinder
}
// String-constructable (FileInfo, etc)
var stringConstructor = targetType.GetConstructor(new[] { typeof(string) });
var stringConstructor = targetType.GetConstructor([typeof(string)]);
if (stringConstructor is not null)
{
return stringConstructor.Invoke(new object?[] { rawValue });
return stringConstructor.Invoke([rawValue]);
}
// String-parseable (with IFormatProvider)
var parseMethodWithFormatProvider = targetType.TryGetStaticParseMethod(true);
if (parseMethodWithFormatProvider is not null)
{
return parseMethodWithFormatProvider.Invoke(
null,
new object?[] { rawValue, _formatProvider }
);
return parseMethodWithFormatProvider.Invoke(null, [rawValue, _formatProvider]);
}
// String-parseable (without IFormatProvider)
var parseMethod = targetType.TryGetStaticParseMethod();
if (parseMethod is not null)
{
return parseMethod.Invoke(null, new object?[] { rawValue });
return parseMethod.Invoke(null, [rawValue]);
}
throw CliFxException.InternalError(
@@ -132,10 +125,10 @@ internal class CommandBinder
}
// Array-constructable (List<T>, HashSet<T>, etc)
var arrayConstructor = targetEnumerableType.GetConstructor(new[] { arrayType });
var arrayConstructor = targetEnumerableType.GetConstructor([arrayType]);
if (arrayConstructor is not null)
{
return arrayConstructor.Invoke(new object?[] { array });
return arrayConstructor.Invoke([array]);
}
throw CliFxException.InternalError(
@@ -152,10 +145,8 @@ internal class CommandBinder
try
{
// Non-scalar
var enumerableUnderlyingType = memberSchema
.Property
.Type
.TryGetEnumerableUnderlyingType();
var enumerableUnderlyingType =
memberSchema.Property.Type.TryGetEnumerableUnderlyingType();
if (
enumerableUnderlyingType is not null
@@ -213,7 +204,7 @@ internal class CommandBinder
foreach (var validatorType in memberSchema.ValidatorTypes)
{
var validator = _typeActivator.CreateInstance<IBindingValidator>(validatorType);
var validator = typeActivator.CreateInstance<IBindingValidator>(validatorType);
var error = validator.Validate(convertedValue);
if (error is not null)
@@ -253,8 +244,7 @@ internal class CommandBinder
// Ensure there are no unexpected parameters and that all parameters are provided
var remainingParameterInputs = commandInput.Parameters.ToList();
var remainingRequiredParameterSchemas = commandSchema
.Parameters
.Where(p => p.IsRequired)
.Parameters.Where(p => p.IsRequired)
.ToList();
var position = 0;
@@ -269,12 +259,9 @@ internal class CommandBinder
if (parameterSchema.Property.IsScalar())
{
var parameterInput = commandInput.Parameters[position];
var rawValues = new[] { parameterInput.Value };
BindMember(parameterSchema, commandInstance, rawValues);
BindMember(parameterSchema, commandInstance, [parameterInput.Value]);
position++;
remainingParameterInputs.Remove(parameterInput);
}
// Non-scalar: take all remaining inputs starting from the current position
@@ -282,11 +269,13 @@ internal class CommandBinder
{
var parameterInputs = commandInput.Parameters.Skip(position).ToArray();
var rawValues = parameterInputs.Select(p => p.Value).ToArray();
BindMember(parameterSchema, commandInstance, rawValues);
BindMember(
parameterSchema,
commandInstance,
parameterInputs.Select(p => p.Value).ToArray()
);
position += parameterInputs.Length;
remainingParameterInputs.RemoveRange(parameterInputs);
}
@@ -308,7 +297,9 @@ internal class CommandBinder
throw CliFxException.UserError(
$"""
Missing required parameter(s):
{remainingRequiredParameterSchemas.Select(p => p.GetFormattedIdentifier()).JoinToString(" ")}
{remainingRequiredParameterSchemas
.Select(p => p.GetFormattedIdentifier())
.JoinToString(" ")}
"""
);
}
@@ -323,20 +314,18 @@ internal class CommandBinder
// Ensure there are no unrecognized options and that all required options are set
var remainingOptionInputs = commandInput.Options.ToList();
var remainingRequiredOptionSchemas = commandSchema
.Options
.Where(o => o.IsRequired)
.Options.Where(o => o.IsRequired)
.ToList();
foreach (var optionSchema in commandSchema.Options)
{
var optionInputs = commandInput
.Options
.Where(o => optionSchema.MatchesIdentifier(o.Identifier))
.Options.Where(o => optionSchema.MatchesIdentifier(o.Identifier))
.ToArray();
var environmentVariableInput = commandInput
.EnvironmentVariables
.FirstOrDefault(e => optionSchema.MatchesEnvironmentVariable(e.Name));
var environmentVariableInput = commandInput.EnvironmentVariables.FirstOrDefault(e =>
optionSchema.MatchesEnvironmentVariable(e.Name)
);
// Direct input
if (optionInputs.Any())
@@ -353,7 +342,7 @@ internal class CommandBinder
else if (environmentVariableInput is not null)
{
var rawValues = optionSchema.Property.IsScalar()
? new[] { environmentVariableInput.Value }
? [environmentVariableInput.Value]
: environmentVariableInput.SplitValues();
BindMember(optionSchema, commandInstance, rawValues);
@@ -386,7 +375,9 @@ internal class CommandBinder
throw CliFxException.UserError(
$"""
Missing required option(s):
{remainingRequiredOptionSchemas.Select(o => o.GetFormattedIdentifier()).JoinToString(", ")}
{remainingRequiredOptionSchemas
.Select(o => o.GetFormattedIdentifier())
.JoinToString(", ")}
"""
);
}

View File

@@ -5,7 +5,12 @@ namespace CliFx.Exceptions;
/// <summary>
/// Exception thrown when there is an error during application execution.
/// </summary>
public partial class CliFxException : Exception
public partial class CliFxException(
string message,
int exitCode = CliFxException.DefaultExitCode,
bool showHelp = false,
Exception? innerException = null
) : Exception(message, innerException)
{
internal const int DefaultExitCode = 1;
@@ -13,33 +18,17 @@ public partial class CliFxException : Exception
// provides a default message that is not very useful.
// This property is used to identify whether this instance was created with
// a custom message, so that we can avoid printing the default message.
internal bool HasCustomMessage { get; }
internal bool HasCustomMessage { get; } = !string.IsNullOrWhiteSpace(message);
/// <summary>
/// Returned exit code.
/// </summary>
public int ExitCode { get; }
public int ExitCode { get; } = exitCode;
/// <summary>
/// Whether to show the help text before exiting.
/// </summary>
public bool ShowHelp { get; }
/// <summary>
/// Initializes an instance of <see cref="CliFxException" />.
/// </summary>
public CliFxException(
string message,
int exitCode = DefaultExitCode,
bool showHelp = false,
Exception? innerException = null
)
: base(message, innerException)
{
HasCustomMessage = !string.IsNullOrWhiteSpace(message);
ExitCode = exitCode;
ShowHelp = showHelp;
}
public bool ShowHelp { get; } = showHelp;
}
public partial class CliFxException

View File

@@ -6,16 +6,9 @@ namespace CliFx.Exceptions;
/// Exception thrown when a command cannot proceed with its normal execution due to an error.
/// Use this exception to report an error to the console and return a specific exit code.
/// </summary>
public class CommandException : CliFxException
{
/// <summary>
/// Initializes an instance of <see cref="CommandException" />.
/// </summary>
public CommandException(
public class CommandException(
string message,
int exitCode = DefaultExitCode,
int exitCode = CliFxException.DefaultExitCode,
bool showHelp = false,
Exception? innerException = null
)
: base(message, exitCode, showHelp, innerException) { }
}
) : CliFxException(message, exitCode, showHelp, innerException);

View File

@@ -3,15 +3,10 @@
/// <summary>
/// Represents a validation error.
/// </summary>
public class BindingValidationError
public class BindingValidationError(string message)
{
/// <summary>
/// Error message shown to the user.
/// </summary>
public string Message { get; }
/// <summary>
/// Initializes an instance of <see cref="BindingValidationError" />.
/// </summary>
public BindingValidationError(string message) => Message = message;
public string Message { get; } = message;
}

View File

@@ -4,11 +4,9 @@ using CliFx.Input;
namespace CliFx.Formatting;
internal class CommandInputConsoleFormatter : ConsoleFormatter
internal class CommandInputConsoleFormatter(ConsoleWriter consoleWriter)
: ConsoleFormatter(consoleWriter)
{
public CommandInputConsoleFormatter(ConsoleWriter consoleWriter)
: base(consoleWriter) { }
private void WriteCommandLineArguments(CommandInput commandInput)
{
Write("Command-line:");
@@ -94,4 +92,7 @@ internal static class CommandInputConsoleFormatterExtensions
this ConsoleWriter consoleWriter,
CommandInput commandInput
) => new CommandInputConsoleFormatter(consoleWriter).WriteCommandInput(commandInput);
public static void WriteCommandInput(this IConsole console, CommandInput commandInput) =>
console.Output.WriteCommandInput(commandInput);
}

View File

@@ -3,50 +3,46 @@ using CliFx.Infrastructure;
namespace CliFx.Formatting;
internal class ConsoleFormatter
internal class ConsoleFormatter(ConsoleWriter consoleWriter)
{
private readonly ConsoleWriter _consoleWriter;
private int _column;
private int _row;
public bool IsEmpty => _column == 0 && _row == 0;
public ConsoleFormatter(ConsoleWriter consoleWriter) => _consoleWriter = consoleWriter;
public void Write(string? value)
{
_consoleWriter.Write(value);
consoleWriter.Write(value);
_column += value?.Length ?? 0;
}
public void Write(char value)
{
_consoleWriter.Write(value);
consoleWriter.Write(value);
_column++;
}
public void Write(ConsoleColor foregroundColor, string? value)
{
using (_consoleWriter.Console.WithForegroundColor(foregroundColor))
using (consoleWriter.Console.WithForegroundColor(foregroundColor))
Write(value);
}
public void Write(ConsoleColor foregroundColor, char value)
{
using (_consoleWriter.Console.WithForegroundColor(foregroundColor))
using (consoleWriter.Console.WithForegroundColor(foregroundColor))
Write(value);
}
public void Write(ConsoleColor foregroundColor, ConsoleColor backgroundColor, string? value)
{
using (_consoleWriter.Console.WithColors(foregroundColor, backgroundColor))
using (consoleWriter.Console.WithColors(foregroundColor, backgroundColor))
Write(value);
}
public void WriteLine()
{
_consoleWriter.WriteLine();
consoleWriter.WriteLine();
_column = 0;
_row++;
}

View File

@@ -7,11 +7,9 @@ using CliFx.Utils.Extensions;
namespace CliFx.Formatting;
internal class ExceptionConsoleFormatter : ConsoleFormatter
internal class ExceptionConsoleFormatter(ConsoleWriter consoleWriter)
: ConsoleFormatter(consoleWriter)
{
public ExceptionConsoleFormatter(ConsoleWriter consoleWriter)
: base(consoleWriter) { }
private void WriteStackFrame(StackFrame stackFrame, int indentLevel)
{
WriteHorizontalMargin(2 + 4 * indentLevel);
@@ -124,4 +122,7 @@ internal static class ExceptionConsoleFormatterExtensions
{
public static void WriteException(this ConsoleWriter consoleWriter, Exception exception) =>
new ExceptionConsoleFormatter(consoleWriter).WriteException(exception);
public static void WriteException(this IConsole console, Exception exception) =>
console.Error.WriteException(exception);
}

View File

@@ -9,16 +9,9 @@ using CliFx.Utils.Extensions;
namespace CliFx.Formatting;
internal class HelpConsoleFormatter : ConsoleFormatter
internal class HelpConsoleFormatter(ConsoleWriter consoleWriter, HelpContext context)
: ConsoleFormatter(consoleWriter)
{
private readonly HelpContext _context;
public HelpConsoleFormatter(ConsoleWriter consoleWriter, HelpContext context)
: base(consoleWriter)
{
_context = context;
}
private void WriteHeader(string text)
{
Write(ConsoleColor.White, text.ToUpperInvariant());
@@ -27,13 +20,13 @@ internal class HelpConsoleFormatter : ConsoleFormatter
private void WriteCommandInvocation()
{
Write(_context.ApplicationMetadata.ExecutableName);
Write(context.ApplicationMetadata.ExecutableName);
// Command name
if (!string.IsNullOrWhiteSpace(_context.CommandSchema.Name))
if (!string.IsNullOrWhiteSpace(context.CommandSchema.Name))
{
Write(' ');
Write(ConsoleColor.Cyan, _context.CommandSchema.Name);
Write(ConsoleColor.Cyan, context.CommandSchema.Name);
}
}
@@ -43,16 +36,16 @@ internal class HelpConsoleFormatter : ConsoleFormatter
WriteVerticalMargin();
// Title and version
Write(ConsoleColor.White, _context.ApplicationMetadata.Title);
Write(ConsoleColor.White, context.ApplicationMetadata.Title);
Write(' ');
Write(ConsoleColor.Yellow, _context.ApplicationMetadata.Version);
Write(ConsoleColor.Yellow, context.ApplicationMetadata.Version);
WriteLine();
// Description
if (!string.IsNullOrWhiteSpace(_context.ApplicationMetadata.Description))
if (!string.IsNullOrWhiteSpace(context.ApplicationMetadata.Description))
{
WriteHorizontalMargin();
Write(_context.ApplicationMetadata.Description);
Write(context.ApplicationMetadata.Description);
WriteLine();
}
}
@@ -72,7 +65,7 @@ internal class HelpConsoleFormatter : ConsoleFormatter
Write(' ');
// Parameters
foreach (var parameter in _context.CommandSchema.Parameters.OrderBy(p => p.Order))
foreach (var parameter in context.CommandSchema.Parameters.OrderBy(p => p.Order))
{
Write(
ConsoleColor.DarkCyan,
@@ -82,7 +75,7 @@ internal class HelpConsoleFormatter : ConsoleFormatter
}
// Required options
foreach (var option in _context.CommandSchema.Options.Where(o => o.IsRequired))
foreach (var option in context.CommandSchema.Options.Where(o => o.IsRequired))
{
Write(
ConsoleColor.Yellow,
@@ -97,7 +90,7 @@ internal class HelpConsoleFormatter : ConsoleFormatter
}
// Placeholder for non-required options
if (_context.CommandSchema.Options.Any(o => !o.IsRequired))
if (context.CommandSchema.Options.Any(o => !o.IsRequired))
{
Write(ConsoleColor.Yellow, "[options]");
}
@@ -106,9 +99,9 @@ internal class HelpConsoleFormatter : ConsoleFormatter
}
// Child command usage
var childCommandSchemas = _context
.ApplicationSchema
.GetChildCommands(_context.CommandSchema.Name);
var childCommandSchemas = context.ApplicationSchema.GetChildCommands(
context.CommandSchema.Name
);
if (childCommandSchemas.Any())
{
@@ -130,7 +123,7 @@ internal class HelpConsoleFormatter : ConsoleFormatter
private void WriteCommandDescription()
{
if (string.IsNullOrWhiteSpace(_context.CommandSchema.Description))
if (string.IsNullOrWhiteSpace(context.CommandSchema.Description))
return;
if (!IsEmpty)
@@ -140,13 +133,13 @@ internal class HelpConsoleFormatter : ConsoleFormatter
WriteHorizontalMargin();
Write(_context.CommandSchema.Description);
Write(context.CommandSchema.Description);
WriteLine();
}
private void WriteCommandParameters()
{
if (!_context.CommandSchema.Parameters.Any())
if (!context.CommandSchema.Parameters.Any())
return;
if (!IsEmpty)
@@ -154,7 +147,7 @@ internal class HelpConsoleFormatter : ConsoleFormatter
WriteHeader("Parameters");
foreach (var parameterSchema in _context.CommandSchema.Parameters.OrderBy(p => p.Order))
foreach (var parameterSchema in context.CommandSchema.Parameters.OrderBy(p => p.Order))
{
if (parameterSchema.IsRequired)
{
@@ -224,7 +217,7 @@ internal class HelpConsoleFormatter : ConsoleFormatter
WriteHeader("Options");
foreach (
var optionSchema in _context.CommandSchema.Options.OrderByDescending(o => o.IsRequired)
var optionSchema in context.CommandSchema.Options.OrderByDescending(o => o.IsRequired)
)
{
if (optionSchema.IsRequired)
@@ -314,7 +307,7 @@ internal class HelpConsoleFormatter : ConsoleFormatter
private void WriteDefaultValue(IMemberSchema schema)
{
var defaultValue = _context.CommandDefaultValues.GetValueOrDefault(schema);
var defaultValue = context.CommandDefaultValues.GetValueOrDefault(schema);
if (defaultValue is not null)
{
// Non-Scalar
@@ -365,9 +358,8 @@ internal class HelpConsoleFormatter : ConsoleFormatter
private void WriteCommandChildren()
{
var childCommandSchemas = _context
.ApplicationSchema
.GetChildCommands(_context.CommandSchema.Name)
var childCommandSchemas = context
.ApplicationSchema.GetChildCommands(context.CommandSchema.Name)
.OrderBy(a => a.Name, StringComparer.Ordinal)
.ToArray();
@@ -386,7 +378,7 @@ internal class HelpConsoleFormatter : ConsoleFormatter
Write(
ConsoleColor.Cyan,
// Relative to current command
childCommandSchema.Name?.Substring(_context.CommandSchema.Name?.Length ?? 0).Trim()
childCommandSchema.Name?.Substring(context.CommandSchema.Name?.Length ?? 0).Trim()
);
WriteColumnMargin();
@@ -399,9 +391,8 @@ internal class HelpConsoleFormatter : ConsoleFormatter
}
// Child commands of child command
var grandChildCommandSchemas = _context
.ApplicationSchema
.GetChildCommands(childCommandSchema.Name)
var grandChildCommandSchemas = context
.ApplicationSchema.GetChildCommands(childCommandSchema.Name)
.OrderBy(c => c.Name, StringComparer.Ordinal)
.ToArray();
@@ -425,8 +416,7 @@ internal class HelpConsoleFormatter : ConsoleFormatter
ConsoleColor.Cyan,
// Relative to current command (not the parent)
grandChildCommandSchema
.Name
?.Substring(_context.CommandSchema.Name?.Length ?? 0)
.Name?.Substring(context.CommandSchema.Name?.Length ?? 0)
.Trim()
);
}
@@ -465,4 +455,7 @@ internal static class HelpConsoleFormatterExtensions
{
public static void WriteHelpText(this ConsoleWriter consoleWriter, HelpContext context) =>
new HelpConsoleFormatter(consoleWriter, context).WriteHelpText();
public static void WriteHelpText(this IConsole console, HelpContext context) =>
console.Output.WriteHelpText(context);
}

View File

@@ -3,26 +3,19 @@ using CliFx.Schema;
namespace CliFx.Formatting;
internal class HelpContext
{
public ApplicationMetadata ApplicationMetadata { get; }
public ApplicationSchema ApplicationSchema { get; }
public CommandSchema CommandSchema { get; }
public IReadOnlyDictionary<IMemberSchema, object?> CommandDefaultValues { get; }
public HelpContext(
internal class HelpContext(
ApplicationMetadata applicationMetadata,
ApplicationSchema applicationSchema,
CommandSchema commandSchema,
IReadOnlyDictionary<IMemberSchema, object?> commandDefaultValues
)
{
ApplicationMetadata = applicationMetadata;
ApplicationSchema = applicationSchema;
CommandSchema = commandSchema;
CommandDefaultValues = commandDefaultValues;
}
public ApplicationMetadata ApplicationMetadata { get; } = applicationMetadata;
public ApplicationSchema ApplicationSchema { get; } = applicationSchema;
public CommandSchema CommandSchema { get; } = commandSchema;
public IReadOnlyDictionary<IMemberSchema, object?> CommandDefaultValues { get; } =
commandDefaultValues;
}

View File

@@ -11,28 +11,20 @@ namespace CliFx.Infrastructure;
/// </summary>
// Both the underlying stream AND the stream reader must be synchronized!
// https://github.com/Tyrrrz/CliFx/issues/123
public partial class ConsoleReader : StreamReader
public class ConsoleReader(IConsole console, Stream stream, Encoding encoding)
: StreamReader(Stream.Synchronized(stream), encoding, false, 4096)
{
/// <summary>
/// Console that owns this stream.
/// </summary>
public IConsole Console { get; }
/// <summary>
/// Initializes an instance of <see cref="ConsoleReader" />.
/// </summary>
public ConsoleReader(IConsole console, Stream stream, Encoding encoding)
: base(stream, encoding, false, 4096)
{
Console = console;
}
/// <summary>
/// Initializes an instance of <see cref="ConsoleReader" />.
/// </summary>
public ConsoleReader(IConsole console, Stream stream)
: this(console, stream, System.Console.InputEncoding) { }
/// <summary>
/// Console that owns this stream.
/// </summary>
public IConsole Console { get; } = console;
// The following overrides are required to establish thread-safe behavior
// in methods deriving from StreamReader.
@@ -94,9 +86,3 @@ public partial class ConsoleReader : StreamReader
[ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)]
protected override void Dispose(bool disposing) => base.Dispose(disposing);
}
public partial class ConsoleReader
{
internal static ConsoleReader Create(IConsole console, Stream stream) =>
new(console, Stream.Synchronized(stream));
}

View File

@@ -12,20 +12,16 @@ namespace CliFx.Infrastructure;
/// </summary>
// Both the underlying stream AND the stream writer must be synchronized!
// https://github.com/Tyrrrz/CliFx/issues/123
public partial class ConsoleWriter : StreamWriter
public class ConsoleWriter : StreamWriter
{
/// <summary>
/// Console that owns this stream.
/// </summary>
public IConsole Console { get; }
/// <summary>
/// Initializes an instance of <see cref="ConsoleWriter" />.
/// </summary>
public ConsoleWriter(IConsole console, Stream stream, Encoding encoding)
: base(stream, encoding.WithoutPreamble(), 256)
: base(Stream.Synchronized(stream), encoding.WithoutPreamble(), 256)
{
Console = console;
AutoFlush = true;
}
/// <summary>
@@ -34,6 +30,11 @@ public partial class ConsoleWriter : StreamWriter
public ConsoleWriter(IConsole console, Stream stream)
: this(console, stream, System.Console.OutputEncoding) { }
/// <summary>
/// Console that owns this stream.
/// </summary>
public IConsole Console { get; }
// The following overrides are required to establish thread-safe behavior
// in methods deriving from StreamWriter.
@@ -44,7 +45,7 @@ public partial class ConsoleWriter : StreamWriter
/// <inheritdoc />
[ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)]
public override void Write(char[] buffer) => base.Write(buffer);
public override void Write(char[]? buffer) => base.Write(buffer);
/// <inheritdoc />
[ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)]
@@ -146,7 +147,7 @@ public partial class ConsoleWriter : StreamWriter
/// <inheritdoc />
[ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)]
public override void WriteLine(char[] buffer) => base.WriteLine(buffer);
public override void WriteLine(char[]? buffer) => base.WriteLine(buffer);
/// <inheritdoc />
[ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)]
@@ -268,9 +269,3 @@ public partial class ConsoleWriter : StreamWriter
[ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)]
protected override void Dispose(bool disposing) => base.Dispose(disposing);
}
public partial class ConsoleWriter
{
internal static ConsoleWriter Create(IConsole console, Stream stream) =>
new(console, Stream.Synchronized(stream)) { AutoFlush = true };
}

View File

@@ -14,14 +14,20 @@ public class DefaultTypeActivator : ITypeActivator
{
try
{
return Activator.CreateInstance(type);
return Activator.CreateInstance(type)
?? throw CliFxException.InternalError(
$"""
Failed to create an instance of type `{type.FullName}`, received <null> instead.
This may be caused by the type's constructor being trimmed away.
"""
);
}
// Only catch MemberAccessException because the constructor can throw for its own reasons too
catch (MemberAccessException ex)
{
throw CliFxException.InternalError(
$"""
Failed to create an instance of type `{type.FullName}`, could not access the constructor.
Failed to create an instance of type `{type.FullName}` because an appropriate constructor is not available.
Default type activator is only capable of instantiating a type if it has a public parameterless constructor.
To fix this, either add a parameterless constructor to the type or configure a custom activator for the application.
""",

View File

@@ -6,24 +6,12 @@ namespace CliFx.Infrastructure;
/// <summary>
/// Implementation of <see cref="ITypeActivator" /> that instantiates an object by using a predefined delegate.
/// </summary>
public class DelegateTypeActivator : ITypeActivator
public class DelegateTypeActivator(Func<Type, object> createInstance) : ITypeActivator
{
private readonly Func<Type, object> _createInstance;
/// <summary>
/// Initializes an instance of <see cref="DelegateTypeActivator" />.
/// </summary>
public DelegateTypeActivator(Func<Type, object> createInstance) =>
_createInstance = createInstance;
/// <inheritdoc />
public object CreateInstance(Type type)
{
var instance = _createInstance(type);
if (instance is null)
{
throw CliFxException.InternalError(
public object CreateInstance(Type type) =>
createInstance(type)
?? throw CliFxException.InternalError(
$"""
Failed to create an instance of type `{type.FullName}`, received <null> instead.
To fix this, ensure that the provided type activator is configured correctly, as it's not expected to return <null>.
@@ -31,7 +19,3 @@ public class DelegateTypeActivator : ITypeActivator
"""
);
}
return instance;
}
}

View File

@@ -6,15 +6,24 @@ using System.Threading;
namespace CliFx.Infrastructure;
/// <summary>
/// Implementation of <see cref="IConsole" /> that uses the provided fake
/// standard input, output, and error streams.
/// Use this implementation in tests to verify command interactions with the console.
/// Implementation of <see cref="IConsole" /> that uses the provided fake standard input, output, and error streams.
/// Use this implementation in tests to verify how a command interacts with the console.
/// </summary>
public class FakeConsole : IConsole, IDisposable
{
private readonly CancellationTokenSource _cancellationTokenSource = new();
private readonly ConcurrentQueue<ConsoleKeyInfo> _keys = new();
/// <summary>
/// Initializes an instance of <see cref="FakeConsole" />.
/// </summary>
public FakeConsole(Stream? input = null, Stream? output = null, Stream? error = null)
{
Input = new ConsoleReader(this, input ?? Stream.Null);
Output = new ConsoleWriter(this, output ?? Stream.Null);
Error = new ConsoleWriter(this, error ?? Stream.Null);
}
/// <inheritdoc />
public ConsoleReader Input { get; }
@@ -52,14 +61,9 @@ public class FakeConsole : IConsole, IDisposable
public int CursorTop { get; set; }
/// <summary>
/// Initializes an instance of <see cref="FakeConsole" />.
/// Enqueues a simulated key press, which can then be read by calling <see cref="ReadKey" />.
/// </summary>
public FakeConsole(Stream? input = null, Stream? output = null, Stream? error = null)
{
Input = ConsoleReader.Create(this, input ?? Stream.Null);
Output = ConsoleWriter.Create(this, output ?? Stream.Null);
Error = ConsoleWriter.Create(this, error ?? Stream.Null);
}
public void EnqueueKey(ConsoleKeyInfo key) => _keys.Enqueue(key);
/// <inheritdoc />
public ConsoleKeyInfo ReadKey(bool intercept = false) =>
@@ -70,11 +74,6 @@ public class FakeConsole : IConsole, IDisposable
+ $"Use the `{nameof(EnqueueKey)}(...)` method to simulate a key press."
);
/// <summary>
/// Enqueues a simulated key press, which can then be read by calling <see cref="ReadKey" />.
/// </summary>
public void EnqueueKey(ConsoleKeyInfo key) => _keys.Enqueue(key);
/// <inheritdoc />
public void ResetColor()
{
@@ -85,11 +84,8 @@ public class FakeConsole : IConsole, IDisposable
/// <inheritdoc />
public void Clear() { }
/// <inheritdoc />
public CancellationToken RegisterCancellationHandler() => _cancellationTokenSource.Token;
/// <summary>
/// Sends a cancellation signal to the currently executing command.
/// Simulates a cancellation request.
/// </summary>
/// <remarks>
/// If the command is not cancellation-aware (i.e. it doesn't call <see cref="IConsole.RegisterCancellationHandler" />),
@@ -108,6 +104,9 @@ public class FakeConsole : IConsole, IDisposable
}
}
/// <inheritdoc />
public CancellationToken RegisterCancellationHandler() => _cancellationTokenSource.Token;
/// <inheritdoc />
public virtual void Dispose() => _cancellationTokenSource.Dispose();
}

View File

@@ -3,9 +3,9 @@
namespace CliFx.Infrastructure;
/// <summary>
/// Implementation of <see cref="IConsole" /> that uses fake
/// standard input, output, and error streams backed by in-memory stores.
/// Use this implementation in tests to verify command interactions with the console.
/// Implementation of <see cref="IConsole" /> that uses fake standard input, output, and error streams
/// backed by in-memory stores.
/// Use this implementation in tests to verify how a command interacts with the console.
/// </summary>
public class FakeInMemoryConsole : FakeConsole
{

View File

@@ -5,47 +5,47 @@ using CliFx.Utils;
namespace CliFx.Infrastructure;
/// <summary>
/// Abstraction for the console layer.
/// Abstraction for interacting with the console layer.
/// </summary>
public interface IConsole
{
/// <summary>
/// Input stream (stdin).
/// Console's standard input stream.
/// </summary>
ConsoleReader Input { get; }
/// <summary>
/// Gets a value that indicates whether input has been redirected from the standard input stream.
/// Whether the input stream has been redirected.
/// </summary>
bool IsInputRedirected { get; }
/// <summary>
/// Output stream (stdout).
/// Console's standard output stream.
/// </summary>
ConsoleWriter Output { get; }
/// <summary>
/// Gets a value that indicates whether output has been redirected from the standard output stream.
/// Whether the output stream has been redirected.
/// </summary>
bool IsOutputRedirected { get; }
/// <summary>
/// Error stream (stderr).
/// Console's standard error stream.
/// </summary>
ConsoleWriter Error { get; }
/// <summary>
/// Gets a value that indicates whether error output has been redirected from the standard error stream.
/// Whether the error stream has been redirected.
/// </summary>
bool IsErrorRedirected { get; }
/// <summary>
/// Gets or sets the foreground color of the console
/// Gets or sets the current foreground color of the console.
/// </summary>
ConsoleColor ForegroundColor { get; set; }
/// <summary>
/// Gets or sets the background color of the console.
/// Gets or sets the current background color of the console.
/// </summary>
ConsoleColor BackgroundColor { get; set; }
@@ -108,6 +108,43 @@ public interface IConsole
/// </summary>
public static class ConsoleExtensions
{
/// <summary>
/// Writes a string to the console's output stream.
/// </summary>
public static void Write(this IConsole console, string? value) => console.Output.Write(value);
/// <summary>
/// Writes an object to the console's output stream.
/// </summary>
public static void Write(this IConsole console, object? value) => console.Output.Write(value);
/// <summary>
/// Writes an empty line to the console's output stream.
/// </summary>
public static void WriteLine(this IConsole console) => console.Output.WriteLine();
/// <summary>
/// Writes a string to the console's output stream, followed by a line terminator.
/// </summary>
public static void WriteLine(this IConsole console, string? value) =>
console.Output.WriteLine(value);
/// <summary>
/// Writes an object to the console's output stream, followed by a line terminator.
/// </summary>
public static void WriteLine(this IConsole console, object? value) =>
console.Output.WriteLine(value);
/// <summary>
/// Reads a single character from the console's input stream.
/// </summary>
public static int Read(this IConsole console) => console.Input.Read();
/// <summary>
/// Reads a line from the console's input stream.
/// </summary>
public static string? ReadLine(this IConsole console) => console.Input.ReadLine();
/// <summary>
/// Sets the specified foreground color and returns an <see cref="IDisposable" />
/// that will reset the color back to its previous value upon disposal.

View File

@@ -10,6 +10,16 @@ public class SystemConsole : IConsole, IDisposable
{
private CancellationTokenSource? _cancellationTokenSource;
/// <summary>
/// Initializes an instance of <see cref="SystemConsole" />.
/// </summary>
public SystemConsole()
{
Input = new ConsoleReader(this, Console.OpenStandardInput());
Output = new ConsoleWriter(this, Console.OpenStandardOutput());
Error = new ConsoleWriter(this, Console.OpenStandardError());
}
/// <inheritdoc />
public ConsoleReader Input { get; }
@@ -70,16 +80,6 @@ public class SystemConsole : IConsole, IDisposable
set => Console.CursorTop = value;
}
/// <summary>
/// Initializes an instance of <see cref="SystemConsole" />.
/// </summary>
public SystemConsole()
{
Input = ConsoleReader.Create(this, Console.OpenStandardInput());
Output = ConsoleWriter.Create(this, Console.OpenStandardOutput());
Error = ConsoleWriter.Create(this, Console.OpenStandardError());
}
/// <inheritdoc />
public ConsoleKeyInfo ReadKey(bool intercept = false) => Console.ReadKey(intercept);

View File

@@ -5,17 +5,24 @@ using CliFx.Utils.Extensions;
namespace CliFx.Input;
internal partial class CommandInput
internal partial class CommandInput(
string? commandName,
IReadOnlyList<DirectiveInput> directives,
IReadOnlyList<ParameterInput> parameters,
IReadOnlyList<OptionInput> options,
IReadOnlyList<EnvironmentVariableInput> environmentVariables
)
{
public string? CommandName { get; }
public string? CommandName { get; } = commandName;
public IReadOnlyList<DirectiveInput> Directives { get; }
public IReadOnlyList<DirectiveInput> Directives { get; } = directives;
public IReadOnlyList<ParameterInput> Parameters { get; }
public IReadOnlyList<ParameterInput> Parameters { get; } = parameters;
public IReadOnlyList<OptionInput> Options { get; }
public IReadOnlyList<OptionInput> Options { get; } = options;
public IReadOnlyList<EnvironmentVariableInput> EnvironmentVariables { get; }
public IReadOnlyList<EnvironmentVariableInput> EnvironmentVariables { get; } =
environmentVariables;
public bool HasArguments =>
!string.IsNullOrWhiteSpace(CommandName)
@@ -30,21 +37,6 @@ internal partial class CommandInput
public bool IsHelpOptionSpecified => Options.Any(o => o.IsHelpOption);
public bool IsVersionOptionSpecified => Options.Any(o => o.IsVersionOption);
public CommandInput(
string? commandName,
IReadOnlyList<DirectiveInput> directives,
IReadOnlyList<ParameterInput> parameters,
IReadOnlyList<OptionInput> options,
IReadOnlyList<EnvironmentVariableInput> environmentVariables
)
{
CommandName = commandName;
Directives = directives;
Parameters = parameters;
Options = options;
EnvironmentVariables = environmentVariables;
}
}
internal partial class CommandInput
@@ -168,7 +160,7 @@ internal partial class CommandInput
result.Add(new OptionInput(lastOptionIdentifier, lastOptionValues));
lastOptionIdentifier = argument[2..];
lastOptionValues = new List<string>();
lastOptionValues = [];
}
// Short name
else if (argument.StartsWith('-') && argument.Length > 1 && char.IsLetter(argument[1]))
@@ -180,7 +172,7 @@ internal partial class CommandInput
result.Add(new OptionInput(lastOptionIdentifier, lastOptionValues));
lastOptionIdentifier = identifier.AsString();
lastOptionValues = new List<string>();
lastOptionValues = [];
}
}
// Value

View File

@@ -2,15 +2,13 @@
namespace CliFx.Input;
internal class DirectiveInput
internal class DirectiveInput(string name)
{
public string Name { get; }
public string Name { get; } = name;
public bool IsDebugDirective =>
string.Equals(Name, "debug", StringComparison.OrdinalIgnoreCase);
public bool IsPreviewDirective =>
string.Equals(Name, "preview", StringComparison.OrdinalIgnoreCase);
public DirectiveInput(string name) => Name = name;
}

View File

@@ -3,17 +3,11 @@ using System.IO;
namespace CliFx.Input;
internal class EnvironmentVariableInput
internal class EnvironmentVariableInput(string name, string value)
{
public string Name { get; }
public string Name { get; } = name;
public string Value { get; }
public EnvironmentVariableInput(string name, string value)
{
Name = name;
Value = value;
}
public string Value { get; } = value;
public IReadOnlyList<string> SplitValues() => Value.Split(Path.PathSeparator);
}

View File

@@ -3,26 +3,20 @@ using CliFx.Schema;
namespace CliFx.Input;
internal class OptionInput
internal class OptionInput(string identifier, IReadOnlyList<string> values)
{
public string Identifier { get; }
public string Identifier { get; } = identifier;
public IReadOnlyList<string> Values { get; }
public IReadOnlyList<string> Values { get; } = values;
public bool IsHelpOption => OptionSchema.HelpOption.MatchesIdentifier(Identifier);
public bool IsHelpOption => OptionSchema.ImplicitHelpOption.MatchesIdentifier(Identifier);
public bool IsVersionOption => OptionSchema.VersionOption.MatchesIdentifier(Identifier);
public OptionInput(string identifier, IReadOnlyList<string> values)
{
Identifier = identifier;
Values = values;
}
public bool IsVersionOption => OptionSchema.ImplicitVersionOption.MatchesIdentifier(Identifier);
public string GetFormattedIdentifier() =>
Identifier switch
{
{ Length: >= 2 } => "--" + Identifier,
_ => '-' + Identifier
_ => '-' + Identifier,
};
}

View File

@@ -1,10 +1,8 @@
namespace CliFx.Input;
internal class ParameterInput
internal class ParameterInput(string value)
{
public string Value { get; }
public ParameterInput(string value) => Value = value;
public string Value { get; } = value;
public string GetFormattedIdentifier() => $"<{Value}>";
}

View File

@@ -5,14 +5,9 @@ using CliFx.Utils.Extensions;
namespace CliFx.Schema;
internal partial class ApplicationSchema
internal partial class ApplicationSchema(IReadOnlyList<CommandSchema> commands)
{
public IReadOnlyList<CommandSchema> Commands { get; }
public ApplicationSchema(IReadOnlyList<CommandSchema> commands)
{
Commands = commands;
}
public IReadOnlyList<CommandSchema> Commands { get; } = commands;
public IReadOnlyList<string> GetCommandNames() =>
Commands.Select(c => c.Name).WhereNotNullOrWhiteSpace().ToArray();
@@ -44,9 +39,10 @@ internal partial class ApplicationSchema
string.IsNullOrWhiteSpace(parentCommandName)
||
// Otherwise a command is a descendant if it starts with the same name segments
potentialParentCommandSchema
.Name
.StartsWith(parentCommandName + ' ', StringComparison.OrdinalIgnoreCase);
potentialParentCommandSchema.Name.StartsWith(
parentCommandName + ' ',
StringComparison.OrdinalIgnoreCase
);
if (isDescendant)
result.Add(potentialParentCommandSchema);

View File

@@ -5,18 +5,14 @@ using CliFx.Utils.Extensions;
namespace CliFx.Schema;
internal class BindablePropertyDescriptor : IPropertyDescriptor
internal class BindablePropertyDescriptor(PropertyInfo property) : IPropertyDescriptor
{
private readonly PropertyInfo _property;
public Type Type => property.PropertyType;
public Type Type => _property.PropertyType;
public BindablePropertyDescriptor(PropertyInfo property) => _property = property;
public object? GetValue(ICommand commandInstance) => _property.GetValue(commandInstance);
public object? GetValue(ICommand commandInstance) => property.GetValue(commandInstance);
public void SetValue(ICommand commandInstance, object? value) =>
_property.SetValue(commandInstance, value);
property.SetValue(commandInstance, value);
public IReadOnlyList<object?> GetValidValues()
{

View File

@@ -8,25 +8,7 @@ using CliFx.Utils.Extensions;
namespace CliFx.Schema;
internal partial class CommandSchema
{
public Type Type { get; }
public string? Name { get; }
public string? Description { get; }
public IReadOnlyList<ParameterSchema> Parameters { get; }
public IReadOnlyList<OptionSchema> Options { get; }
public bool IsDefault => string.IsNullOrWhiteSpace(Name);
public bool IsHelpOptionAvailable => Options.Contains(OptionSchema.HelpOption);
public bool IsVersionOptionAvailable => Options.Contains(OptionSchema.VersionOption);
public CommandSchema(
internal partial class CommandSchema(
Type type,
string? name,
string? description,
@@ -34,12 +16,22 @@ internal partial class CommandSchema
IReadOnlyList<OptionSchema> options
)
{
Type = type;
Name = name;
Description = description;
Parameters = parameters;
Options = options;
}
public Type Type { get; } = type;
public string? Name { get; } = name;
public string? Description { get; } = description;
public IReadOnlyList<ParameterSchema> Parameters { get; } = parameters;
public IReadOnlyList<OptionSchema> Options { get; } = options;
public bool IsDefault => string.IsNullOrWhiteSpace(Name);
public bool IsImplicitHelpOptionAvailable => Options.Contains(OptionSchema.ImplicitHelpOption);
public bool IsImplicitVersionOptionAvailable =>
Options.Contains(OptionSchema.ImplicitVersionOption);
public bool MatchesName(string? name) =>
!string.IsNullOrWhiteSpace(Name)
@@ -83,10 +75,6 @@ internal partial class CommandSchema
var name = attribute?.Name?.Trim();
var description = attribute?.Description?.Trim();
var implicitOptionSchemas = string.IsNullOrWhiteSpace(name)
? new[] { OptionSchema.HelpOption, OptionSchema.VersionOption }
: new[] { OptionSchema.HelpOption };
var properties = type
// Get properties directly on the command type
.GetProperties()
@@ -95,10 +83,14 @@ internal partial class CommandSchema
type.GetInterfaces()
// Only interfaces implementing ICommand for explicitness
.Where(i => i != typeof(ICommand) && i.IsAssignableTo(typeof(ICommand)))
.SelectMany(
i =>
.SelectMany(i =>
i.GetProperties()
.Where(p => !p.GetMethod.IsAbstract && !p.SetMethod.IsAbstract)
.Where(p =>
p.GetMethod is not null
&& !p.GetMethod.IsAbstract
&& p.SetMethod is not null
&& !p.SetMethod.IsAbstract
)
)
)
.ToArray();
@@ -108,11 +100,25 @@ internal partial class CommandSchema
.WhereNotNull()
.ToArray();
var optionSchemas = properties
.Select(OptionSchema.TryResolve)
.WhereNotNull()
.Concat(implicitOptionSchemas)
.ToArray();
var optionSchemas = properties.Select(OptionSchema.TryResolve).WhereNotNull().ToList();
// Include implicit options, if appropriate
var isImplicitHelpOptionAvailable =
// If the command implements its own help option, don't include the implicit one
!optionSchemas.Any(o => o.MatchesShortName('h') || o.MatchesName("help"));
if (isImplicitHelpOptionAvailable)
optionSchemas.Add(OptionSchema.ImplicitHelpOption);
var isImplicitVersionOptionAvailable =
// Only the default command can have the version option
string.IsNullOrWhiteSpace(name)
&&
// If the command implements its own version option, don't include the implicit one
!optionSchemas.Any(o => o.MatchesName("version"));
if (isImplicitVersionOptionAvailable)
optionSchemas.Add(OptionSchema.ImplicitVersionOption);
return new CommandSchema(type, name, description, parameterSchemas, optionSchemas);
}

View File

@@ -21,6 +21,6 @@ internal static class MemberSchemaExtensions
{
ParameterSchema => "Parameter",
OptionSchema => "Option",
_ => throw new ArgumentOutOfRangeException(nameof(memberSchema))
_ => throw new ArgumentOutOfRangeException(nameof(memberSchema)),
};
}

View File

@@ -7,25 +7,7 @@ using CliFx.Utils.Extensions;
namespace CliFx.Schema;
internal partial class OptionSchema : IMemberSchema
{
public IPropertyDescriptor Property { get; }
public string? Name { get; }
public char? ShortName { get; }
public string? EnvironmentVariable { get; }
public bool IsRequired { get; }
public string? Description { get; }
public Type? ConverterType { get; }
public IReadOnlyList<Type> ValidatorTypes { get; }
public OptionSchema(
internal partial class OptionSchema(
IPropertyDescriptor property,
string? name,
char? shortName,
@@ -34,17 +16,23 @@ internal partial class OptionSchema : IMemberSchema
string? description,
Type? converterType,
IReadOnlyList<Type> validatorTypes
)
) : IMemberSchema
{
Property = property;
Name = name;
ShortName = shortName;
EnvironmentVariable = environmentVariable;
IsRequired = isRequired;
Description = description;
ConverterType = converterType;
ValidatorTypes = validatorTypes;
}
public IPropertyDescriptor Property { get; } = property;
public string? Name { get; } = name;
public char? ShortName { get; } = shortName;
public string? EnvironmentVariable { get; } = environmentVariable;
public bool IsRequired { get; } = isRequired;
public string? Description { get; } = description;
public Type? ConverterType { get; } = converterType;
public IReadOnlyList<Type> ValidatorTypes { get; } = validatorTypes;
public bool MatchesName(string? name) =>
!string.IsNullOrWhiteSpace(Name)
@@ -115,7 +103,7 @@ internal partial class OptionSchema
internal partial class OptionSchema
{
public static OptionSchema HelpOption { get; } =
public static OptionSchema ImplicitHelpOption { get; } =
new(
NullPropertyDescriptor.Instance,
"help",
@@ -127,7 +115,7 @@ internal partial class OptionSchema
Array.Empty<Type>()
);
public static OptionSchema VersionOption { get; } =
public static OptionSchema ImplicitVersionOption { get; } =
new(
NullPropertyDescriptor.Instance,
"version",

View File

@@ -6,23 +6,7 @@ using CliFx.Utils.Extensions;
namespace CliFx.Schema;
internal partial class ParameterSchema : IMemberSchema
{
public IPropertyDescriptor Property { get; }
public int Order { get; }
public string Name { get; }
public bool IsRequired { get; }
public string? Description { get; }
public Type? ConverterType { get; }
public IReadOnlyList<Type> ValidatorTypes { get; }
public ParameterSchema(
internal partial class ParameterSchema(
IPropertyDescriptor property,
int order,
string name,
@@ -30,16 +14,21 @@ internal partial class ParameterSchema : IMemberSchema
string? description,
Type? converterType,
IReadOnlyList<Type> validatorTypes
)
) : IMemberSchema
{
Property = property;
Order = order;
Name = name;
IsRequired = isRequired;
Description = description;
ConverterType = converterType;
ValidatorTypes = validatorTypes;
}
public IPropertyDescriptor Property { get; } = property;
public int Order { get; } = order;
public string Name { get; } = name;
public bool IsRequired { get; } = isRequired;
public string? Description { get; } = description;
public Type? ConverterType { get; } = converterType;
public IReadOnlyList<Type> ValidatorTypes { get; } = validatorTypes;
public string GetFormattedIdentifier() => Property.IsScalar() ? $"<{Name}>" : $"<{Name}...>";
}

Some files were not shown because too many files have changed in this diff Show More