Skip to content

Commit

Permalink
POC for grpc
Browse files Browse the repository at this point in the history
  • Loading branch information
belav committed Sep 3, 2023
1 parent ca73769 commit 0f3e397
Show file tree
Hide file tree
Showing 20 changed files with 1,087 additions and 153 deletions.
3 changes: 3 additions & 0 deletions Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@
<PackageVersion Include="DotNet.Glob" Version="3.1.3" />
<PackageVersion Include="FluentAssertions" Version="5.10.3" />
<PackageVersion Include="GitHubActionsTestLogger" Version="2.3.2" />
<PackageVersion Include="Google.Protobuf" Version="3.24.2" />
<PackageVersion Include="Grpc.Core" Version="2.46.6" />
<PackageVersion Include="Grpc.Tools" Version="2.57.0" />
<PackageVersion Include="Ignore" Version="0.1.48" />
<PackageVersion Include="ini-parser-netstandard" Version="2.5.2" />
<PackageVersion Include="Microsoft.AspNetCore.SpaServices.Extensions" Version="5.0.1" />
Expand Down
12 changes: 6 additions & 6 deletions Src/CSharpier.Cli.Tests/CSharpier.Cli.Tests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,14 @@
<SignAssembly>True</SignAssembly>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="CliWrap"/>
<PackageReference Include="FluentAssertions"/>
<PackageReference Include="CliWrap" />
<PackageReference Include="FluentAssertions" />
<PackageReference Include="GitHubActionsTestLogger" PrivateAssets="all" />
<PackageReference Include="Microsoft.NET.Test.Sdk"/>
<PackageReference Include="NUnit"/>
<PackageReference Include="NUnit3TestAdapter"/>
<PackageReference Include="Microsoft.NET.Test.Sdk" />
<PackageReference Include="NUnit" />
<PackageReference Include="NUnit3TestAdapter" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\CSharpier.Cli\CSharpier.Cli.csproj"/>
<ProjectReference Include="..\CSharpier.Cli\CSharpier.Cli.csproj" />
</ItemGroup>
</Project>
52 changes: 0 additions & 52 deletions Src/CSharpier.Cli.Tests/CliTests.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
using System;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using CliWrap;
using CliWrap.Buffered;
using FluentAssertions;
using NUnit.Framework;

Expand Down Expand Up @@ -491,53 +488,4 @@ private void EnsureExists(DirectoryInfo directoryInfo)
directoryInfo.Create();
}
}

private class CsharpierProcess
{
private readonly StringBuilder output = new();
private readonly StringBuilder errorOutput = new();
private Command command;

private readonly Encoding encoding = Encoding.UTF8;

public CsharpierProcess()
{
var path = Path.Combine(Directory.GetCurrentDirectory(), "dotnet-csharpier.dll");

this.command = CliWrap.Cli
.Wrap("dotnet")
.WithArguments(path)
.WithWorkingDirectory(testFileDirectory)
.WithValidation(CommandResultValidation.None)
.WithStandardOutputPipe(PipeTarget.ToStringBuilder(this.output, this.encoding))
.WithStandardErrorPipe(PipeTarget.ToStringBuilder(this.errorOutput, this.encoding));
}

public CsharpierProcess WithArguments(string arguments)
{
this.command = this.command.WithArguments(this.command.Arguments + " " + arguments);
return this;
}

public CsharpierProcess WithPipedInput(string input)
{
this.command = this.command.WithStandardInputPipe(
PipeSource.FromString(input, this.encoding)
);

return this;
}

public async Task<ProcessResult> ExecuteAsync()
{
var result = await this.command.ExecuteBufferedAsync(this.encoding);
return new ProcessResult(
this.output.ToString(),
this.errorOutput.ToString(),
result.ExitCode
);
}

public record ProcessResult(string Output, string ErrorOutput, int ExitCode);
}
}
59 changes: 59 additions & 0 deletions Src/CSharpier.Cli.Tests/CsharpierProcess.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
namespace CSharpier.Cli.Tests;

using System.Text;
using CliWrap;
using CliWrap.Buffered;

public class CsharpierProcess
{
private static readonly string testFileDirectory = Path.Combine(
Directory.GetCurrentDirectory(),
"TestFiles"
);

private readonly StringBuilder output = new();
private readonly StringBuilder errorOutput = new();
private Command command;

private readonly Encoding encoding = Encoding.UTF8;

public CsharpierProcess()
{
var path = Path.Combine(Directory.GetCurrentDirectory(), "dotnet-csharpier.dll");

this.command = Cli
.Wrap("dotnet")
.WithArguments(path)
.WithWorkingDirectory(testFileDirectory)
.WithValidation(CommandResultValidation.None)
.WithStandardOutputPipe(PipeTarget.ToStringBuilder(this.output, this.encoding))
.WithStandardErrorPipe(PipeTarget.ToStringBuilder(this.errorOutput, this.encoding));
}

public CsharpierProcess WithArguments(string arguments)
{
this.command = this.command.WithArguments(this.command.Arguments + " " + arguments);
return this;
}

public CsharpierProcess WithPipedInput(string input)
{
this.command = this.command.WithStandardInputPipe(
PipeSource.FromString(input, this.encoding)
);

return this;
}

public async Task<ProcessResult> ExecuteAsync()
{
var result = await this.command.ExecuteBufferedAsync(this.encoding);
return new ProcessResult(
this.output.ToString(),
this.errorOutput.ToString(),
result.ExitCode
);
}

public record ProcessResult(string Output, string ErrorOutput, int ExitCode);
}
47 changes: 47 additions & 0 deletions Src/CSharpier.Cli.Tests/GrpcTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
namespace CSharpier.Cli.Tests;

