Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add magic ✨ #223

Closed
wants to merge 29 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions CliWrap.Immersive.Tests/CliWrap.Immersive.Tests.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFrameworks>net8.0</TargetFrameworks>
<TargetFrameworks Condition="$([MSBuild]::IsOsPlatform('Windows'))">$(TargetFrameworks);net48</TargetFrameworks>
</PropertyGroup>

<ItemGroup>
<Content Include="xunit.runner.json" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="coverlet.collector" Version="6.0.0" PrivateAssets="all" />
<PackageReference Include="CSharpier.MsBuild" Version="0.26.2" PrivateAssets="all" />
<PackageReference Include="FluentAssertions" Version="6.12.0" />
<PackageReference Include="GitHubActionsTestLogger" Version="2.3.3" PrivateAssets="all" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0" />
<PackageReference Include="PolyShim" Version="1.8.0" PrivateAssets="all" />
<PackageReference Include="xunit" Version="2.6.2" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.5.4" PrivateAssets="all" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\CliWrap.Immersive\CliWrap.Immersive.csproj" />
<ProjectReference Include="..\CliWrap.Tests.Dummy\CliWrap.Tests.Dummy.csproj" />
</ItemGroup>

</Project>
67 changes: 67 additions & 0 deletions CliWrap.Immersive.Tests/ExecutionSpecs.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
using System.Threading.Tasks;
using FluentAssertions;
using Xunit;
using static CliWrap.Immersive.Spells;
using Dummy = CliWrap.Tests.Dummy;

namespace CliWrap.Immersive.Tests;

public class ExecutionSpecs
{
[Fact(Timeout = 15000)]
public async Task I_can_execute_a_command_with_magic_and_get_the_exit_code()
{
// Arrange
var cmd = Command(Dummy.Program.FilePath);

// Act
int result = await cmd;

// Assert
result.Should().Be(0);
}

[Fact(Timeout = 15000)]
public async Task I_can_execute_a_command_with_magic_and_verify_that_it_succeeded()
{
// Arrange
var cmd = Command(Dummy.Program.FilePath);

// Act
bool result = await cmd;

// Assert
result.Should().BeTrue();
}

[Fact(Timeout = 15000)]
public async Task I_can_execute_a_command_with_magic_and_get_the_stdout()
{
// Arrange
var cmd = Command(Dummy.Program.FilePath, [ "echo", "Hello stdout" ]);

// Act
string result = await cmd;

// Assert
result.Trim().Should().Be("Hello stdout");
}

[Fact(Timeout = 15000)]
public async Task I_can_execute_a_command_with_magic_and_get_the_stdout_and_stderr()
{
// Arrange
var cmd = Command(
Dummy.Program.FilePath,
[ "echo", "Hello stdout and stderr", "--target", "all" ]
);

// Act
var (exitCode, stdOut, stdErr) = await cmd;

// Assert
exitCode.Should().Be(0);
stdOut.Trim().Should().Be("Hello stdout and stderr");
stdErr.Trim().Should().Be("Hello stdout and stderr");
}
}
6 changes: 6 additions & 0 deletions CliWrap.Immersive.Tests/xunit.runner.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"$schema": "https://xunit.net/schema/current/xunit.runner.schema.json",
"appDomain": "denied",
"methodDisplayOptions": "all",
"methodDisplay": "method"
}
32 changes: 32 additions & 0 deletions CliWrap.Immersive/CliWrap.Immersive.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFrameworks>netstandard2.0;netstandard2.1;netcoreapp3.0;net462</TargetFrameworks>
<IsPackable>true</IsPackable>

<!-- TODO: Remove later! -->
<TreatWarningsAsErrors>false</TreatWarningsAsErrors>
</PropertyGroup>

<PropertyGroup>
<Description>Extension for CliWrap that provides a shell-like experience for executing commands</Description>
<PackageProjectUrl>https://github.com/Tyrrrz/CliWrap/tree/master/CliWrap.Immersive</PackageProjectUrl>
<PackageIcon>favicon.png</PackageIcon>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
</PropertyGroup>

<ItemGroup>
<None Include="../favicon.png" Pack="true" PackagePath="" Visible="false" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\CliWrap\CliWrap.csproj" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="CSharpier.MsBuild" Version="0.26.2" PrivateAssets="all" />
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="8.0.0" PrivateAssets="all" />
<PackageReference Include="PolyShim" Version="1.8.0" PrivateAssets="all" />
</ItemGroup>

</Project>
45 changes: 45 additions & 0 deletions CliWrap.Immersive/ImmersiveCommandResult.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
using System;
using CliWrap.Buffered;

namespace CliWrap.Immersive;

/// <summary>
/// Result of a command execution, with buffered text data from standard output and standard error streams.
/// Includes additional operator overloads for convenience in immersive mode.
/// </summary>
public partial class ImmersiveCommandResult(
int exitCode,
DateTimeOffset startTime,
DateTimeOffset exitTime,
string standardOutput,
string standardError
) : BufferedCommandResult(exitCode, startTime, exitTime, standardOutput, standardError)
{
/// <summary>
/// Deconstructs the result into its components.
/// </summary>
public void Deconstruct(out int exitCode, out string standardOutput, out string standardError)
{
exitCode = ExitCode;
standardOutput = StandardOutput;
standardError = StandardError;
}
}

