mirror of
https://github.com/Tyrrrz/CliFx.git
synced 2025-10-25 15:19:17 +00:00
Compare commits
11 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5ec732fe9a | ||
|
|
6d87411dbf | ||
|
|
ed3054c855 | ||
|
|
5d00de4dfe | ||
|
|
016ec8b186 | ||
|
|
9141092919 | ||
|
|
1fe97b0140 | ||
|
|
6ad5989c25 | ||
|
|
7e1db916fc | ||
|
|
1c69d5c80d | ||
|
|
ab87225f1f |
@@ -1,3 +1,7 @@
|
||||
### 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.
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.1.0" />
|
||||
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.1.0" />
|
||||
<PackageReference Include="xunit" Version="2.4.1" />
|
||||
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.3" PrivateAssets="all" />
|
||||
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.5" PrivateAssets="all" />
|
||||
<PackageReference Include="coverlet.collector" Version="3.1.2" PrivateAssets="all" />
|
||||
</ItemGroup>
|
||||
|
||||
|
||||
@@ -10,13 +10,13 @@
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Basic.Reference.Assemblies" Version="1.2.4" />
|
||||
<PackageReference Include="CliWrap" Version="3.4.3" />
|
||||
<PackageReference Include="CliWrap" Version="3.4.4" />
|
||||
<PackageReference Include="FluentAssertions" Version="6.6.0" />
|
||||
<PackageReference Include="GitHubActionsTestLogger" Version="1.4.1" PrivateAssets="all" />
|
||||
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.1.0" />
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.1.0" />
|
||||
<PackageReference Include="xunit" Version="2.4.1" />
|
||||
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.3" PrivateAssets="all" />
|
||||
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.5" PrivateAssets="all" />
|
||||
<PackageReference Include="coverlet.collector" Version="3.1.2" PrivateAssets="all" />
|
||||
</ItemGroup>
|
||||
|
||||
|
||||
@@ -31,7 +31,8 @@ public class ConsoleSpecs : SpecsBase
|
||||
var command = "Hello world" | Cli.Wrap("dotnet")
|
||||
.WithArguments(a => a
|
||||
.Add(Dummy.Program.Location)
|
||||
.Add("console-test"));
|
||||
.Add("console-test")
|
||||
);
|
||||
|
||||
// Act
|
||||
var result = await command.ExecuteBufferedAsync();
|
||||
|
||||
@@ -28,7 +28,8 @@ public class DirectivesSpecs : SpecsBase
|
||||
var command = Cli.Wrap("dotnet")
|
||||
.WithArguments(a => a
|
||||
.Add(Dummy.Program.Location)
|
||||
.Add("[debug]")) | stdOutBuffer;
|
||||
.Add("[debug]")
|
||||
) | stdOutBuffer;
|
||||
|
||||
// Act
|
||||
try
|
||||
@@ -57,7 +58,7 @@ public class DirectivesSpecs : SpecsBase
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
// It's expected to fail
|
||||
// This is expected
|
||||
}
|
||||
|
||||
var stdOut = stdOutBuffer.ToString();
|
||||
|
||||
@@ -246,9 +246,11 @@ public class Command : ICommand
|
||||
var command = Cli.Wrap("dotnet")
|
||||
.WithArguments(a => a
|
||||
.Add(Dummy.Program.Location)
|
||||
.Add("env-test"))
|
||||
.Add("env-test")
|
||||
)
|
||||
.WithEnvironmentVariables(e => e
|
||||
.Set("ENV_TARGET", "Mars"));
|
||||
.Set("ENV_TARGET", "Mars")
|
||||
);
|
||||
|
||||
// Act
|
||||
var result = await command.ExecuteBufferedAsync();
|
||||
|
||||
@@ -6,6 +6,7 @@ using System.Reflection;
|
||||
using CliFx.Attributes;
|
||||
using CliFx.Infrastructure;
|
||||
using CliFx.Schema;
|
||||
using CliFx.Utils;
|
||||
using CliFx.Utils.Extensions;
|
||||
|
||||
namespace CliFx;
|
||||
@@ -21,7 +22,7 @@ public partial class CliApplicationBuilder
|
||||
private bool _isPreviewModeAllowed = true;
|
||||
private string? _title;
|
||||
private string? _executableName;
|
||||
private string? _versionText;
|
||||
private string? _version;
|
||||
private string? _description;
|
||||
private IConsole? _console;
|
||||
private ITypeActivator? _typeActivator;
|
||||
@@ -144,7 +145,7 @@ public partial class CliApplicationBuilder
|
||||
/// </remarks>
|
||||
public CliApplicationBuilder SetVersion(string version)
|
||||
{
|
||||
_versionText = version;
|
||||
_version = version;
|
||||
return this;
|
||||
}
|
||||
|
||||
@@ -189,7 +190,7 @@ public partial class CliApplicationBuilder
|
||||
var metadata = new ApplicationMetadata(
|
||||
_title ?? GetDefaultTitle(),
|
||||
_executableName ?? GetDefaultExecutableName(),
|
||||
_versionText ?? GetDefaultVersionText(),
|
||||
_version ?? GetDefaultVersionText(),
|
||||
_description
|
||||
);
|
||||
|
||||
@@ -210,14 +211,9 @@ public partial class CliApplicationBuilder
|
||||
|
||||
public partial class CliApplicationBuilder
|
||||
{
|
||||
private static readonly Lazy<Assembly?> EntryAssemblyLazy = new(Assembly.GetEntryAssembly);
|
||||
|
||||
// Entry assembly can be null, for example in tests
|
||||
private static Assembly? EntryAssembly => EntryAssemblyLazy.Value;
|
||||
|
||||
private static string GetDefaultTitle()
|
||||
{
|
||||
var entryAssemblyName = EntryAssembly?.GetName().Name;
|
||||
var entryAssemblyName = EnvironmentEx.EntryAssembly?.GetName().Name;
|
||||
if (string.IsNullOrWhiteSpace(entryAssemblyName))
|
||||
return "App";
|
||||
|
||||
@@ -226,26 +222,39 @@ public partial class CliApplicationBuilder
|
||||
|
||||
private static string GetDefaultExecutableName()
|
||||
{
|
||||
var entryAssemblyLocation = EntryAssembly?.Location;
|
||||
var entryAssemblyLocation = EnvironmentEx.EntryAssembly?.Location;
|
||||
if (string.IsNullOrWhiteSpace(entryAssemblyLocation))
|
||||
return "app";
|
||||
|
||||
// The assembly can be an .exe or a .dll, depending on how it was packaged
|
||||
// If the application was launched via matching EXE apphost, use that as the executable name
|
||||
var isLaunchedViaAppHost = string.Equals(
|
||||
EnvironmentEx.ProcessPath,
|
||||
Path.ChangeExtension(entryAssemblyLocation, ".exe"),
|
||||
StringComparison.OrdinalIgnoreCase
|
||||
);
|
||||
|
||||
if (isLaunchedViaAppHost)
|
||||
return Path.GetFileNameWithoutExtension(entryAssemblyLocation);
|
||||
|
||||
// Otherwise, use the entry assembly as the executable name.
|
||||
// Prefix it with `dotnet` if it's a DLL file.
|
||||
var isDll = string.Equals(
|
||||
Path.GetExtension(entryAssemblyLocation),
|
||||
".dll",
|
||||
StringComparison.OrdinalIgnoreCase
|
||||
);
|
||||
|
||||
var name = isDll
|
||||
return isDll
|
||||
? "dotnet " + Path.GetFileName(entryAssemblyLocation)
|
||||
: Path.GetFileNameWithoutExtension(entryAssemblyLocation);
|
||||
|
||||
return name;
|
||||
}
|
||||
|
||||
private static string GetDefaultVersionText() =>
|
||||
EntryAssembly is not null
|
||||
? "v" + EntryAssembly.GetName().Version.ToSemanticString()
|
||||
: "v1.0";
|
||||
private static string GetDefaultVersionText()
|
||||
{
|
||||
var entryAssemblyVersion = EnvironmentEx.EntryAssembly?.GetName().Version;
|
||||
if (entryAssemblyVersion is null)
|
||||
return "v1.0";
|
||||
|
||||
return "v" + entryAssemblyVersion.ToSemanticString();
|
||||
}
|
||||
}
|
||||
@@ -99,10 +99,8 @@ public partial class ConsoleReader : StreamReader
|
||||
|
||||
public partial class ConsoleReader
|
||||
{
|
||||
internal static ConsoleReader Create(IConsole console, Stream? stream) => new(
|
||||
internal static ConsoleReader Create(IConsole console, Stream stream) => new(
|
||||
console,
|
||||
stream is not null
|
||||
? Stream.Synchronized(stream)
|
||||
: Stream.Null
|
||||
Stream.Synchronized(stream)
|
||||
);
|
||||
}
|
||||
@@ -272,10 +272,8 @@ public partial class ConsoleWriter : StreamWriter
|
||||
|
||||
public partial class ConsoleWriter
|
||||
{
|
||||
internal static ConsoleWriter Create(IConsole console, Stream? stream) => new(
|
||||
internal static ConsoleWriter Create(IConsole console, Stream stream) => new(
|
||||
console,
|
||||
stream is not null
|
||||
? Stream.Synchronized(stream)
|
||||
: Stream.Null
|
||||
Stream.Synchronized(stream)
|
||||
) {AutoFlush = true};
|
||||
}
|
||||
@@ -59,14 +59,33 @@ public class FakeConsole : IConsole, IDisposable
|
||||
/// </summary>
|
||||
public FakeConsole(Stream? input = null, Stream? output = null, Stream? error = null)
|
||||
{
|
||||
Input = ConsoleReader.Create(this, input);
|
||||
Output = ConsoleWriter.Create(this, output);
|
||||
Error = ConsoleWriter.Create(this, error);
|
||||
Input = ConsoleReader.Create(this, input ?? Stream.Null);
|
||||
Output = ConsoleWriter.Create(this, output ?? Stream.Null);
|
||||
Error = ConsoleWriter.Create(this, error ?? Stream.Null);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public ConsoleKeyInfo ReadKey(bool intercept = false) =>
|
||||
_keys.TryDequeue(out var key)
|
||||
? key
|
||||
: throw new InvalidOperationException(
|
||||
"Cannot read key because there are no key presses enqueued. " +
|
||||
$"Use the `{nameof(EnqueueKey)}(...)` method to simulate a key press."
|
||||
);
|
||||
|
||||
/// <summary>
|
||||
/// Enqueues a simulated key press, which can then be read by calling <see cref="ReadKey"/>.
|
||||
/// </summary>
|
||||
public void EnqueueKey(ConsoleKeyInfo key) => _keys.Enqueue(key);
|
||||
|
||||
/// <inheritdoc />
|
||||
public void Clear()
|
||||
{
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public CancellationToken RegisterCancellationHandler() => _cancellationTokenSource.Token;
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Sends a cancellation signal to the currently executing command.
|
||||
/// </summary>
|
||||
@@ -87,25 +106,6 @@ public class FakeConsole : IConsole, IDisposable
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public void Clear()
|
||||
{
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public ConsoleKeyInfo ReadKey(bool intercept = false) =>
|
||||
_keys.TryDequeue(out var key)
|
||||
? key
|
||||
: throw new InvalidOperationException(
|
||||
"Cannot read key because there are no key presses enqueued. " +
|
||||
$"Use the `{nameof(EnqueueKey)}(...)` method to simulate a key press."
|
||||
);
|
||||
|
||||
/// <summary>
|
||||
/// Enqueues a simulated key press, which can then be read by calling <see cref="ReadKey"/>.
|
||||
/// </summary>
|
||||
public void EnqueueKey(ConsoleKeyInfo key) => _keys.Enqueue(key);
|
||||
|
||||
/// <inheritdoc />
|
||||
public virtual void Dispose() => _cancellationTokenSource.Dispose();
|
||||
}
|
||||
@@ -64,10 +64,20 @@ public interface IConsole
|
||||
/// </summary>
|
||||
int CursorTop { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Obtains the next character or function key pressed by the user.
|
||||
/// </summary>
|
||||
ConsoleKeyInfo ReadKey(bool intercept = false);
|
||||
|
||||
/// <summary>
|
||||
/// Clears the console buffer and corresponding console window of display information.
|
||||
/// </summary>
|
||||
void Clear();
|
||||
|
||||
/// <summary>
|
||||
/// Registers a handler for the interrupt signal (Ctrl+C) on the console and returns
|
||||
/// a token representing the cancellation request.
|
||||
/// Subsequent calls to this method have no side-effects and return the same token.
|
||||
/// Subsequent calls to this method have no side effects and return the same token.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
@@ -82,16 +92,6 @@ public interface IConsole
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
CancellationToken RegisterCancellationHandler();
|
||||
|
||||
/// <summary>
|
||||
/// Clears the console buffer and corresponding console window of display information.
|
||||
/// </summary>
|
||||
void Clear();
|
||||
|
||||
/// <summary>
|
||||
/// Obtains the next character or function key pressed by the user.
|
||||
/// </summary>
|
||||
ConsoleKeyInfo ReadKey(bool intercept = false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -41,6 +41,20 @@ public class SystemConsole : IConsole, IDisposable
|
||||
get => Console.BackgroundColor;
|
||||
set => Console.BackgroundColor = value;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public int CursorLeft
|
||||
{
|
||||
get => Console.CursorLeft;
|
||||
set => Console.CursorLeft = value;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public int CursorTop
|
||||
{
|
||||
get => Console.CursorTop;
|
||||
set => Console.CursorTop = value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes an instance of <see cref="SystemConsole"/>.
|
||||
@@ -56,19 +70,11 @@ public class SystemConsole : IConsole, IDisposable
|
||||
public void ResetColor() => Console.ResetColor();
|
||||
|
||||
/// <inheritdoc />
|
||||
public int CursorLeft
|
||||
{
|
||||
get => Console.CursorLeft;
|
||||
set => Console.CursorLeft = value;
|
||||
}
|
||||
|
||||
public ConsoleKeyInfo ReadKey(bool intercept = false) => Console.ReadKey(intercept);
|
||||
|
||||
/// <inheritdoc />
|
||||
public int CursorTop
|
||||
{
|
||||
get => Console.CursorTop;
|
||||
set => Console.CursorTop = value;
|
||||
}
|
||||
|
||||
public void Clear() => Console.Clear();
|
||||
|
||||
/// <inheritdoc />
|
||||
public CancellationToken RegisterCancellationHandler()
|
||||
{
|
||||
@@ -89,13 +95,7 @@ public class SystemConsole : IConsole, IDisposable
|
||||
|
||||
return (_cancellationTokenSource = cts).Token;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public void Clear() => Console.Clear();
|
||||
|
||||
/// <inheritdoc />
|
||||
public ConsoleKeyInfo ReadKey(bool intercept = false) => Console.ReadKey(intercept);
|
||||
|
||||
|
||||
/// <inheritdoc />
|
||||
public void Dispose()
|
||||
{
|
||||
|
||||
20
CliFx/Utils/EnvironmentEx.cs
Normal file
20
CliFx/Utils/EnvironmentEx.cs
Normal file
@@ -0,0 +1,20 @@
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.Reflection;
|
||||
|
||||
namespace CliFx.Utils;
|
||||
|
||||
internal static class EnvironmentEx
|
||||
{
|
||||
private static readonly Lazy<string?> ProcessPathLazy = new(() =>
|
||||
{
|
||||
using var process = Process.GetCurrentProcess();
|
||||
return process.MainModule?.FileName;
|
||||
});
|
||||
|
||||
public static string? ProcessPath => ProcessPathLazy.Value;
|
||||
|
||||
private static readonly Lazy<Assembly?> EntryAssemblyLazy = new(Assembly.GetEntryAssembly);
|
||||
|
||||
public static Assembly? EntryAssembly => EntryAssemblyLazy.Value;
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
<Project>
|
||||
|
||||
<PropertyGroup>
|
||||
<Version>2.2.4</Version>
|
||||
<Version>2.2.5</Version>
|
||||
<Company>Tyrrrz</Company>
|
||||
<Copyright>Copyright (C) Oleksii Holub</Copyright>
|
||||
<LangVersion>latest</LangVersion>
|
||||
|
||||
165
Readme.md
165
Readme.md
@@ -34,7 +34,7 @@ To learn more about the war and how you can help, [click here](https://tyrrrz.me
|
||||
- Complete application framework, not just an argument parser
|
||||
- Minimum boilerplate and easy to get started
|
||||
- Class-first configuration via attributes
|
||||
- Comprehensive autogenerated help text
|
||||
- Comprehensive auto-generated help text
|
||||
- Support for deeply nested command hierarchies
|
||||
- Graceful cancellation via interrupt signals
|
||||
- Support for reading and writing binary data
|
||||
@@ -49,9 +49,7 @@ To learn more about the war and how you can help, [click here](https://tyrrrz.me
|
||||
|
||||
## Usage
|
||||
|
||||
### Quick start
|
||||
|
||||

|
||||
### Application and commands
|
||||
|
||||
To turn your program into a command line interface, modify your `Main` method so that it delegates execution to `CliApplication`.
|
||||
You can use `CliApplicationBuilder` to fluently create and configure an instance of `CliApplication`:
|
||||
@@ -68,9 +66,12 @@ public static class Program
|
||||
```
|
||||
|
||||
> ⚠️ Ensure that your `Main()` method returns the integer exit code provided by `CliApplication.RunAsync()`, as shown in the above example.
|
||||
Exit code is used to communicate execution result to the parent process, so it's important that your program returns it.
|
||||
> Exit code is used to communicate execution result to the parent process, so it's important that your program propagates it.
|
||||
|
||||
The code above calls `AddCommandsFromThisAssembly()` to scan and resolve command types defined within the current assembly.
|
||||
> 💡 When calling `CliApplication.RunAsync()`, **CliFx** resolves command line arguments and environment variables from `Environment.GetCommandLineArgs()` and `Environment.GetEnvironmentVariables()` respectively.
|
||||
> You can also provide them explicitly if you choose.
|
||||
|
||||
The code above uses `AddCommandsFromThisAssembly()` to detect command types defined within the current assembly.
|
||||
Commands are entry points, through which the user can interact with your application.
|
||||
|
||||
To define a command, create a new class by implementing the `ICommand` interface and annotate it with the `[Command]` attribute:
|
||||
@@ -92,12 +93,12 @@ public class HelloWorldCommand : ICommand
|
||||
In order to implement `ICommand`, the class needs to define an `ExecuteAsync(...)` method.
|
||||
This is the method that gets called by the framework when the user decides to execute this command.
|
||||
|
||||
As a parameter, this method takes an instance of `IConsole`, which is an abstraction around the system console.
|
||||
As the only parameter, this method takes an instance of `IConsole`, which is an abstraction around the system console.
|
||||
Use this abstraction in place of `System.Console` whenever you need to write output, read input, or otherwise interact with the console.
|
||||
|
||||
With the basic setup above, the user can now run the application and get a greeting in return:
|
||||
|
||||
```sh
|
||||
```powershell
|
||||
> dotnet myapp.dll
|
||||
|
||||
Hello world!
|
||||
@@ -106,7 +107,7 @@ Hello world!
|
||||
Out of the box, the application also comes with built-in `--help` and `--version` options.
|
||||
They can be used to show help text or application version respectively:
|
||||
|
||||
```sh
|
||||
```powershell
|
||||
> dotnet myapp.dll --help
|
||||
|
||||
MyApp v1.0
|
||||
@@ -119,7 +120,7 @@ OPTIONS
|
||||
--version Shows version information.
|
||||
```
|
||||
|
||||
```sh
|
||||
```powershell
|
||||
> dotnet myapp.dll --version
|
||||
|
||||
v1.0
|
||||
@@ -128,12 +129,12 @@ v1.0
|
||||
### Parameters and options
|
||||
|
||||
Commands can be configured to take input from command line arguments.
|
||||
To do that, you need to add properties to the command class and annotate them with special attributes.
|
||||
To do that, you need to add properties to the command class and bind them using special attributes.
|
||||
|
||||
In **CliFx**, there are two types of argument bindings: **parameters** and **options**.
|
||||
Parameters are positional arguments identified by the order they appear in, while options represent sets of arguments identified by their name.
|
||||
Parameters are bound from arguments based on the order they appear in, while options are bound by their name.
|
||||
|
||||
As an example, here's a command that calculates the logarithm of a value, using a parameter binding to specify the input and an option binding to configure the logarithm base:
|
||||
As an example, here's a command that calculates logarithm of a value — it uses a parameter binding to specify the input value and an option binding for the logarithm base:
|
||||
|
||||
```csharp
|
||||
[Command]
|
||||
@@ -158,9 +159,12 @@ public class LogCommand : ICommand
|
||||
}
|
||||
```
|
||||
|
||||
> 💡 **CliFx** has built-in analyzers that detect common errors in command definitions.
|
||||
> Your code will not compile if the command contains duplicate options, overlapping parameters, or otherwise invalid configuration.
|
||||
|
||||
In order to execute this command, at a minimum, the user needs to provide the input value:
|
||||
|
||||
```sh
|
||||
```powershell
|
||||
> dotnet myapp.dll 10000
|
||||
|
||||
4
|
||||
@@ -168,7 +172,7 @@ In order to execute this command, at a minimum, the user needs to provide the in
|
||||
|
||||
They can also pass the `base` option to override the default logarithm base of 10:
|
||||
|
||||
```sh
|
||||
```powershell
|
||||
> dotnet myapp.dll 729 -b 3
|
||||
|
||||
6
|
||||
@@ -176,7 +180,7 @@ They can also pass the `base` option to override the default logarithm base of 1
|
||||
|
||||
In case the user forgets to specify the `value` parameter, the application will exit with an error:
|
||||
|
||||
```sh
|
||||
```powershell
|
||||
> dotnet myapp.dll -b 10
|
||||
|
||||
Missing required parameter(s):
|
||||
@@ -185,7 +189,7 @@ Missing required parameter(s):
|
||||
|
||||
Available parameters and options are also listed in the command's help text, which can be accessed by passing the `--help` option:
|
||||
|
||||
```sh
|
||||
```powershell
|
||||
> dotnet myapp.dll --help
|
||||
|
||||
MyApp v1.0
|
||||
@@ -204,14 +208,14 @@ OPTIONS
|
||||
|
||||
Overall, parameters and options are both used to consume input from the command line, but they differ in a few important ways:
|
||||
|
||||
| | Parameters | Options |
|
||||
|--------------------|-------------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------|
|
||||
| **Identification** | Positional (by relative order). | Named (by name or short name). |
|
||||
| **Requiredness** | Required by default. Only the last parameter can be configured to be optional. | Optional by default. Any option can be configured to be required without limitations. |
|
||||
| **Arity** | Depends on the property type. Only the last parameter can be bound to a non-scalar type (i.e. array). | Depends on the property type. Any option can be bound to a non-scalar type without limitations. |
|
||||
| **Fallback** | — | Can be configured to use an environment variable as fallback, in case the option isn't set. |
|
||||
| | Parameter | Option |
|
||||
|--------------------|--------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------|
|
||||
| **Identification** | Positional (by relative order). | Nominal (by name or short name). |
|
||||
| **Requiredness** | Required by default. Only the last parameter can be configured to be optional. | Optional by default. Any option can be configured to be required without limitations. |
|
||||
| **Arity** | Only the last parameter can be bound to a non-scalar property (i.e. an array). | Any option can be bound to a non-scalar property without limitations. |
|
||||
| **Fallback** | — | Can be configured to use an environment variable as fallback if the value isn't explicitly provided. |
|
||||
|
||||
As a general guideline, it's recommended to use parameters for required inputs that the command can't function without.
|
||||
As a general guideline, use parameters for required inputs that the command can't function without.
|
||||
Use options for all other non-required inputs or when specifying the name explicitly makes the usage clearer.
|
||||
|
||||
### Argument syntax
|
||||
@@ -227,26 +231,26 @@ Here are some examples of how it works:
|
||||
- `myapp -xqf bar` sets options `'x'` and `'q'` without value, and option `'f'` to value `"bar"`
|
||||
- `myapp -i file1.txt file2.txt` sets option `'i'` to a sequence of values `"file1.txt"` and `"file2.txt"`
|
||||
- `myapp -i file1.txt -i file2.txt` sets option `'i'` to a sequence of values `"file1.txt"` and `"file2.txt"`
|
||||
- `myapp cmd abc -o` routes to command `cmd` (assuming it's an existing command) with parameter `abc` and sets option `'o'` without value
|
||||
- `myapp cmd abc -o` routes to command `cmd` (assuming it's a command) with parameter `abc` and sets option `'o'` without value
|
||||
|
||||
Additionally, argument parsing in **CliFx** aims to be as deterministic as possible, ideally yielding the same result regardless of the application configuration.
|
||||
In fact, the only context-sensitive part in the parser is the command name resolution, which needs to know the list of available commands in order to discern between arguments that correspond to command name and arguments which map as parameters.
|
||||
In fact, the only context-sensitive part in the parser is the command name resolution, which needs to know the list of available commands in order to discern them from parameters.
|
||||
|
||||
The parser's context-free nature has several implications on how it consumes arguments.
|
||||
For example, passing `myapp -i file1.txt file2.txt` will always be parsed as an option with multiple values, regardless of the arity of the underlying property it's bound to.
|
||||
For example, `myapp -i file1.txt file2.txt` will always be parsed as an option with multiple values, regardless of the arity of the underlying property it's bound to.
|
||||
Similarly, unseparated arguments in the form of `myapp -ofile` will be treated as five distinct options `'o'`, `'f'`, `'i'`, `'l'`, `'e'`, instead of `'o'` being set to value `"file"`.
|
||||
|
||||
Because of these rules, order of arguments is semantically important and must always follow this pattern:
|
||||
These rules also make the order of arguments important — command line string is expected to follow this pattern:
|
||||
|
||||
```txt
|
||||
[directives] [command name] [parameters] [options]
|
||||
```powershell
|
||||
> myapp [...directives] [command] [...parameters] [...options]
|
||||
```
|
||||
|
||||
### Value conversion
|
||||
|
||||
Parameters and options can have the following underlying types:
|
||||
Parameters and options can be bound to properties with the following underlying types:
|
||||
|
||||
- Standard types
|
||||
- Basic types
|
||||
- Primitive types (`int`, `bool`, `double`, `ulong`, `char`, etc.)
|
||||
- Date and time types (`DateTime`, `DateTimeOffset`, `TimeSpan`)
|
||||
- Enum types (converted from either name or numeric value)
|
||||
@@ -284,7 +288,7 @@ public class FileSizeCalculatorCommand : ICommand
|
||||
}
|
||||
```
|
||||
|
||||
```sh
|
||||
```powershell
|
||||
> dotnet myapp.dll file1.bin file2.exe
|
||||
|
||||
Total file size: 186368 bytes
|
||||
@@ -310,7 +314,7 @@ public class FileSizeCalculatorCommand : ICommand
|
||||
}
|
||||
```
|
||||
|
||||
```sh
|
||||
```powershell
|
||||
> dotnet myapp.dll --files file1.bin file2.exe
|
||||
|
||||
Total file size: 186368 bytes
|
||||
@@ -366,10 +370,42 @@ public class SurfaceCalculatorCommand : ICommand
|
||||
}
|
||||
```
|
||||
|
||||
### Environment variables
|
||||
|
||||
An option can be configured to use a specific environment variable as fallback.
|
||||
If the user does not provide value for such option through command line arguments, the current value of the environment variable will be used instead.
|
||||
|
||||
```csharp
|
||||
[Command]
|
||||
public class AuthCommand : ICommand
|
||||
{
|
||||
[CommandOption("token", IsRequired = true, EnvironmentVariable = "AUTH_TOKEN")]
|
||||
public string AuthToken { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console)
|
||||
{
|
||||
console.Output.WriteLine(AuthToken);
|
||||
|
||||
return default;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```powershell
|
||||
> $env:AUTH_TOKEN="test"
|
||||
|
||||
> dotnet myapp.dll
|
||||
|
||||
test
|
||||
```
|
||||
|
||||
Environment variables can be configured for options of non-scalar types (arrays, lists, etc.) as well.
|
||||
In such case, the values of the environment variable will be split by `Path.PathSeparator` (`;` on Windows, `:` on Linux).
|
||||
|
||||
### Multiple commands
|
||||
|
||||
In order to facilitate a variety of different workflows, command line applications may provide the user with more than just a single command.
|
||||
Complex applications may also nest commands within each other, employing a multi-level hierarchical structure.
|
||||
Complex applications may also nest commands underneath each other, employing a multi-level hierarchical structure.
|
||||
|
||||
With **CliFx**, this is achieved by simply giving each command a unique name through the `[Command]` attribute.
|
||||
Commands that have common name segments are considered to be hierarchically related, which affects how they're listed in the help text.
|
||||
@@ -404,12 +440,12 @@ public class SubCommand : ICommand
|
||||
}
|
||||
```
|
||||
|
||||
Once configured, the user can execute a specific command by including its name in the passed arguments.
|
||||
Once configured, the user can execute a specific command by pre-pending its name to the passed arguments.
|
||||
For example, running `dotnet myapp.dll cmd1 arg1 -p 42` will execute `FirstCommand` in the above example.
|
||||
|
||||
Requesting help will show direct subcommands of the current command:
|
||||
|
||||
```sh
|
||||
```powershell
|
||||
> dotnet myapp.dll --help
|
||||
|
||||
MyApp v1.0
|
||||
@@ -431,7 +467,7 @@ You can run `dotnet myapp.dll [command] --help` to show help on a specific comma
|
||||
|
||||
The user can also refine their help request by querying it on a specific command:
|
||||
|
||||
```sh
|
||||
```powershell
|
||||
> dotnet myapp.dll cmd1 --help
|
||||
|
||||
USAGE
|
||||
@@ -448,7 +484,7 @@ You can run `dotnet myapp.dll cmd1 [command] --help` to show help on a specific
|
||||
```
|
||||
|
||||
> 💡 Defining a default (unnamed) command is not required.
|
||||
If it's absent, running the application without specifying a command will just show the root level help text.
|
||||
> If it's absent, running the application without specifying a command will just show the root level help text.
|
||||
|
||||
### Reporting errors
|
||||
|
||||
@@ -481,7 +517,7 @@ public class DivideCommand : ICommand
|
||||
}
|
||||
```
|
||||
|
||||
```sh
|
||||
```powershell
|
||||
> dotnet myapp.dll --dividend 10 --divisor 0
|
||||
|
||||
Division by zero is not supported.
|
||||
@@ -492,8 +528,8 @@ Division by zero is not supported.
|
||||
133
|
||||
```
|
||||
|
||||
> ⚠️ Even though exit codes are represented by 32-bit integers in .NET, using values outside of 8-bit unsigned range will cause an overflow on Unix systems.
|
||||
To avoid unexpected results, use numbers between 1 and 255 for exit codes that indicate failure.
|
||||
> ⚠️ Even though exit codes are represented by 32-bit integers in .NET, using values outside 8-bit unsigned range will cause an overflow on Unix systems.
|
||||
> To avoid unexpected results, use numbers between 1 and 255 for exit codes that indicate failure.
|
||||
|
||||
### Graceful cancellation
|
||||
|
||||
@@ -526,14 +562,14 @@ public class CancellableCommand : ICommand
|
||||
```
|
||||
|
||||
> ⚠️ Forceful termination of a command can only be delayed once.
|
||||
If the user issues a second interrupt signal, the process will be killed immediately without waiting for graceful cancellation.
|
||||
> If the user issues a second interrupt signal, the process will be killed immediately without waiting for graceful cancellation.
|
||||
|
||||
### Type activation
|
||||
|
||||
Because **CliFx** takes responsibility for the application's entire lifecycle, it needs to be capable of instantiating various user-defined types at runtime.
|
||||
To facilitate that, it uses an interface called `ITypeActivator` that determines how to create a new instance of a given type.
|
||||
|
||||
The default implementation of `ITypeActivator` only supports types that have public parameterless constructors, which is sufficient for majority of scenarios.
|
||||
The default implementation of `ITypeActivator` only supports types that have public parameterless constructors, which is sufficient for the majority of scenarios.
|
||||
However, in some cases you may also want to define a custom initializer, for example when integrating with an external dependency container.
|
||||
|
||||
The following example shows how to configure your application to use [`Microsoft.Extensions.DependencyInjection`](https://nuget.org/packages/Microsoft.Extensions.DependencyInjection) as the type activator in **CliFx**:
|
||||
@@ -652,7 +688,7 @@ To do that, you need to pass the corresponding directive before any other argume
|
||||
In order to run the application in debug mode, use the `[debug]` directive.
|
||||
This will cause the program to launch in a suspended state, waiting for debugger to be attached to the process:
|
||||
|
||||
```sh
|
||||
```powershell
|
||||
> dotnet myapp.dll [debug] cmd -o
|
||||
|
||||
Attach debugger to PID 3148 to continue.
|
||||
@@ -661,12 +697,12 @@ Attach debugger to PID 3148 to continue.
|
||||
To run the application in preview mode, use the `[preview]` directive.
|
||||
This will short-circuit the execution and instead print the consumed command line arguments as they were parsed, along with resolved environment variables:
|
||||
|
||||
```sh
|
||||
```powershell
|
||||
> dotnet myapp.dll [preview] cmd arg1 arg2 -o foo --option bar1 bar2
|
||||
|
||||
Command line:
|
||||
cmd <arg1> <arg2> [-o foo] [--option bar1 bar2]
|
||||
|
||||
|
||||
Environment:
|
||||
FOO="123"
|
||||
BAR="xyz"
|
||||
@@ -682,38 +718,7 @@ var app = new CliApplicationBuilder()
|
||||
.Build();
|
||||
```
|
||||
|
||||
### Environment variables
|
||||
|
||||
An option can be configured to use a specific environment variable as fallback.
|
||||
If the user does not provide value for such option through command line arguments, the current value of the environment variable will be used instead.
|
||||
|
||||
```csharp
|
||||
[Command]
|
||||
public class AuthCommand : ICommand
|
||||
{
|
||||
[CommandOption("token", IsRequired = true, EnvironmentVariable = "AUTH_TOKEN")]
|
||||
public string AuthToken { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console)
|
||||
{
|
||||
console.Output.WriteLine(AuthToken);
|
||||
|
||||
return default;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```sh
|
||||
> $env:AUTH_TOKEN="test"
|
||||
|
||||
> dotnet myapp.dll
|
||||
|
||||
test
|
||||
```
|
||||
|
||||
Environment variables can be configured for options of non-scalar types (arrays, lists, etc.) as well.
|
||||
In such case, the values of the environment variable will be split by `Path.PathSeparator` (`;` on Windows, `:` on Linux).
|
||||
|
||||
## Etymology
|
||||
|
||||
**CliFx** is made out of "Cli" for "Command Line Interface" and "Fx" for "Framework". It's pronounced as "cliff ex".
|
||||
**CliFx** is made out of "Cli" for "Command Line Interface" and "Fx" for "Framework".
|
||||
It's pronounced as "cliff ex".
|
||||
Reference in New Issue
Block a user