using System.Diagnostics;
using System.Text;
using CSharpierService.Generated;
using FluentAssertions;
using Grpc.Core;
using NUnit.Framework;

[TestFixture]
public class GrpcTests
{
// can this used named pipes instead of ports?
// may not be happy in VSCode, see this, and try getting it working in js
// https://gist.github.com/badsyntax/9827722afcb33a4b0e03c809f1aede98
// also make sure it will work in java
[Test]
public async Task Stuff()
{
var path = Path.Combine(Directory.GetCurrentDirectory(), "dotnet-csharpier.dll");

var processStartInfo = new ProcessStartInfo("dotnet", $"{path} --named-pipe")
{
RedirectStandardInput = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
StandardOutputEncoding = Encoding.UTF8,
StandardErrorEncoding = Encoding.UTF8,
UseShellExecute = false,
CreateNoWindow = true
};

processStartInfo.EnvironmentVariables["DOTNET_NOLOGO"] = "1";
var process = new Process { StartInfo = processStartInfo };
process.Start();

var output = await process.StandardOutput.ReadLineAsync();

var channel = new Channel("localhost", 50052, ChannelCredentials.Insecure);
var client = new CSharpierService.CSharpierServiceClient(channel);

var data = new FormatFileDto { FileName = "test.cs", FileContents = "public class TestClass { }"};
var result = await client.FormatFileAsync(data);

result.FormattedFile.Should().Be("public class TestClass { }");
}
}
7 changes: 7 additions & 0 deletions Src/CSharpier.Cli/CSharpier.Cli.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,12 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="DotNet.Glob" />
<PackageReference Include="Google.Protobuf" />
<PackageReference Include="Grpc.Core" />
<PackageReference Include="Grpc.Tools">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Ignore" />
<PackageReference Include="ini-parser-netstandard" />
<PackageReference Include="Microsoft.Extensions.Logging" />
Expand All @@ -31,6 +37,7 @@
</AssemblyAttribute>
</ItemGroup>
<ItemGroup>
<Protobuf Include="Protos\*.proto" />
<None Include="..\..\logo.png" Pack="true" PackagePath="">
<Link>logo.png</Link>
</None>
Expand Down
12 changes: 11 additions & 1 deletion Src/CSharpier.Cli/CommandLineOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ internal delegate Task<int> Handler(
bool skipWrite,
bool writeStdout,
bool pipeMultipleFiles,
bool namedPipe,
bool noCache,
bool noMSBuildCheck,
string config,
Expand Down Expand Up @@ -75,6 +76,11 @@ public static RootCommand Create()
new[] { "--pipe-multiple-files" },
"Keep csharpier running so that multiples files can be piped to it via stdin"
),
// TODO this needs a proper name
new Option(
new[] { "--named-pipe" },
"Keep csharpier running so that multiples files can be piped to it via stdin"
),
new Option<string>(
new[] { "--config-path" },
"Path to the CSharpier configuration file"
Expand All @@ -87,7 +93,11 @@ public static RootCommand Create()
{
return "--pipe-multiple-files may only be used if you pipe stdin to CSharpier";
}
if (!Console.IsInputRedirected && !cmd.Children.Contains("directoryOrFile"))
if (
!Console.IsInputRedirected
&& !cmd.Children.Contains("directoryOrFile")
&& !cmd.Children.Contains("--named-pipe")
)
{
return "directoryOrFile is required when not piping stdin to CSharpier";
}
Expand Down
100 changes: 100 additions & 0 deletions Src/CSharpier.Cli/PipingFormatter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
namespace CSharpier.Cli;

using System.IO.Abstractions;
using System.Text;
using Microsoft.Extensions.Logging;

public class PipingFormatter
{
public static async Task<int> PipeMultipleFiles(
SystemConsole console,
ILogger logger,
string? configPath,
CancellationToken cancellationToken
)
{
using var streamReader = new StreamReader(
Console.OpenStandardInput(),
console.InputEncoding
);

var stringBuilder = new StringBuilder();
string? fileName = null;

var exitCode = 0;

while (true)
{
while (true)
{
var value = streamReader.Read();
if (value == -1)
{
return exitCode;
}
var character = Convert.ToChar(value);
DebugLogger.Log("Got " + character);
if (character == '\u0003')
{
DebugLogger.Log("Got EOF");
break;
}

stringBuilder.Append(character);
}

if (fileName == null)
{
fileName = stringBuilder.ToString();
stringBuilder.Clear();
}
else
{
var commandLineOptions = new CommandLineOptions
{
DirectoryOrFilePaths = new[]
{
Path.Combine(Directory.GetCurrentDirectory(), fileName)
},
OriginalDirectoryOrFilePaths = new[]
{
Path.IsPathRooted(fileName)
? fileName
: fileName.StartsWith(".")
? fileName
: "./" + fileName
},
StandardInFileContents = stringBuilder.ToString(),
Fast = true,
WriteStdout = true,
ConfigPath = configPath
};

try
{
var result = await CommandLineFormatter.Format(
commandLineOptions,
new FileSystem(),
console,
logger,
cancellationToken
);

console.Write('\u0003'.ToString());

if (result != 0)
{
exitCode = result;
}
}
catch (Exception ex)
{
logger.LogError(ex, "Failed!");
}

stringBuilder.Clear();
fileName = null;
}
}
}
}
Loading

0 comments on commit 0f3e397

Please sign in to comment.