34 Commits

Author SHA1 Message Date
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 1063 additions and 1684 deletions

View File

@@ -62,12 +62,14 @@ body:
required: true required: true
- label: I have provided a descriptive title for this issue - label: I have provided a descriptive title for this issue
required: true 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 required: true
- label: I have provided all the information needed to reproduce this bug as efficiently as possible - label: I have provided all the information needed to reproduce this bug as efficiently as possible
required: true required: true
- label: I have sponsored this project - label: I have sponsored this project
required: false 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 - type: markdown
attributes: 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 required: false
default: false default: false
push: push:
branches:
- master
tags:
- "*"
pull_request: pull_request:
branches:
- master
jobs: jobs:
main: main:
uses: Tyrrrz/.github/.github/workflows/nuget.yml@master uses: Tyrrrz/.github/.github/workflows/nuget.yml@master
with: with:
dotnet-version: 8.0.x deploy: ${{ inputs.deploy || github.ref_type == 'tag' }}
package-version: ${{ inputs.package-version }} package-version: ${{ inputs.package-version || (github.ref_type == 'tag' && github.ref_name) || format('0.0.0-ci-{0}', github.sha) }}
# Deploy only on tags by default, unless deploy is explicitly requested dotnet-version: 9.0.x
deploy-on-tags-only: ${{ !(github.event_name == 'workflow_dispatch' && inputs.deploy) }}
secrets: secrets:
CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}
NUGET_TOKEN: ${{ secrets.NUGET_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"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<TargetFramework>net8.0</TargetFramework> <TargetFramework>net9.0</TargetFramework>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
@@ -9,15 +9,15 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Basic.Reference.Assemblies.Net70" Version="1.4.5" /> <PackageReference Include="Basic.Reference.Assemblies.Net80" Version="1.8.0" />
<PackageReference Include="coverlet.collector" Version="6.0.0" PrivateAssets="all" /> <PackageReference Include="coverlet.collector" Version="6.0.4" PrivateAssets="all" />
<PackageReference Include="CSharpier.MsBuild" Version="0.26.1" PrivateAssets="all" /> <PackageReference Include="CSharpier.MsBuild" Version="0.30.6" PrivateAssets="all" />
<PackageReference Include="GitHubActionsTestLogger" Version="2.3.3" PrivateAssets="all" /> <PackageReference Include="GitHubActionsTestLogger" Version="2.4.1" PrivateAssets="all" />
<PackageReference Include="FluentAssertions" Version="6.12.0" /> <PackageReference Include="FluentAssertions" Version="8.0.1" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0" /> <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.12.0" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.7.0" /> <PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.11.0" />
<PackageReference Include="xunit" Version="2.6.1" /> <PackageReference Include="xunit" Version="2.9.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.5.3" PrivateAssets="all" /> <PackageReference Include="xunit.runner.visualstudio" Version="3.0.1" PrivateAssets="all" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>

View File

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

View File

@@ -23,7 +23,7 @@ public class OptionMustHaveValidValidatorsAnalyzerSpecs
[Command] [Command]
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
[CommandOption("foo", Validators = new[] {typeof(MyValidator)})] [CommandOption("foo", Validators = new[] { typeof(MyValidator) })]
public string? Foo { get; init; } public string? Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
@@ -48,7 +48,7 @@ public class OptionMustHaveValidValidatorsAnalyzerSpecs
[Command] [Command]
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
[CommandOption("foo", Validators = new[] {typeof(MyValidator)})] [CommandOption("foo", Validators = new[] { typeof(MyValidator) })]
public string? Foo { get; init; } public string? Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
@@ -73,7 +73,7 @@ public class OptionMustHaveValidValidatorsAnalyzerSpecs
[Command] [Command]
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
[CommandOption("foo", Validators = new[] {typeof(MyValidator)})] [CommandOption("foo", Validators = new[] { typeof(MyValidator) })]
public string? Foo { get; init; } public string? Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;

View File

@@ -23,7 +23,7 @@ public class ParameterMustHaveValidValidatorsAnalyzerSpecs
[Command] [Command]
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
[CommandParameter(0, Validators = new[] {typeof(MyValidator)})] [CommandParameter(0, Validators = new[] { typeof(MyValidator) })]
public required string Foo { get; init; } public required string Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
@@ -48,7 +48,7 @@ public class ParameterMustHaveValidValidatorsAnalyzerSpecs
[Command] [Command]
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
[CommandParameter(0, Validators = new[] {typeof(MyValidator)})] [CommandParameter(0, Validators = new[] { typeof(MyValidator) })]
public required string Foo { get; init; } public required string Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
@@ -73,7 +73,7 @@ public class ParameterMustHaveValidValidatorsAnalyzerSpecs
[Command] [Command]
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
[CommandParameter(0, Validators = new[] {typeof(MyValidator)})] [CommandParameter(0, Validators = new[] { typeof(MyValidator) })]
public required string Foo { get; init; } public required string Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -9,7 +9,7 @@ namespace CliFx.Benchmarks;
[Orderer(SummaryOrderPolicy.FastestToSlowest)] [Orderer(SummaryOrderPolicy.FastestToSlowest)]
public partial class Benchmarks 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() => public static void Main() =>
BenchmarkRunner.Run<Benchmarks>( BenchmarkRunner.Run<Benchmarks>(

View File

@@ -2,18 +2,19 @@
<PropertyGroup> <PropertyGroup>
<OutputType>Exe</OutputType> <OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework> <TargetFramework>net9.0</TargetFramework>
<NuGetAudit>false</NuGetAudit>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="BenchmarkDotNet" Version="0.13.10" /> <PackageReference Include="BenchmarkDotNet" Version="0.14.0" />
<PackageReference Include="clipr" Version="1.6.1" /> <PackageReference Include="clipr" Version="1.6.1" />
<PackageReference Include="Cocona" Version="2.2.0" /> <PackageReference Include="Cocona" Version="2.2.0" />
<PackageReference Include="CommandLineParser" Version="2.9.1" /> <PackageReference Include="CommandLineParser" Version="2.9.1" />
<PackageReference Include="CSharpier.MsBuild" Version="0.26.1" PrivateAssets="all" /> <PackageReference Include="CSharpier.MsBuild" Version="0.30.6" PrivateAssets="all" />
<PackageReference Include="McMaster.Extensions.CommandLineUtils" Version="4.1.0" /> <PackageReference Include="McMaster.Extensions.CommandLineUtils" Version="4.1.1" />
<PackageReference Include="PowerArgs" Version="4.0.3" /> <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-beta4.22272.1" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>

View File

@@ -2,13 +2,13 @@
<PropertyGroup> <PropertyGroup>
<OutputType>Exe</OutputType> <OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework> <TargetFramework>net9.0</TargetFramework>
<ApplicationIcon>../favicon.ico</ApplicationIcon> <ApplicationIcon>../favicon.ico</ApplicationIcon>
</PropertyGroup> </PropertyGroup>
<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.Extensions.DependencyInjection" Version="8.0.0" /> <PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="9.0.1" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>

View File

@@ -9,10 +9,8 @@ using CliFx.Infrastructure;
namespace CliFx.Demo.Commands; namespace CliFx.Demo.Commands;
[Command("book add", Description = "Adds a book to the library.")] [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.")] [CommandParameter(0, Name = "title", Description = "Book title.")]
public required string Title { get; init; } public required string Title { get; init; }
@@ -20,52 +18,38 @@ public partial class BookAddCommand : ICommand
public required string Author { get; init; } public required string Author { get; init; }
[CommandOption("published", 'p', Description = "Book publish date.")] [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.")] [CommandOption("isbn", 'n', Description = "Book ISBN.")]
public Isbn Isbn { get; init; } = CreateRandomIsbn(); public Isbn Isbn { get; init; } =
new(
public BookAddCommand(LibraryProvider libraryProvider) Random.Shared.Next(0, 999),
{ Random.Shared.Next(0, 99),
_libraryProvider = libraryProvider; Random.Shared.Next(0, 99999),
} Random.Shared.Next(0, 99),
Random.Shared.Next(0, 9)
);
public ValueTask ExecuteAsync(IConsole console) public ValueTask ExecuteAsync(IConsole console)
{ {
if (_libraryProvider.TryGetBook(Title) is not null) if (libraryProvider.TryGetBook(Title) is not null)
throw new CommandException("Book already exists.", 10); throw new CommandException($"Book '{Title}' already exists.", 10);
var book = new Book(Title, Author, Published, Isbn); var book = new Book(Title, Author, Published, Isbn);
_libraryProvider.AddBook(book); libraryProvider.AddBook(book);
console.Output.WriteLine("Book added."); console.WriteLine($"Book '{Title}' added.");
console.Output.WriteBook(book); console.WriteBook(book);
return default; 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; namespace CliFx.Demo.Commands;
[Command("book", Description = "Retrieves a book from the library.")] [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.")] [CommandParameter(0, Name = "title", Description = "Title of the book to retrieve.")]
public required string Title { get; init; } public required string Title { get; init; }
public BookCommand(LibraryProvider libraryProvider)
{
_libraryProvider = libraryProvider;
}
public ValueTask ExecuteAsync(IConsole console) public ValueTask ExecuteAsync(IConsole console)
{ {
var book = _libraryProvider.TryGetBook(Title); var book = libraryProvider.TryGetBook(Title);
if (book is null) 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; return default;
} }

View File

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

View File

@@ -7,28 +7,21 @@ using CliFx.Infrastructure;
namespace CliFx.Demo.Commands; namespace CliFx.Demo.Commands;
[Command("book remove", Description = "Removes a book from the library.")] [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.")] [CommandParameter(0, Name = "title", Description = "Title of the book to remove.")]
public required string Title { get; init; } public required string Title { get; init; }
public BookRemoveCommand(LibraryProvider libraryProvider)
{
_libraryProvider = libraryProvider;
}
public ValueTask ExecuteAsync(IConsole console) public ValueTask ExecuteAsync(IConsole console)
{ {
var book = _libraryProvider.TryGetBook(Title); var book = libraryProvider.TryGetBook(Title);
if (book is null) 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; return default;
} }

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -9,11 +9,8 @@ using Xunit.Abstractions;
namespace CliFx.Tests; namespace CliFx.Tests;
public class ErrorReportingSpecs : SpecsBase public class ErrorReportingSpecs(ITestOutputHelper testOutput) : SpecsBase(testOutput)
{ {
public ErrorReportingSpecs(ITestOutputHelper testOutput)
: base(testOutput) { }
[Fact] [Fact]
public async Task I_can_throw_an_exception_in_a_command_to_report_an_error_with_a_stacktrace() 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; namespace CliFx.Tests;
public class HelpTextSpecs : SpecsBase public class HelpTextSpecs(ITestOutputHelper testOutput) : SpecsBase(testOutput)
{ {
public HelpTextSpecs(ITestOutputHelper testOutput)
: base(testOutput) { }
[Fact] [Fact]
public async Task I_can_request_the_help_text_by_running_the_application_without_arguments_if_the_default_command_is_not_defined() public async Task I_can_request_the_help_text_by_running_the_application_without_arguments_if_the_default_command_is_not_defined()
{ {
@@ -58,10 +55,7 @@ public class HelpTextSpecs : SpecsBase
.Build(); .Build();
// Act // Act
var exitCode = await application.RunAsync( var exitCode = await application.RunAsync(["--help"], new Dictionary<string, string>());
new[] { "--help" },
new Dictionary<string, string>()
);
// Assert // Assert
exitCode.Should().Be(0); exitCode.Should().Be(0);
@@ -98,10 +92,7 @@ public class HelpTextSpecs : SpecsBase
.Build(); .Build();
// Act // Act
var exitCode = await application.RunAsync( var exitCode = await application.RunAsync(["--help"], new Dictionary<string, string>());
new[] { "--help" },
new Dictionary<string, string>()
);
// Assert // Assert
exitCode.Should().Be(0); exitCode.Should().Be(0);
@@ -144,7 +135,7 @@ public class HelpTextSpecs : SpecsBase
// Act // Act
var exitCode = await application.RunAsync( var exitCode = await application.RunAsync(
new[] { "cmd", "--help" }, ["cmd", "--help"],
new Dictionary<string, string>() new Dictionary<string, string>()
); );
@@ -189,7 +180,7 @@ public class HelpTextSpecs : SpecsBase
// Act // Act
var exitCode = await application.RunAsync( var exitCode = await application.RunAsync(
new[] { "cmd", "sub", "--help" }, ["cmd", "sub", "--help"],
new Dictionary<string, string>() new Dictionary<string, string>()
); );
@@ -212,7 +203,7 @@ public class HelpTextSpecs : SpecsBase
// Act // Act
var exitCode = await application.RunAsync( var exitCode = await application.RunAsync(
new[] { "invalid-command", "--invalid-option" }, ["invalid-command", "--invalid-option"],
new Dictionary<string, string>() new Dictionary<string, string>()
); );
@@ -238,10 +229,7 @@ public class HelpTextSpecs : SpecsBase
.Build(); .Build();
// Act // Act
var exitCode = await application.RunAsync( var exitCode = await application.RunAsync(["--help"], new Dictionary<string, string>());
new[] { "--help" },
new Dictionary<string, string>()
);
// Assert // Assert
exitCode.Should().Be(0); exitCode.Should().Be(0);
@@ -271,10 +259,7 @@ public class HelpTextSpecs : SpecsBase
.Build(); .Build();
// Act // Act
var exitCode = await application.RunAsync( var exitCode = await application.RunAsync(["--help"], new Dictionary<string, string>());
new[] { "--help" },
new Dictionary<string, string>()
);
// Assert // Assert
exitCode.Should().Be(0); exitCode.Should().Be(0);
@@ -310,10 +295,7 @@ public class HelpTextSpecs : SpecsBase
.Build(); .Build();
// Act // Act
var exitCode = await application.RunAsync( var exitCode = await application.RunAsync(["--help"], new Dictionary<string, string>());
new[] { "--help" },
new Dictionary<string, string>()
);
// Assert // Assert
exitCode.Should().Be(0); exitCode.Should().Be(0);
@@ -352,10 +334,7 @@ public class HelpTextSpecs : SpecsBase
.Build(); .Build();
// Act // Act
var exitCode = await application.RunAsync( var exitCode = await application.RunAsync(["--help"], new Dictionary<string, string>());
new[] { "--help" },
new Dictionary<string, string>()
);
// Assert // Assert
exitCode.Should().Be(0); exitCode.Should().Be(0);
@@ -401,10 +380,7 @@ public class HelpTextSpecs : SpecsBase
.Build(); .Build();
// Act // Act
var exitCode = await application.RunAsync( var exitCode = await application.RunAsync(["--help"], new Dictionary<string, string>());
new[] { "--help" },
new Dictionary<string, string>()
);
// Assert // Assert
exitCode.Should().Be(0); exitCode.Should().Be(0);
@@ -443,10 +419,7 @@ public class HelpTextSpecs : SpecsBase
.Build(); .Build();
// Act // Act
var exitCode = await application.RunAsync( var exitCode = await application.RunAsync(["--help"], new Dictionary<string, string>());
new[] { "--help" },
new Dictionary<string, string>()
);
// Assert // Assert
exitCode.Should().Be(0); exitCode.Should().Be(0);
@@ -484,10 +457,7 @@ public class HelpTextSpecs : SpecsBase
.Build(); .Build();
// Act // Act
var exitCode = await application.RunAsync( var exitCode = await application.RunAsync(["--help"], new Dictionary<string, string>());
new[] { "--help" },
new Dictionary<string, string>()
);
// Assert // Assert
exitCode.Should().Be(0); exitCode.Should().Be(0);
@@ -526,10 +496,7 @@ public class HelpTextSpecs : SpecsBase
.Build(); .Build();
// Act // Act
var exitCode = await application.RunAsync( var exitCode = await application.RunAsync(["--help"], new Dictionary<string, string>());
new[] { "--help" },
new Dictionary<string, string>()
);
// Assert // Assert
exitCode.Should().Be(0); exitCode.Should().Be(0);
@@ -569,7 +536,7 @@ public class HelpTextSpecs : SpecsBase
// Act // Act
var exitCode = await application.RunAsync( var exitCode = await application.RunAsync(
new[] { "cmd", "--help" }, ["cmd", "--help"],
new Dictionary<string, string>() new Dictionary<string, string>()
); );
@@ -612,10 +579,7 @@ public class HelpTextSpecs : SpecsBase
.Build(); .Build();
// Act // Act
var exitCode = await application.RunAsync( var exitCode = await application.RunAsync(["--help"], new Dictionary<string, string>());
new[] { "--help" },
new Dictionary<string, string>()
);
// Assert // Assert
exitCode.Should().Be(0); exitCode.Should().Be(0);
@@ -668,10 +632,7 @@ public class HelpTextSpecs : SpecsBase
.Build(); .Build();
// Act // Act
var exitCode = await application.RunAsync( var exitCode = await application.RunAsync(["--help"], new Dictionary<string, string>());
new[] { "--help" },
new Dictionary<string, string>()
);
// Assert // Assert
exitCode.Should().Be(0); exitCode.Should().Be(0);
@@ -724,10 +685,7 @@ public class HelpTextSpecs : SpecsBase
.Build(); .Build();
// Act // Act
var exitCode = await application.RunAsync( var exitCode = await application.RunAsync(["--help"], new Dictionary<string, string>());
new[] { "--help" },
new Dictionary<string, string>()
);
// Assert // Assert
exitCode.Should().Be(0); exitCode.Should().Be(0);
@@ -780,10 +738,7 @@ public class HelpTextSpecs : SpecsBase
.Build(); .Build();
// Act // Act
var exitCode = await application.RunAsync( var exitCode = await application.RunAsync(["--help"], new Dictionary<string, string>());
new[] { "--help" },
new Dictionary<string, string>()
);
// Assert // Assert
exitCode.Should().Be(0); exitCode.Should().Be(0);
@@ -849,10 +804,7 @@ public class HelpTextSpecs : SpecsBase
.Build(); .Build();
// Act // Act
var exitCode = await application.RunAsync( var exitCode = await application.RunAsync(["--help"], new Dictionary<string, string>());
new[] { "--help" },
new Dictionary<string, string>()
);
// Assert // Assert
exitCode.Should().Be(0); exitCode.Should().Be(0);
@@ -930,10 +882,7 @@ public class HelpTextSpecs : SpecsBase
.Build(); .Build();
// Act // Act
var exitCode = await application.RunAsync( var exitCode = await application.RunAsync(["--help"], new Dictionary<string, string>());
new[] { "--help" },
new Dictionary<string, string>()
);
// Assert // Assert
exitCode.Should().Be(0); exitCode.Should().Be(0);
@@ -1004,10 +953,7 @@ public class HelpTextSpecs : SpecsBase
.Build(); .Build();
// Act // Act
var exitCode = await application.RunAsync( var exitCode = await application.RunAsync(["--help"], new Dictionary<string, string>());
new[] { "--help" },
new Dictionary<string, string>()
);
// Assert // Assert
exitCode.Should().Be(0); exitCode.Should().Be(0);
@@ -1038,10 +984,7 @@ public class HelpTextSpecs : SpecsBase
.Build(); .Build();
// Act // Act
var exitCode = await application.RunAsync( var exitCode = await application.RunAsync(["--version"], new Dictionary<string, string>());
new[] { "--version" },
new Dictionary<string, string>()
);
// Assert // Assert
exitCode.Should().Be(0); exitCode.Should().Be(0);

View File

@@ -9,11 +9,8 @@ using Xunit.Abstractions;
namespace CliFx.Tests; namespace CliFx.Tests;
public class OptionBindingSpecs : SpecsBase public class OptionBindingSpecs(ITestOutputHelper testOutput) : SpecsBase(testOutput)
{ {
public OptionBindingSpecs(ITestOutputHelper testOutput)
: base(testOutput) { }
[Fact] [Fact]
public async Task I_can_bind_an_option_to_a_property_and_get_the_value_from_the_corresponding_argument_by_name() 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) public ValueTask ExecuteAsync(IConsole console)
{ {
console.Output.WriteLine(Foo); console.WriteLine(Foo);
return default; return default;
} }
} }
@@ -42,10 +39,7 @@ public class OptionBindingSpecs : SpecsBase
.Build(); .Build();
// Act // Act
var exitCode = await application.RunAsync( var exitCode = await application.RunAsync(["--foo"], new Dictionary<string, string>());
new[] { "--foo" },
new Dictionary<string, string>()
);
// Assert // Assert
exitCode.Should().Be(0); exitCode.Should().Be(0);
@@ -69,7 +63,7 @@ public class OptionBindingSpecs : SpecsBase
public ValueTask ExecuteAsync(IConsole console) public ValueTask ExecuteAsync(IConsole console)
{ {
console.Output.WriteLine(Foo); console.WriteLine(Foo);
return default; return default;
} }
} }
@@ -82,7 +76,7 @@ public class OptionBindingSpecs : SpecsBase
.Build(); .Build();
// Act // Act
var exitCode = await application.RunAsync(new[] { "-f" }, new Dictionary<string, string>()); var exitCode = await application.RunAsync(["-f"], new Dictionary<string, string>());
// Assert // Assert
exitCode.Should().Be(0); exitCode.Should().Be(0);
@@ -109,8 +103,8 @@ public class OptionBindingSpecs : SpecsBase
public ValueTask ExecuteAsync(IConsole console) public ValueTask ExecuteAsync(IConsole console)
{ {
console.Output.WriteLine("Foo = " + Foo); console.WriteLine("Foo = " + Foo);
console.Output.WriteLine("Bar = " + Bar); console.WriteLine("Bar = " + Bar);
return default; return default;
} }
@@ -125,7 +119,7 @@ public class OptionBindingSpecs : SpecsBase
// Act // Act
var exitCode = await application.RunAsync( var exitCode = await application.RunAsync(
new[] { "--foo", "one", "--bar", "two" }, ["--foo", "one", "--bar", "two"],
new Dictionary<string, string>() new Dictionary<string, string>()
); );
@@ -154,8 +148,8 @@ public class OptionBindingSpecs : SpecsBase
public ValueTask ExecuteAsync(IConsole console) public ValueTask ExecuteAsync(IConsole console)
{ {
console.Output.WriteLine("Foo = " + Foo); console.WriteLine("Foo = " + Foo);
console.Output.WriteLine("Bar = " + Bar); console.WriteLine("Bar = " + Bar);
return default; return default;
} }
@@ -170,7 +164,7 @@ public class OptionBindingSpecs : SpecsBase
// Act // Act
var exitCode = await application.RunAsync( var exitCode = await application.RunAsync(
new[] { "-f", "one", "-b", "two" }, ["-f", "one", "-b", "two"],
new Dictionary<string, string>() new Dictionary<string, string>()
); );
@@ -199,8 +193,8 @@ public class OptionBindingSpecs : SpecsBase
public ValueTask ExecuteAsync(IConsole console) public ValueTask ExecuteAsync(IConsole console)
{ {
console.Output.WriteLine("Foo = " + Foo); console.WriteLine("Foo = " + Foo);
console.Output.WriteLine("Bar = " + Bar); console.WriteLine("Bar = " + Bar);
return default; return default;
} }
@@ -215,7 +209,7 @@ public class OptionBindingSpecs : SpecsBase
// Act // Act
var exitCode = await application.RunAsync( var exitCode = await application.RunAsync(
new[] { "-fb", "value" }, ["-fb", "value"],
new Dictionary<string, string>() new Dictionary<string, string>()
); );
@@ -242,7 +236,7 @@ public class OptionBindingSpecs : SpecsBase
public ValueTask ExecuteAsync(IConsole console) public ValueTask ExecuteAsync(IConsole console)
{ {
foreach (var i in Foo) foreach (var i in Foo)
console.Output.WriteLine(i); console.WriteLine(i);
return default; return default;
} }
@@ -257,7 +251,7 @@ public class OptionBindingSpecs : SpecsBase
// Act // Act
var exitCode = await application.RunAsync( var exitCode = await application.RunAsync(
new[] { "--foo", "one", "two", "three" }, ["--foo", "one", "two", "three"],
new Dictionary<string, string>() new Dictionary<string, string>()
); );
@@ -284,7 +278,7 @@ public class OptionBindingSpecs : SpecsBase
public ValueTask ExecuteAsync(IConsole console) public ValueTask ExecuteAsync(IConsole console)
{ {
foreach (var i in Foo) foreach (var i in Foo)
console.Output.WriteLine(i); console.WriteLine(i);
return default; return default;
} }
@@ -299,7 +293,7 @@ public class OptionBindingSpecs : SpecsBase
// Act // Act
var exitCode = await application.RunAsync( var exitCode = await application.RunAsync(
new[] { "-f", "one", "two", "three" }, ["-f", "one", "two", "three"],
new Dictionary<string, string>() new Dictionary<string, string>()
); );
@@ -326,7 +320,7 @@ public class OptionBindingSpecs : SpecsBase
public ValueTask ExecuteAsync(IConsole console) public ValueTask ExecuteAsync(IConsole console)
{ {
foreach (var i in Foo) foreach (var i in Foo)
console.Output.WriteLine(i); console.WriteLine(i);
return default; return default;
} }
@@ -341,7 +335,7 @@ public class OptionBindingSpecs : SpecsBase
// Act // Act
var exitCode = await application.RunAsync( var exitCode = await application.RunAsync(
new[] { "--foo", "one", "--foo", "two", "--foo", "three" }, ["--foo", "one", "--foo", "two", "--foo", "three"],
new Dictionary<string, string>() new Dictionary<string, string>()
); );
@@ -368,7 +362,7 @@ public class OptionBindingSpecs : SpecsBase
public ValueTask ExecuteAsync(IConsole console) public ValueTask ExecuteAsync(IConsole console)
{ {
foreach (var i in Foo) foreach (var i in Foo)
console.Output.WriteLine(i); console.WriteLine(i);
return default; return default;
} }
@@ -383,7 +377,7 @@ public class OptionBindingSpecs : SpecsBase
// Act // Act
var exitCode = await application.RunAsync( var exitCode = await application.RunAsync(
new[] { "-f", "one", "-f", "two", "-f", "three" }, ["-f", "one", "-f", "two", "-f", "three"],
new Dictionary<string, string>() new Dictionary<string, string>()
); );
@@ -410,7 +404,7 @@ public class OptionBindingSpecs : SpecsBase
public ValueTask ExecuteAsync(IConsole console) public ValueTask ExecuteAsync(IConsole console)
{ {
foreach (var i in Foo) foreach (var i in Foo)
console.Output.WriteLine(i); console.WriteLine(i);
return default; return default;
} }
@@ -425,7 +419,7 @@ public class OptionBindingSpecs : SpecsBase
// Act // Act
var exitCode = await application.RunAsync( var exitCode = await application.RunAsync(
new[] { "--foo", "one", "-f", "two", "--foo", "three" }, ["--foo", "one", "-f", "two", "--foo", "three"],
new Dictionary<string, string>() new Dictionary<string, string>()
); );
@@ -454,8 +448,8 @@ public class OptionBindingSpecs : SpecsBase
public ValueTask ExecuteAsync(IConsole console) public ValueTask ExecuteAsync(IConsole console)
{ {
console.Output.WriteLine("Foo = " + Foo); console.WriteLine("Foo = " + Foo);
console.Output.WriteLine("Bar = " + Bar); console.WriteLine("Bar = " + Bar);
return default; return default;
} }
@@ -470,7 +464,7 @@ public class OptionBindingSpecs : SpecsBase
// Act // Act
var exitCode = await application.RunAsync( var exitCode = await application.RunAsync(
new[] { "--foo", "one" }, ["--foo", "one"],
new Dictionary<string, string>() new Dictionary<string, string>()
); );
@@ -528,9 +522,9 @@ public class OptionBindingSpecs : SpecsBase
public ValueTask ExecuteAsync(IConsole console) public ValueTask ExecuteAsync(IConsole console)
{ {
console.Output.WriteLine("Foo = " + SharedContext.Foo); console.WriteLine("Foo = " + SharedContext.Foo);
console.Output.WriteLine("Bar = " + SharedContext.Bar); console.WriteLine("Bar = " + SharedContext.Bar);
console.Output.WriteLine("Baz = " + Baz); console.WriteLine("Baz = " + Baz);
return default; return default;
} }
@@ -544,7 +538,7 @@ public class OptionBindingSpecs : SpecsBase
.Build(); .Build();
// Act // Act
var exitCode = await application.RunAsync(new[] { "--foo", "42", "--bar", "--baz", "xyz" }); var exitCode = await application.RunAsync(["--foo", "42", "--bar", "--baz", "xyz"]);
// Assert // Assert
exitCode.Should().Be(0); exitCode.Should().Be(0);
@@ -568,7 +562,7 @@ public class OptionBindingSpecs : SpecsBase
public ValueTask ExecuteAsync(IConsole console) public ValueTask ExecuteAsync(IConsole console)
{ {
console.Output.WriteLine(Foo); console.WriteLine(Foo);
return default; return default;
} }
} }
@@ -582,7 +576,7 @@ public class OptionBindingSpecs : SpecsBase
// Act // Act
var exitCode = await application.RunAsync( var exitCode = await application.RunAsync(
new[] { "--foo", "-13" }, ["--foo", "-13"],
new Dictionary<string, string>() new Dictionary<string, string>()
); );
@@ -653,10 +647,7 @@ public class OptionBindingSpecs : SpecsBase
.Build(); .Build();
// Act // Act
var exitCode = await application.RunAsync( var exitCode = await application.RunAsync(["--foo"], new Dictionary<string, string>());
new[] { "--foo" },
new Dictionary<string, string>()
);
// Assert // Assert
exitCode.Should().NotBe(0); exitCode.Should().NotBe(0);
@@ -689,10 +680,7 @@ public class OptionBindingSpecs : SpecsBase
.Build(); .Build();
// Act // Act
var exitCode = await application.RunAsync( var exitCode = await application.RunAsync(["--foo"], new Dictionary<string, string>());
new[] { "--foo" },
new Dictionary<string, string>()
);
// Assert // Assert
exitCode.Should().NotBe(0); exitCode.Should().NotBe(0);
@@ -726,7 +714,7 @@ public class OptionBindingSpecs : SpecsBase
// Act // Act
var exitCode = await application.RunAsync( var exitCode = await application.RunAsync(
new[] { "--foo", "one", "--bar", "two" }, ["--foo", "one", "--bar", "two"],
new Dictionary<string, string>() new Dictionary<string, string>()
); );
@@ -762,7 +750,7 @@ public class OptionBindingSpecs : SpecsBase
// Act // Act
var exitCode = await application.RunAsync( var exitCode = await application.RunAsync(
new[] { "--foo", "one", "two", "three" }, ["--foo", "one", "two", "three"],
new Dictionary<string, string>() new Dictionary<string, string>()
); );

View File

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

View File

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

View File

@@ -5,14 +5,12 @@ using Xunit.Abstractions;
namespace CliFx.Tests; 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(); public FakeInMemoryConsole FakeConsole { get; } = new();
protected SpecsBase(ITestOutputHelper testOutput) => TestOutput = testOutput;
public void Dispose() public void Dispose()
{ {
FakeConsole.DumpToTestOutput(TestOutput); FakeConsole.DumpToTestOutput(TestOutput);

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -3,41 +3,30 @@
/// <summary> /// <summary>
/// Metadata associated with an application. /// Metadata associated with an application.
/// </summary> /// </summary>
public class ApplicationMetadata 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(
string title, string title,
string executableName, string executableName,
string version, string version,
string? description string? description
) )
{ {
Title = title; /// <summary>
ExecutableName = executableName; /// Application title.
Version = version; /// </summary>
Description = description; 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)] [AttributeUsage(AttributeTargets.Class, Inherited = false)]
public sealed class CommandAttribute : Attribute 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> /// <summary>
/// Command name. /// Command name.
/// </summary> /// </summary>
@@ -23,17 +33,4 @@ public sealed class CommandAttribute : Attribute
/// This is shown to the user in the help text. /// This is shown to the user in the help text.
/// </summary> /// </summary>
public string? Description { get; set; } 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)] [AttributeUsage(AttributeTargets.Property)]
public sealed class CommandOptionAttribute : Attribute 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> /// <summary>
/// Option name. /// Option name.
/// </summary> /// </summary>
@@ -67,31 +94,4 @@ public sealed class CommandOptionAttribute : Attribute
/// Validators must derive from <see cref="BindingValidator{T}" />. /// Validators must derive from <see cref="BindingValidator{T}" />.
/// </remarks> /// </remarks>
public Type[] Validators { get; set; } = Array.Empty<Type>(); 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. /// Annotates a property that defines a command parameter.
/// </summary> /// </summary>
[AttributeUsage(AttributeTargets.Property)] [AttributeUsage(AttributeTargets.Property)]
public sealed class CommandParameterAttribute : Attribute public sealed class CommandParameterAttribute(int order) : Attribute
{ {
/// <summary> /// <summary>
/// Parameter order. /// 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. /// 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. /// Only one non-scalar parameter is allowed in a command.
/// </remarks> /// </remarks>
public int Order { get; } public int Order { get; } = order;
/// <summary> /// <summary>
/// Whether this parameter is required (default: <c>true</c>). /// 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}" />. /// Validators must derive from <see cref="BindingValidator{T}" />.
/// </remarks> /// </remarks>
public Type[] Validators { get; set; } = Array.Empty<Type>(); 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

@@ -17,40 +17,24 @@ namespace CliFx;
/// <summary> /// <summary>
/// Command-line application facade. /// Command-line application facade.
/// </summary> /// </summary>
public class CliApplication 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(
ApplicationMetadata metadata, ApplicationMetadata metadata,
ApplicationConfiguration configuration, ApplicationConfiguration configuration,
IConsole console, IConsole console,
ITypeActivator typeActivator ITypeActivator typeActivator
) )
{ {
Metadata = metadata; private readonly CommandBinder _commandBinder = new(typeActivator);
Configuration = configuration;
_console = console;
_typeActivator = 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) => private bool IsDebugModeEnabled(CommandInput commandInput) =>
Configuration.IsDebugModeAllowed && commandInput.IsDebugDirectiveSpecified; Configuration.IsDebugModeAllowed && commandInput.IsDebugDirectiveSpecified;
@@ -70,11 +54,9 @@ public class CliApplication
private async ValueTask PromptDebuggerAsync() private async ValueTask PromptDebuggerAsync()
{ {
using (_console.WithForegroundColor(ConsoleColor.Green)) using (console.WithForegroundColor(ConsoleColor.Green))
{ {
_console console.Output.WriteLine(
.Output
.WriteLine(
$"Attach the debugger to process with ID {ProcessEx.GetCurrentProcessId()} to continue." $"Attach the debugger to process with ID {ProcessEx.GetCurrentProcessId()} to continue."
); );
} }
@@ -93,7 +75,7 @@ public class CliApplication
{ {
// Console colors may have already been overridden by the parent process, // 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. // so we need to reset it to make sure that everything we write looks properly.
_console.ResetColor(); console.ResetColor();
// Handle the debug directive // Handle the debug directive
if (IsDebugModeEnabled(commandInput)) if (IsDebugModeEnabled(commandInput))
@@ -104,7 +86,7 @@ public class CliApplication
// Handle the preview directive // Handle the preview directive
if (IsPreviewModeEnabled(commandInput)) if (IsPreviewModeEnabled(commandInput))
{ {
_console.Output.WriteCommandInput(commandInput); console.WriteCommandInput(commandInput);
return 0; return 0;
} }
@@ -128,7 +110,7 @@ public class CliApplication
var commandInstance = var commandInstance =
commandSchema == FallbackDefaultCommand.Schema commandSchema == FallbackDefaultCommand.Schema
? new FallbackDefaultCommand() // bypass the activator ? new FallbackDefaultCommand() // bypass the activator
: _typeActivator.CreateInstance<ICommand>(commandSchema.Type); : typeActivator.CreateInstance<ICommand>(commandSchema.Type);
// Assemble the help context // Assemble the help context
var helpContext = new HelpContext( var helpContext = new HelpContext(
@@ -141,14 +123,14 @@ public class CliApplication
// Handle the help option // Handle the help option
if (ShouldShowHelpText(commandSchema, commandInput)) if (ShouldShowHelpText(commandSchema, commandInput))
{ {
_console.Output.WriteHelpText(helpContext); console.WriteHelpText(helpContext);
return 0; return 0;
} }
// Handle the version option // Handle the version option
if (ShouldShowVersionText(commandSchema, commandInput)) if (ShouldShowVersionText(commandSchema, commandInput))
{ {
_console.Output.WriteLine(Metadata.Version); console.WriteLine(Metadata.Version);
return 0; return 0;
} }
@@ -160,18 +142,18 @@ public class CliApplication
{ {
// Bind and execute the command // Bind and execute the command
_commandBinder.Bind(commandInput, commandSchema, commandInstance); _commandBinder.Bind(commandInput, commandSchema, commandInstance);
await commandInstance.ExecuteAsync(_console); await commandInstance.ExecuteAsync(console);
return 0; return 0;
} }
catch (CliFxException ex) catch (CliFxException ex)
{ {
_console.Error.WriteException(ex); console.WriteException(ex);
if (ex.ShowHelp) if (ex.ShowHelp)
{ {
_console.Output.WriteLine(); console.WriteLine();
_console.Output.WriteHelpText(helpContext); console.WriteHelpText(helpContext);
} }
return ex.ExitCode; return ex.ExitCode;
@@ -211,7 +193,7 @@ public class CliApplication
// developer, so we don't swallow them in that case. // developer, so we don't swallow them in that case.
catch (Exception ex) when (!Debugger.IsAttached) catch (Exception ex) when (!Debugger.IsAttached)
{ {
_console.Error.WriteException(ex); console.WriteException(ex);
return 1; return 1;
} }
} }

View File

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

View File

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

View File

@@ -12,22 +12,16 @@ using CliFx.Utils.Extensions;
namespace CliFx; namespace CliFx;
internal class CommandBinder internal class CommandBinder(ITypeActivator typeActivator)
{ {
private readonly ITypeActivator _typeActivator;
private readonly IFormatProvider _formatProvider = CultureInfo.InvariantCulture; private readonly IFormatProvider _formatProvider = CultureInfo.InvariantCulture;
public CommandBinder(ITypeActivator typeActivator)
{
_typeActivator = typeActivator;
}
private object? ConvertSingle(IMemberSchema memberSchema, string? rawValue, Type targetType) private object? ConvertSingle(IMemberSchema memberSchema, string? rawValue, Type targetType)
{ {
// Custom converter // Custom converter
if (memberSchema.ConverterType is not null) if (memberSchema.ConverterType is not null)
{ {
var converter = _typeActivator.CreateInstance<IBindingConverter>( var converter = typeActivator.CreateInstance<IBindingConverter>(
memberSchema.ConverterType memberSchema.ConverterType
); );
return converter.Convert(rawValue); return converter.Convert(rawValue);
@@ -48,13 +42,15 @@ internal class CommandBinder
// Special case for DateTimeOffset // Special case for DateTimeOffset
if (targetType == typeof(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 // Special case for TimeSpan
if (targetType == typeof(TimeSpan)) if (targetType == typeof(TimeSpan))
{ {
return TimeSpan.Parse(rawValue, _formatProvider); // Null reference exception will be handled upstream
return TimeSpan.Parse(rawValue!, _formatProvider);
} }
// Enum // Enum
@@ -80,27 +76,24 @@ internal class CommandBinder
} }
// String-constructable (FileInfo, etc) // String-constructable (FileInfo, etc)
var stringConstructor = targetType.GetConstructor(new[] { typeof(string) }); var stringConstructor = targetType.GetConstructor([typeof(string)]);
if (stringConstructor is not null) if (stringConstructor is not null)
{ {
return stringConstructor.Invoke(new object?[] { rawValue }); return stringConstructor.Invoke([rawValue]);
} }
// String-parseable (with IFormatProvider) // String-parseable (with IFormatProvider)
var parseMethodWithFormatProvider = targetType.TryGetStaticParseMethod(true); var parseMethodWithFormatProvider = targetType.TryGetStaticParseMethod(true);
if (parseMethodWithFormatProvider is not null) if (parseMethodWithFormatProvider is not null)
{ {
return parseMethodWithFormatProvider.Invoke( return parseMethodWithFormatProvider.Invoke(null, [rawValue, _formatProvider]);
null,
new object?[] { rawValue, _formatProvider }
);
} }
// String-parseable (without IFormatProvider) // String-parseable (without IFormatProvider)
var parseMethod = targetType.TryGetStaticParseMethod(); var parseMethod = targetType.TryGetStaticParseMethod();
if (parseMethod is not null) if (parseMethod is not null)
{ {
return parseMethod.Invoke(null, new object?[] { rawValue }); return parseMethod.Invoke(null, [rawValue]);
} }
throw CliFxException.InternalError( throw CliFxException.InternalError(
@@ -132,10 +125,10 @@ internal class CommandBinder
} }
// Array-constructable (List<T>, HashSet<T>, etc) // Array-constructable (List<T>, HashSet<T>, etc)
var arrayConstructor = targetEnumerableType.GetConstructor(new[] { arrayType }); var arrayConstructor = targetEnumerableType.GetConstructor([arrayType]);
if (arrayConstructor is not null) if (arrayConstructor is not null)
{ {
return arrayConstructor.Invoke(new object?[] { array }); return arrayConstructor.Invoke([array]);
} }
throw CliFxException.InternalError( throw CliFxException.InternalError(
@@ -152,10 +145,8 @@ internal class CommandBinder
try try
{ {
// Non-scalar // Non-scalar
var enumerableUnderlyingType = memberSchema var enumerableUnderlyingType =
.Property memberSchema.Property.Type.TryGetEnumerableUnderlyingType();
.Type
.TryGetEnumerableUnderlyingType();
if ( if (
enumerableUnderlyingType is not null enumerableUnderlyingType is not null
@@ -213,7 +204,7 @@ internal class CommandBinder
foreach (var validatorType in memberSchema.ValidatorTypes) foreach (var validatorType in memberSchema.ValidatorTypes)
{ {
var validator = _typeActivator.CreateInstance<IBindingValidator>(validatorType); var validator = typeActivator.CreateInstance<IBindingValidator>(validatorType);
var error = validator.Validate(convertedValue); var error = validator.Validate(convertedValue);
if (error is not null) if (error is not null)
@@ -253,8 +244,7 @@ internal class CommandBinder
// Ensure there are no unexpected parameters and that all parameters are provided // Ensure there are no unexpected parameters and that all parameters are provided
var remainingParameterInputs = commandInput.Parameters.ToList(); var remainingParameterInputs = commandInput.Parameters.ToList();
var remainingRequiredParameterSchemas = commandSchema var remainingRequiredParameterSchemas = commandSchema
.Parameters .Parameters.Where(p => p.IsRequired)
.Where(p => p.IsRequired)
.ToList(); .ToList();
var position = 0; var position = 0;
@@ -269,12 +259,9 @@ internal class CommandBinder
if (parameterSchema.Property.IsScalar()) if (parameterSchema.Property.IsScalar())
{ {
var parameterInput = commandInput.Parameters[position]; var parameterInput = commandInput.Parameters[position];
BindMember(parameterSchema, commandInstance, [parameterInput.Value]);
var rawValues = new[] { parameterInput.Value };
BindMember(parameterSchema, commandInstance, rawValues);
position++; position++;
remainingParameterInputs.Remove(parameterInput); remainingParameterInputs.Remove(parameterInput);
} }
// Non-scalar: take all remaining inputs starting from the current position // 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 parameterInputs = commandInput.Parameters.Skip(position).ToArray();
var rawValues = parameterInputs.Select(p => p.Value).ToArray(); BindMember(
BindMember(parameterSchema, commandInstance, rawValues); parameterSchema,
commandInstance,
parameterInputs.Select(p => p.Value).ToArray()
);
position += parameterInputs.Length; position += parameterInputs.Length;
remainingParameterInputs.RemoveRange(parameterInputs); remainingParameterInputs.RemoveRange(parameterInputs);
} }
@@ -308,7 +297,9 @@ internal class CommandBinder
throw CliFxException.UserError( throw CliFxException.UserError(
$""" $"""
Missing required parameter(s): 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 // Ensure there are no unrecognized options and that all required options are set
var remainingOptionInputs = commandInput.Options.ToList(); var remainingOptionInputs = commandInput.Options.ToList();
var remainingRequiredOptionSchemas = commandSchema var remainingRequiredOptionSchemas = commandSchema
.Options .Options.Where(o => o.IsRequired)
.Where(o => o.IsRequired)
.ToList(); .ToList();
foreach (var optionSchema in commandSchema.Options) foreach (var optionSchema in commandSchema.Options)
{ {
var optionInputs = commandInput var optionInputs = commandInput
.Options .Options.Where(o => optionSchema.MatchesIdentifier(o.Identifier))
.Where(o => optionSchema.MatchesIdentifier(o.Identifier))
.ToArray(); .ToArray();
var environmentVariableInput = commandInput var environmentVariableInput = commandInput.EnvironmentVariables.FirstOrDefault(e =>
.EnvironmentVariables optionSchema.MatchesEnvironmentVariable(e.Name)
.FirstOrDefault(e => optionSchema.MatchesEnvironmentVariable(e.Name)); );
// Direct input // Direct input
if (optionInputs.Any()) if (optionInputs.Any())
@@ -353,7 +342,7 @@ internal class CommandBinder
else if (environmentVariableInput is not null) else if (environmentVariableInput is not null)
{ {
var rawValues = optionSchema.Property.IsScalar() var rawValues = optionSchema.Property.IsScalar()
? new[] { environmentVariableInput.Value } ? [environmentVariableInput.Value]
: environmentVariableInput.SplitValues(); : environmentVariableInput.SplitValues();
BindMember(optionSchema, commandInstance, rawValues); BindMember(optionSchema, commandInstance, rawValues);
@@ -386,7 +375,9 @@ internal class CommandBinder
throw CliFxException.UserError( throw CliFxException.UserError(
$""" $"""
Missing required option(s): 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> /// <summary>
/// Exception thrown when there is an error during application execution. /// Exception thrown when there is an error during application execution.
/// </summary> /// </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; internal const int DefaultExitCode = 1;
@@ -13,33 +18,17 @@ public partial class CliFxException : Exception
// provides a default message that is not very useful. // provides a default message that is not very useful.
// This property is used to identify whether this instance was created with // This property is used to identify whether this instance was created with
// a custom message, so that we can avoid printing the default message. // a custom message, so that we can avoid printing the default message.
internal bool HasCustomMessage { get; } internal bool HasCustomMessage { get; } = !string.IsNullOrWhiteSpace(message);
/// <summary> /// <summary>
/// Returned exit code. /// Returned exit code.
/// </summary> /// </summary>
public int ExitCode { get; } public int ExitCode { get; } = exitCode;
/// <summary> /// <summary>
/// Whether to show the help text before exiting. /// Whether to show the help text before exiting.
/// </summary> /// </summary>
public bool ShowHelp { get; } public bool ShowHelp { get; } = showHelp;
/// <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 partial class CliFxException 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. /// 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. /// Use this exception to report an error to the console and return a specific exit code.
/// </summary> /// </summary>
public class CommandException : CliFxException public class CommandException(
{
/// <summary>
/// Initializes an instance of <see cref="CommandException" />.
/// </summary>
public CommandException(
string message, string message,
int exitCode = DefaultExitCode, int exitCode = CliFxException.DefaultExitCode,
bool showHelp = false, bool showHelp = false,
Exception? innerException = null Exception? innerException = null
) ) : CliFxException(message, exitCode, showHelp, innerException);
: base(message, exitCode, showHelp, innerException) { }
}

View File

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

View File

@@ -4,11 +4,9 @@ using CliFx.Input;
namespace CliFx.Formatting; 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) private void WriteCommandLineArguments(CommandInput commandInput)
{ {
Write("Command-line:"); Write("Command-line:");
@@ -94,4 +92,7 @@ internal static class CommandInputConsoleFormatterExtensions
this ConsoleWriter consoleWriter, this ConsoleWriter consoleWriter,
CommandInput commandInput CommandInput commandInput
) => new CommandInputConsoleFormatter(consoleWriter).WriteCommandInput(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; namespace CliFx.Formatting;
internal class ConsoleFormatter internal class ConsoleFormatter(ConsoleWriter consoleWriter)
{ {
private readonly ConsoleWriter _consoleWriter;
private int _column; private int _column;
private int _row; private int _row;
public bool IsEmpty => _column == 0 && _row == 0; public bool IsEmpty => _column == 0 && _row == 0;
public ConsoleFormatter(ConsoleWriter consoleWriter) => _consoleWriter = consoleWriter;
public void Write(string? value) public void Write(string? value)
{ {
_consoleWriter.Write(value); consoleWriter.Write(value);
_column += value?.Length ?? 0; _column += value?.Length ?? 0;
} }
public void Write(char value) public void Write(char value)
{ {
_consoleWriter.Write(value); consoleWriter.Write(value);
_column++; _column++;
} }
public void Write(ConsoleColor foregroundColor, string? value) public void Write(ConsoleColor foregroundColor, string? value)
{ {
using (_consoleWriter.Console.WithForegroundColor(foregroundColor)) using (consoleWriter.Console.WithForegroundColor(foregroundColor))
Write(value); Write(value);
} }
public void Write(ConsoleColor foregroundColor, char value) public void Write(ConsoleColor foregroundColor, char value)
{ {
using (_consoleWriter.Console.WithForegroundColor(foregroundColor)) using (consoleWriter.Console.WithForegroundColor(foregroundColor))
Write(value); Write(value);
} }
public void Write(ConsoleColor foregroundColor, ConsoleColor backgroundColor, string? value) public void Write(ConsoleColor foregroundColor, ConsoleColor backgroundColor, string? value)
{ {
using (_consoleWriter.Console.WithColors(foregroundColor, backgroundColor)) using (consoleWriter.Console.WithColors(foregroundColor, backgroundColor))
Write(value); Write(value);
} }
public void WriteLine() public void WriteLine()
{ {
_consoleWriter.WriteLine(); consoleWriter.WriteLine();
_column = 0; _column = 0;
_row++; _row++;
} }

View File

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

View File

@@ -11,28 +11,20 @@ namespace CliFx.Infrastructure;
/// </summary> /// </summary>
// Both the underlying stream AND the stream reader must be synchronized! // Both the underlying stream AND the stream reader must be synchronized!
// https://github.com/Tyrrrz/CliFx/issues/123 // 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> /// <summary>
/// Initializes an instance of <see cref="ConsoleReader" />. /// Initializes an instance of <see cref="ConsoleReader" />.
/// </summary> /// </summary>
public ConsoleReader(IConsole console, Stream stream) public ConsoleReader(IConsole console, Stream stream)
: this(console, stream, System.Console.InputEncoding) { } : 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 // The following overrides are required to establish thread-safe behavior
// in methods deriving from StreamReader. // in methods deriving from StreamReader.
@@ -94,9 +86,3 @@ public partial class ConsoleReader : StreamReader
[ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)] [ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)]
protected override void Dispose(bool disposing) => base.Dispose(disposing); 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> /// </summary>
// Both the underlying stream AND the stream writer must be synchronized! // Both the underlying stream AND the stream writer must be synchronized!
// https://github.com/Tyrrrz/CliFx/issues/123 // 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> /// <summary>
/// Initializes an instance of <see cref="ConsoleWriter" />. /// Initializes an instance of <see cref="ConsoleWriter" />.
/// </summary> /// </summary>
public ConsoleWriter(IConsole console, Stream stream, Encoding encoding) public ConsoleWriter(IConsole console, Stream stream, Encoding encoding)
: base(stream, encoding.WithoutPreamble(), 256) : base(Stream.Synchronized(stream), encoding.WithoutPreamble(), 256)
{ {
Console = console; Console = console;
AutoFlush = true;
} }
/// <summary> /// <summary>
@@ -34,6 +30,11 @@ public partial class ConsoleWriter : StreamWriter
public ConsoleWriter(IConsole console, Stream stream) public ConsoleWriter(IConsole console, Stream stream)
: this(console, stream, System.Console.OutputEncoding) { } : 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 // The following overrides are required to establish thread-safe behavior
// in methods deriving from StreamWriter. // in methods deriving from StreamWriter.
@@ -44,7 +45,7 @@ public partial class ConsoleWriter : StreamWriter
/// <inheritdoc /> /// <inheritdoc />
[ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)] [ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)]
public override void Write(char[] buffer) => base.Write(buffer); public override void Write(char[]? buffer) => base.Write(buffer);
/// <inheritdoc /> /// <inheritdoc />
[ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)] [ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)]
@@ -146,7 +147,7 @@ public partial class ConsoleWriter : StreamWriter
/// <inheritdoc /> /// <inheritdoc />
[ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)] [ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)]
public override void WriteLine(char[] buffer) => base.WriteLine(buffer); public override void WriteLine(char[]? buffer) => base.WriteLine(buffer);
/// <inheritdoc /> /// <inheritdoc />
[ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)] [ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)]
@@ -268,9 +269,3 @@ public partial class ConsoleWriter : StreamWriter
[ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)] [ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)]
protected override void Dispose(bool disposing) => base.Dispose(disposing); 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 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 // Only catch MemberAccessException because the constructor can throw for its own reasons too
catch (MemberAccessException ex) catch (MemberAccessException ex)
{ {
throw CliFxException.InternalError( 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. 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. To fix this, either add a parameterless constructor to the type or configure a custom activator for the application.
""", """,

View File

@@ -6,32 +6,16 @@ namespace CliFx.Infrastructure;
/// <summary> /// <summary>
/// Implementation of <see cref="ITypeActivator" /> that instantiates an object by using a predefined delegate. /// Implementation of <see cref="ITypeActivator" /> that instantiates an object by using a predefined delegate.
/// </summary> /// </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 /> /// <inheritdoc />
public object CreateInstance(Type type) public object CreateInstance(Type type) =>
{ createInstance(type)
var instance = _createInstance(type); ?? throw CliFxException.InternalError(
if (instance is null)
{
throw CliFxException.InternalError(
$""" $"""
Failed to create an instance of type `{type.FullName}`, received <null> instead. 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>. To fix this, ensure that the provided type activator is configured correctly, as it's not expected to return <null>.
If you are relying on a dependency container, this error may indicate that the specified type has not been registered. If you are relying on a dependency container, this error may indicate that the specified type has not been registered.
""" """
); );
}
return instance;
}
} }

View File

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

View File

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

View File

@@ -5,47 +5,47 @@ using CliFx.Utils;
namespace CliFx.Infrastructure; namespace CliFx.Infrastructure;
/// <summary> /// <summary>
/// Abstraction for the console layer. /// Abstraction for interacting with the console layer.
/// </summary> /// </summary>
public interface IConsole public interface IConsole
{ {
/// <summary> /// <summary>
/// Input stream (stdin). /// Console's standard input stream.
/// </summary> /// </summary>
ConsoleReader Input { get; } ConsoleReader Input { get; }
/// <summary> /// <summary>
/// Gets a value that indicates whether input has been redirected from the standard input stream. /// Whether the input stream has been redirected.
/// </summary> /// </summary>
bool IsInputRedirected { get; } bool IsInputRedirected { get; }
/// <summary> /// <summary>
/// Output stream (stdout). /// Console's standard output stream.
/// </summary> /// </summary>
ConsoleWriter Output { get; } ConsoleWriter Output { get; }
/// <summary> /// <summary>
/// Gets a value that indicates whether output has been redirected from the standard output stream. /// Whether the output stream has been redirected.
/// </summary> /// </summary>
bool IsOutputRedirected { get; } bool IsOutputRedirected { get; }
/// <summary> /// <summary>
/// Error stream (stderr). /// Console's standard error stream.
/// </summary> /// </summary>
ConsoleWriter Error { get; } ConsoleWriter Error { get; }
/// <summary> /// <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> /// </summary>
bool IsErrorRedirected { get; } bool IsErrorRedirected { get; }
/// <summary> /// <summary>
/// Gets or sets the foreground color of the console /// Gets or sets the current foreground color of the console.
/// </summary> /// </summary>
ConsoleColor ForegroundColor { get; set; } ConsoleColor ForegroundColor { get; set; }
/// <summary> /// <summary>
/// Gets or sets the background color of the console. /// Gets or sets the current background color of the console.
/// </summary> /// </summary>
ConsoleColor BackgroundColor { get; set; } ConsoleColor BackgroundColor { get; set; }
@@ -108,6 +108,43 @@ public interface IConsole
/// </summary> /// </summary>
public static class ConsoleExtensions 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> /// <summary>
/// Sets the specified foreground color and returns an <see cref="IDisposable" /> /// Sets the specified foreground color and returns an <see cref="IDisposable" />
/// that will reset the color back to its previous value upon disposal. /// 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; 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 /> /// <inheritdoc />
public ConsoleReader Input { get; } public ConsoleReader Input { get; }
@@ -70,16 +80,6 @@ public class SystemConsole : IConsole, IDisposable
set => Console.CursorTop = value; 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 /> /// <inheritdoc />
public ConsoleKeyInfo ReadKey(bool intercept = false) => Console.ReadKey(intercept); public ConsoleKeyInfo ReadKey(bool intercept = false) => Console.ReadKey(intercept);

View File

@@ -5,17 +5,24 @@ using CliFx.Utils.Extensions;
namespace CliFx.Input; 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 => public bool HasArguments =>
!string.IsNullOrWhiteSpace(CommandName) !string.IsNullOrWhiteSpace(CommandName)
@@ -30,21 +37,6 @@ internal partial class CommandInput
public bool IsHelpOptionSpecified => Options.Any(o => o.IsHelpOption); public bool IsHelpOptionSpecified => Options.Any(o => o.IsHelpOption);
public bool IsVersionOptionSpecified => Options.Any(o => o.IsVersionOption); 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 internal partial class CommandInput
@@ -168,7 +160,7 @@ internal partial class CommandInput
result.Add(new OptionInput(lastOptionIdentifier, lastOptionValues)); result.Add(new OptionInput(lastOptionIdentifier, lastOptionValues));
lastOptionIdentifier = argument[2..]; lastOptionIdentifier = argument[2..];
lastOptionValues = new List<string>(); lastOptionValues = [];
} }
// Short name // Short name
else if (argument.StartsWith('-') && argument.Length > 1 && char.IsLetter(argument[1])) 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)); result.Add(new OptionInput(lastOptionIdentifier, lastOptionValues));
lastOptionIdentifier = identifier.AsString(); lastOptionIdentifier = identifier.AsString();
lastOptionValues = new List<string>(); lastOptionValues = [];
} }
} }
// Value // Value

View File

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

View File

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

View File

@@ -3,26 +3,20 @@ using CliFx.Schema;
namespace CliFx.Input; 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.HelpOption.MatchesIdentifier(Identifier);
public bool IsVersionOption => OptionSchema.VersionOption.MatchesIdentifier(Identifier); public bool IsVersionOption => OptionSchema.VersionOption.MatchesIdentifier(Identifier);
public OptionInput(string identifier, IReadOnlyList<string> values)
{
Identifier = identifier;
Values = values;
}
public string GetFormattedIdentifier() => public string GetFormattedIdentifier() =>
Identifier switch Identifier switch
{ {
{ Length: >= 2 } => "--" + Identifier, { Length: >= 2 } => "--" + Identifier,
_ => '-' + Identifier _ => '-' + Identifier,
}; };
} }

View File

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

View File

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

View File

@@ -5,18 +5,14 @@ using CliFx.Utils.Extensions;
namespace CliFx.Schema; 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 object? GetValue(ICommand commandInstance) => property.GetValue(commandInstance);
public BindablePropertyDescriptor(PropertyInfo property) => _property = property;
public object? GetValue(ICommand commandInstance) => _property.GetValue(commandInstance);
public void SetValue(ICommand commandInstance, object? value) => public void SetValue(ICommand commandInstance, object? value) =>
_property.SetValue(commandInstance, value); property.SetValue(commandInstance, value);
public IReadOnlyList<object?> GetValidValues() public IReadOnlyList<object?> GetValidValues()
{ {

View File

@@ -8,17 +8,23 @@ using CliFx.Utils.Extensions;
namespace CliFx.Schema; namespace CliFx.Schema;
internal partial class CommandSchema internal partial class CommandSchema(
Type type,
string? name,
string? description,
IReadOnlyList<ParameterSchema> parameters,
IReadOnlyList<OptionSchema> options
)
{ {
public Type Type { get; } public Type Type { get; } = type;
public string? Name { get; } public string? Name { get; } = name;
public string? Description { get; } public string? Description { get; } = description;
public IReadOnlyList<ParameterSchema> Parameters { get; } public IReadOnlyList<ParameterSchema> Parameters { get; } = parameters;
public IReadOnlyList<OptionSchema> Options { get; } public IReadOnlyList<OptionSchema> Options { get; } = options;
public bool IsDefault => string.IsNullOrWhiteSpace(Name); public bool IsDefault => string.IsNullOrWhiteSpace(Name);
@@ -26,21 +32,6 @@ internal partial class CommandSchema
public bool IsVersionOptionAvailable => Options.Contains(OptionSchema.VersionOption); public bool IsVersionOptionAvailable => Options.Contains(OptionSchema.VersionOption);
public CommandSchema(
Type type,
string? name,
string? description,
IReadOnlyList<ParameterSchema> parameters,
IReadOnlyList<OptionSchema> options
)
{
Type = type;
Name = name;
Description = description;
Parameters = parameters;
Options = options;
}
public bool MatchesName(string? name) => public bool MatchesName(string? name) =>
!string.IsNullOrWhiteSpace(Name) !string.IsNullOrWhiteSpace(Name)
? string.Equals(name, Name, StringComparison.OrdinalIgnoreCase) ? string.Equals(name, Name, StringComparison.OrdinalIgnoreCase)
@@ -95,10 +86,14 @@ internal partial class CommandSchema
type.GetInterfaces() type.GetInterfaces()
// Only interfaces implementing ICommand for explicitness // Only interfaces implementing ICommand for explicitness
.Where(i => i != typeof(ICommand) && i.IsAssignableTo(typeof(ICommand))) .Where(i => i != typeof(ICommand) && i.IsAssignableTo(typeof(ICommand)))
.SelectMany( .SelectMany(i =>
i =>
i.GetProperties() 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(); .ToArray();

View File

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

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