Skip to content

Commit

Permalink
Update README.md
Browse files Browse the repository at this point in the history
  • Loading branch information
NikolayPianikov committed Jul 18, 2024
1 parent 0749be3 commit 8770d90
Show file tree
Hide file tree
Showing 3 changed files with 249 additions and 15 deletions.
129 changes: 123 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,132 @@

![](docs/csharp_cat.png)

This is a repository of dotnet-csi which is an interactive tool for running C# scripts. It can installed as a command-line tool on Windows, Linux, or macOS.
```c#
using System.Web;
using HostApi;
using Microsoft.Extensions.DependencyInjection;
using NuGet.Versioning;

// Output API
WriteLine("Hello");
WriteLine("Hello !!!", Color.Highlighted);
Error("Error details", "ErrorId");
Warning("Warning");
Info("Some info");
Trace("Trace message");

// API for arguments and parameters
Info("First argument: " + (Args.Count > 0 ? Args[0] : "empty"));
Info("Version: " + Props.Get("version", "1.0.0"));
Props["version"] = "1.0.1";

var configuration = Props.Get("configuration", "Release");
Info($"Configuration: {configuration}");

// Command line API
var cmd = new CommandLine("whoami");

cmd.Run().EnsureSuccess();

// Asynchronous way
await cmd.RunAsync().EnsureSuccess();

// API for Docker CLI
await new DockerRun("ubuntu")
.WithCommandLine(cmd)
.WithPull(DockerPullType.Always)
.WithAutoRemove(true)
.RunAsync()
.EnsureSuccess();

## Prerequisites
// Microsoft DI API to resolve dependencies
var nuget = GetService<INuGet>();

The tool requires [.NET 6+ runtime](https://dotnet.microsoft.com/en-us/download).
// Creating a custom service provider
var serviceCollection = GetService<IServiceCollection>();
serviceCollection.AddSingleton<MyTool>();

var myServiceProvider = serviceCollection.BuildServiceProvider();
var tool = myServiceProvider.GetRequiredService<MyTool>();

// API for NuGet
var settings = new NuGetRestoreSettings("MySampleLib")
.WithVersionRange(VersionRange.Parse("[1.0.14, 1.1)"))
.WithTargetFrameworkMoniker("net6.0")
.WithPackagesPath(".packages");

var packages = nuget.Restore(settings);
foreach (var package in packages)
{
Info(package.Path);
}

// API for .NET CLI
var buildResult = new DotNetBuild().WithConfiguration(configuration).WithNoLogo(true)
.Build().EnsureSuccess();

var warnings = buildResult.Warnings
.Where(warn => Path.GetFileName(warn.File) == "Calculator.cs")
.Select(warn => $"{warn.Code}({warn.LineNumber}:{warn.ColumnNumber})")
.Distinct();

foreach (var warning in warnings)
{
await new HttpClient().GetAsync(
"https://api.telegram.org/bot7102686717:AAEHw7HZinme_5kfIRV7TwXK4Xql9WPPpM3/" +
"sendMessage?chat_id=878745093&text="
+ HttpUtility.UrlEncode(warning));
}

// Asynchronous way
var cts = new CancellationTokenSource();
await new DotNetTest()
.WithConfiguration(configuration)
.WithNoLogo(true)
.WithNoBuild(true)
.BuildAsync(CancellationOnFirstFailedTest, cts.Token)
.EnsureSuccess();

void CancellationOnFirstFailedTest(BuildMessage message)
{
if (message.TestResult is { State: TestState.Failed }) cts.Cancel();
}

// Parallel tests
var tempDir = Directory.CreateTempSubdirectory();
try
{
new DotNetPublish()
.WithConfiguration(configuration)
.WithNoLogo(true)
.WithNoBuild(true)
.WithFramework("net8.0")
.AddProps(("PublishDir", tempDir.FullName))
.Build().EnsureSuccess();

var test = new VSTest().WithTestFileNames("*.Tests.dll");

var tasks = from tagSuffix in new[] {"bookworm-slim", "alpine", "noble"}
let image = $"mcr.microsoft.com/dotnet/sdk:8.0-{tagSuffix}"
let dockerRun = new DockerRun(image)
.WithCommandLine(test)
.WithAutoRemove(true)
.WithVolumes((tempDir.FullName, "/app"))
.WithContainerWorkingDirectory("/app")
select dockerRun.BuildAsync(CancellationOnFirstFailedTest, cts.Token);

await Task.WhenAll(tasks).EnsureSuccess();
}
finally { tempDir.Delete(); }

class MyTool(INuGet nuGet);
```

## Usage

### Script runner
### Script runner tool