public partial class ImmersiveCommandResult
{
/// <summary>
/// Converts the result to an integer value that corresponds to the <see cref="CommandResult.ExitCode" /> property.
/// </summary>
public static implicit operator int(ImmersiveCommandResult result) => result.ExitCode;

/// <summary>
/// Converts the result to a boolean value that corresponds to the <see cref="CommandResult.IsSuccess" /> property.
/// </summary>
public static implicit operator bool(ImmersiveCommandResult result) => result.IsSuccess;

/// <summary>
/// Converts the result to a string value that corresponds to the <see cref="BufferedCommandResult.StandardOutput" /> property.
/// </summary>
public static implicit operator string(ImmersiveCommandResult result) => result.StandardOutput;
}
33 changes: 33 additions & 0 deletions CliWrap.Immersive/MagicExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
using System.Runtime.CompilerServices;
using CliWrap.Buffered;

namespace CliWrap.Immersive;

/// <summary>
/// Extensions for <see cref="CliWrap" /> types.
/// </summary>
public static class MagicExtensions
{
/// <summary>
/// Executes the command with magic.
/// </summary>
public static CommandTask<ImmersiveCommandResult> ExecuteMagicalAsync(this Command command) =>
command
.ExecuteBufferedAsync()
.Select(
r =>
new ImmersiveCommandResult(
r.ExitCode,
r.StartTime,
r.ExitTime,
r.StandardOutput,
r.StandardError
)
);

/// <summary>
/// Executes the command with buffering and returns the awaiter for the result.
/// </summary>
public static TaskAwaiter<ImmersiveCommandResult> GetAwaiter(this Command command) =>
command.ExecuteMagicalAsync().GetAwaiter();
}
95 changes: 95 additions & 0 deletions CliWrap.Immersive/Readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
# CliWrap.Immersive

[![Version](https://img.shields.io/nuget/v/CliWrap.Immersive.svg)](https://nuget.org/packages/CliWrap.Immersive)
[![Downloads](https://img.shields.io/nuget/dt/CliWrap.Immersive.svg)](https://nuget.org/packages/CliWrap.Immersive)

**CliWrap.Immersive** is an extension package for **CliWrap** that provides a shell-like experience for executing commands.

## Install

- 📦 [NuGet](https://nuget.org/packages/CliWrap.Immersive): `dotnet add package CliWrap.Immersive`

## Usage

### Quick overview

Add `using static CliWrap.Immersive.Spells;` to your file and start writing scripts like this:

```csharp
using static CliWrap.Immersive.Spells;

// Create commands using the _() method, execute them simply by awaiting.
// Check for exit code directly in if statements.
if (!await _("git"))
{
WriteErrorLine("Git is not installed");
Exit(1);
return;
}

// Executing a command returns an object which has implicit conversions to:
// - int (exit code)
// - bool (exit code == 0)
// - string (standard output)
string version = await _("git", "--version"); // git version 2.43.0.windows.1
WriteLine($"Git version: {version}");

// Just like with regular CliWrap, arguments are automatically
// escaped to form a well-formed command line string.
// Non-string arguments of many different types can also be passed directly.
await _("git", "clone", "https://github.com/Tyrrrz/CliWrap", "--depth", 0);

// Resolve environment variables easily with the Environment() method.
var commit = Environment("HEAD_SHA");

// Prompt the user for additional input with the ReadLine() method.
// Check for truthy values using the IsTruthy() method.
if (!IsTruthy(commit))
commit = ReadLine("Enter commit hash");

// Just like with regular CliWrap, arguments are automatically
// escaped to form a well-formed command line string.
await _("git", "checkout", commit);

// Set environment variables using the Environment() method.
// This returns an object that you can dispose to restore the original value.
using (Environment("HEAD_SHA", "deadbeef"))
{
await _("/bin/sh", "-c", "echo $HEAD_SHA"); // deadbeef

// You can also run commands in the default system shell directly
// using the Shell() method.
await Shell("echo $HEAD_SHA"); // deadbeef
}

// Same with the WorkingDirectory() method.
using (WorkingDirectory("/tmp/my-script/"))
{
// Get the current working directory using the same method.
var cwd = WorkingDirectory();
}

// Magic also supports CliWrap's piping syntax.
var commits = new List<string>(); // this will contain commit hashes
await (
_("git", "log", "--pretty=format:%H") | commits.Add
);
```

### Executing commands

In order to run a command with **CliWrap.Immersive**, use the `_` method with the target file path:

```csharp
using CliWrap.Immersive;
using static CliWrap.Immersive.Shell;

await _("dotnet");
var version = await _("dotnet", "--version");
```

Piping works the same way as it does in regular **CliWrap**:

```csharp
await ("standard input" | _("dotnet", "run"));
```
Loading