It can be installed as a command-line tool on Windows, Linux, or macOS. The dotnet tool requires [.NET 6+ runtime](https://dotnet.microsoft.com/en-us/download).

After installing tool you can use this tool to run C# scripts from the command line. dotnet-csi is available as a [NuGet package](https://www.nuget.org/packages/dotnet-csi/).

Expand Down Expand Up @@ -76,12 +193,12 @@ Supported arguments:

```using HostApi;``` directive in a script allows you to use host API types without specifying the fully qualified namespace of these types.

### .NET application
### .NET project

Install the C# script template [CSharpInteractive.Templates](https://www.nuget.org/packages/CSharpInteractive.Templates)

```shell
dotnet new -i CSharpInteractive.Templates
dotnet new install CSharpInteractive.Templates
```

Create a console project "Build" containing a script from the template *__build__*
Expand Down
133 changes: 125 additions & 8 deletions README_BODY.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,132 @@

![](docs/csharp_cat.png)

This is a repository of dotnet-csi which is an interactive tool for running C# scripts. It can installed as a command-line tool on Windows, Linux, or macOS.

## Prerequisites

The tool requires [.NET 6+ runtime](https://dotnet.microsoft.com/en-us/download).
```c#
using System.Web;
using HostApi;
using Microsoft.Extensions.DependencyInjection;
using NuGet.Versioning;

// Output API
WriteLine("Hello");
WriteLine("Hello !!!", Color.Highlighted);
Error("Error details", "ErrorId");
Warning("Warning");
Info("Some info");
Trace("Trace message");

// API for arguments and parameters
Info("First argument: " + (Args.Count > 0 ? Args[0] : "empty"));
Info("Version: " + Props.Get("version", "1.0.0"));
Props["version"] = "1.0.1";

var configuration = Props.Get("configuration", "Release");
Info($"Configuration: {configuration}");

// Command line API
var cmd = new CommandLine("whoami");

cmd.Run().EnsureSuccess();

// Asynchronous way
await cmd.RunAsync().EnsureSuccess();

// API for Docker CLI
await new DockerRun("ubuntu")
.WithCommandLine(cmd)
.WithPull(DockerPullType.Always)
.WithAutoRemove(true)
.RunAsync()
.EnsureSuccess();

// Microsoft DI API to resolve dependencies
var nuget = GetService<INuGet>();

// Creating a custom service provider
var serviceCollection = GetService<IServiceCollection>();
serviceCollection.AddSingleton<MyTool>();

var myServiceProvider = serviceCollection.BuildServiceProvider();
var tool = myServiceProvider.GetRequiredService<MyTool>();

// API for NuGet
var settings = new NuGetRestoreSettings("MySampleLib")
.WithVersionRange(VersionRange.Parse("[1.0.14, 1.1)"))
.WithTargetFrameworkMoniker("net6.0")
.WithPackagesPath(".packages");

var packages = nuget.Restore(settings);
foreach (var package in packages)
{
Info(package.Path);
}

// API for .NET CLI
var buildResult = new DotNetBuild().WithConfiguration(configuration).WithNoLogo(true)
.Build().EnsureSuccess();

var warnings = buildResult.Warnings
.Where(warn => Path.GetFileName(warn.File) == "Calculator.cs")
.Select(warn => $"{warn.Code}({warn.LineNumber}:{warn.ColumnNumber})")
.Distinct();

foreach (var warning in warnings)
{
await new HttpClient().GetAsync(
"https://api.telegram.org/bot7102686717:AAEHw7HZinme_5kfIRV7TwXK4Xql9WPPpM3/" +
"sendMessage?chat_id=878745093&text="
+ HttpUtility.UrlEncode(warning));
}

// Asynchronous way
var cts = new CancellationTokenSource();
await new DotNetTest()
.WithConfiguration(configuration)
.WithNoLogo(true)
.WithNoBuild(true)
.BuildAsync(CancellationOnFirstFailedTest, cts.Token)
.EnsureSuccess();

void CancellationOnFirstFailedTest(BuildMessage message)
{
if (message.TestResult is { State: TestState.Failed }) cts.Cancel();
}

// Parallel tests
var tempDir = Directory.CreateTempSubdirectory();
try
{
new DotNetPublish()
.WithConfiguration(configuration)
.WithNoLogo(true)
.WithNoBuild(true)
.WithFramework("net8.0")
.AddProps(("PublishDir", tempDir.FullName))
.Build().EnsureSuccess();

var test = new VSTest().WithTestFileNames("*.Tests.dll");

var tasks = from tagSuffix in new[] {"bookworm-slim", "alpine", "noble"}
let image = $"mcr.microsoft.com/dotnet/sdk:8.0-{tagSuffix}"
let dockerRun = new DockerRun(image)
.WithCommandLine(test)
.WithAutoRemove(true)
.WithVolumes((tempDir.FullName, "/app"))
.WithContainerWorkingDirectory("/app")
select dockerRun.BuildAsync(CancellationOnFirstFailedTest, cts.Token);

await Task.WhenAll(tasks).EnsureSuccess();
}
finally { tempDir.Delete(); }

class MyTool(INuGet nuGet);
```

## Usage

### Script runner
### Script runner tool

It can be installed as a command-line tool on Windows, Linux, or macOS. The dotnet tool requires [.NET 6+ runtime](https://dotnet.microsoft.com/en-us/download).

After installing tool you can use this tool to run C# scripts from the command line. dotnet-csi is available as a [NuGet package](https://www.nuget.org/packages/dotnet-csi/).

Expand Down Expand Up @@ -76,12 +193,12 @@ Supported arguments:

```using HostApi;``` directive in a script allows you to use host API types without specifying the fully qualified namespace of these types.

### .NET application
### .NET project

Install the C# script template [CSharpInteractive.Templates](https://www.nuget.org/packages/CSharpInteractive.Templates)

```shell
dotnet new -i CSharpInteractive.Templates
dotnet new install CSharpInteractive.Templates
```

Create a console project "Build" containing a script from the template *__build__*
Expand Down
2 changes: 1 addition & 1 deletion Samples/MySampleLib/Build/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@
+ HttpUtility.UrlEncode(warning));
}

// Asynchronous wayS
// Asynchronous way
var cts = new CancellationTokenSource();
/*await new DotNetTest()
.WithConfiguration(configuration)
Expand Down

0 comments on commit 8770d90

Please sign in to comment.