Skip to content

Commit

Permalink
Returning errors from csharpier cli. Make sure we don't hang the old …
Browse files Browse the repository at this point in the history
…stdout version when cli fails (#1191)
  • Loading branch information
belav authored Apr 7, 2024
1 parent e95599a commit 1ee22ea
Show file tree
Hide file tree
Showing 19 changed files with 207 additions and 162 deletions.
6 changes: 4 additions & 2 deletions Src/CSharpier.Cli.Tests/ServerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ namespace CSharpier.Cli.Tests;

using System.Diagnostics;
using System.Net.Http.Json;
using CSharpier.Cli.Server;
using FluentAssertions;
using NUnit.Framework;

Expand All @@ -15,7 +16,7 @@ public class ServerTests
// ignore file
// option file
[Test]
[Ignore("Not working on GH, test on linux?")]
[Ignore("Not working on GH, test locally on linux?")]
public async Task Stuff()
{
var path = Path.Combine(Directory.GetCurrentDirectory(), "dotnet-csharpier.dll");
Expand All @@ -41,7 +42,7 @@ public async Task Stuff()
string.Empty
);
var port = int.Parse(portString);
var data = new FormatFileDto
var data = new FormatFileParameter
{
fileName = "/Temp/test.cs",
fileContents = "public class TestClass { }"
Expand All @@ -58,6 +59,7 @@ public async Task Stuff()
Assert.Fail("Result is null");
}

result!.status.Should().Be(Status.Formatted);
result!.formattedFile!.TrimEnd().Should().Be("public class TestClass { }");
}
finally
Expand Down
4 changes: 4 additions & 0 deletions Src/CSharpier.Cli/CSharpier.Cli.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@
<PackageReference Include="System.Text.Encoding.CodePages" />
<PackageReference Include="YamlDotNet" />
<FrameworkReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Microsoft.CodeAnalysis.PublicApiAnalyzers">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleToAttribute">
Expand Down
2 changes: 1 addition & 1 deletion Src/CSharpier.Cli/CommandLineFormatterResult.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
namespace CSharpier.Cli;

public class CommandLineFormatterResult
internal class CommandLineFormatterResult
{
// these are fields instead of properties so that Interlocked.Increment may be used on them.
public int FailedSyntaxTreeValidation;
Expand Down
2 changes: 1 addition & 1 deletion Src/CSharpier.Cli/CommandLineOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ namespace CSharpier.Cli;

using Microsoft.Extensions.Logging;

public class CommandLineOptions
internal class CommandLineOptions
{
public string[] DirectoryOrFilePaths { get; init; } = Array.Empty<string>();
public bool Check { get; init; }
Expand Down
2 changes: 1 addition & 1 deletion Src/CSharpier.Cli/ConsoleLogger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

namespace CSharpier.Cli;

public class ConsoleLogger : ILogger
internal class ConsoleLogger : ILogger
{
private static readonly object ConsoleLock = new();

Expand Down
2 changes: 1 addition & 1 deletion Src/CSharpier.Cli/EditorConfig/Section.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ namespace CSharpier.Cli.EditorConfig;
using DotNet.Globbing;
using IniParser.Model;

public class Section
internal class Section
{
private readonly Glob matcher;
public string Pattern { get; }
Expand Down
2 changes: 1 addition & 1 deletion Src/CSharpier.Cli/HasMismatchedCliAndMsBuildVersions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

namespace CSharpier.Cli;

public static class HasMismatchedCliAndMsBuildVersions
internal static class HasMismatchedCliAndMsBuildVersions
{
public static bool Check(string directoryName, IFileSystem fileSystem, ILogger logger)
{
Expand Down
4 changes: 2 additions & 2 deletions Src/CSharpier.Cli/IConsole.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

namespace CSharpier.Cli;

public interface IConsole
internal interface IConsole
{
void WriteLine(string? line = null);
void WriteErrorLine(string? line = null);
Expand All @@ -13,7 +13,7 @@ public interface IConsole
void ResetColor();
}

public class SystemConsole : IConsole
internal class SystemConsole : IConsole
{
public SystemConsole()
{
Expand Down
4 changes: 2 additions & 2 deletions Src/CSharpier.Cli/IgnoreFile.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

namespace CSharpier.Cli;

public class IgnoreFile
internal class IgnoreFile
{
protected Ignore.Ignore Ignore { get; }
protected string IgnoreBaseDirectoryPath { get; }
Expand Down Expand Up @@ -105,7 +105,7 @@ var line in await fileSystem.File.ReadAllLinesAsync(ignoreFilePath, cancellation
}
}

public class InvalidIgnoreFileException : Exception
internal class InvalidIgnoreFileException : Exception
{
public InvalidIgnoreFileException(string message, Exception exception)
: base(message, exception) { }
Expand Down
8 changes: 5 additions & 3 deletions Src/CSharpier.Cli/PipeMultipleFilesFormatter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ namespace CSharpier.Cli;
using System.Text;
using Microsoft.Extensions.Logging;

public static class PipeMultipleFilesFormatter
internal static class PipeMultipleFilesFormatter
{
public static async Task<int> StartServer(
SystemConsole console,
Expand Down Expand Up @@ -80,8 +80,6 @@ CancellationToken cancellationToken
cancellationToken
);

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

if (result != 0)
{
exitCode = result;
Expand All @@ -91,6 +89,10 @@ CancellationToken cancellationToken
{
logger.LogError(ex, "Failed!");
}
finally
{
console.Write('\u0003'.ToString());
}

stringBuilder.Clear();
fileName = null;
Expand Down
4 changes: 3 additions & 1 deletion Src/CSharpier.Cli/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@

namespace CSharpier.Cli;

public class Program
using CSharpier.Cli.Server;

internal class Program
{
public static async Task<int> Main(string[] args)
{
Expand Down
1 change: 1 addition & 0 deletions Src/CSharpier.Cli/PublicAPI.Shipped.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
#nullable enable
18 changes: 18 additions & 0 deletions Src/CSharpier.Cli/PublicAPI.Unshipped.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
CSharpier.Cli.Server.FormatFileParameter
CSharpier.Cli.Server.FormatFileParameter.fileContents.get -> string!
CSharpier.Cli.Server.FormatFileParameter.fileContents.set -> void
CSharpier.Cli.Server.FormatFileParameter.fileName.get -> string!
CSharpier.Cli.Server.FormatFileParameter.fileName.set -> void
CSharpier.Cli.Server.FormatFileParameter.FormatFileParameter() -> void
CSharpier.Cli.Server.FormatFileResult
CSharpier.Cli.Server.FormatFileResult.errorMessage.get -> string?
CSharpier.Cli.Server.FormatFileResult.errorMessage.set -> void
CSharpier.Cli.Server.FormatFileResult.FormatFileResult(CSharpier.Cli.Server.Status status) -> void
CSharpier.Cli.Server.FormatFileResult.formattedFile.get -> string?
CSharpier.Cli.Server.FormatFileResult.formattedFile.set -> void
CSharpier.Cli.Server.FormatFileResult.status.get -> CSharpier.Cli.Server.Status
CSharpier.Cli.Server.FormatFileResult.status.set -> void
CSharpier.Cli.Server.Status
CSharpier.Cli.Server.Status.Failed = 2 -> CSharpier.Cli.Server.Status
CSharpier.Cli.Server.Status.Formatted = 0 -> CSharpier.Cli.Server.Status
CSharpier.Cli.Server.Status.Ignored = 1 -> CSharpier.Cli.Server.Status
68 changes: 68 additions & 0 deletions Src/CSharpier.Cli/Server/CSharpierServiceImplementation.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
namespace CSharpier.Cli.Server;

using System.IO.Abstractions;
using CSharpier.Cli.Options;

internal class CSharpierServiceImplementation
{
private readonly string? configPath;
private readonly IFileSystem fileSystem;
private readonly ConsoleLogger logger;

public CSharpierServiceImplementation(string? configPath, ConsoleLogger logger)
{
this.configPath = configPath;
this.logger = logger;
this.fileSystem = new FileSystem();
}

public async Task<FormatFileResult> FormatFile(
FormatFileParameter formatFileParameter,
CancellationToken cancellationToken
)
{
try
{
var directoryName = this.fileSystem.Path.GetDirectoryName(formatFileParameter.fileName);
DebugLogger.Log(directoryName ?? string.Empty);
if (directoryName == null)
{
throw new Exception(
$"There was no directory found for file {formatFileParameter.fileName}"
);
}

var optionsProvider = await OptionsProvider.Create(
directoryName,
this.configPath,
this.fileSystem,
this.logger,
cancellationToken
);

if (
GeneratedCodeUtilities.IsGeneratedCodeFile(formatFileParameter.fileName)
|| optionsProvider.IsIgnored(formatFileParameter.fileName)
)
{
return new FormatFileResult(Status.Ignored);
}

var result = await CSharpFormatter.FormatAsync(
formatFileParameter.fileContents,
optionsProvider.GetPrinterOptionsFor(formatFileParameter.fileName),
cancellationToken
);

return new FormatFileResult(Status.Formatted) { formattedFile = result.Code };
}
catch (Exception ex)
{
DebugLogger.Log(ex.ToString());
return new FormatFileResult(Status.Failed)
{
errorMessage = "An exception was thrown\n" + ex
};
}
}
}
7 changes: 7 additions & 0 deletions Src/CSharpier.Cli/Server/FormatFileParameter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
namespace CSharpier.Cli.Server;

public class FormatFileParameter
{
public required string fileContents { get; set; }
public required string fileName { get; set; }
}
12 changes: 12 additions & 0 deletions Src/CSharpier.Cli/Server/FormatFileResult.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
namespace CSharpier.Cli.Server;

using System.Text.Json.Serialization;

public class FormatFileResult(Status status)
{
public string? formattedFile { get; set; }

[JsonConverter(typeof(JsonStringEnumConverter))]
public Status status { get; set; } = status;
public string? errorMessage { get; set; }
}
68 changes: 68 additions & 0 deletions Src/CSharpier.Cli/Server/ServerFormatter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
namespace CSharpier.Cli.Server;

using System.Net;
using System.Net.NetworkInformation;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Logging;

internal static class ServerFormatter
{
public static async Task<int> StartServer(
int? port,
ConsoleLogger logger,
string? actualConfigPath,
CancellationToken cancellationToken
)
{
var thePort = port ?? FindFreePort();
var builder = WebApplication.CreateBuilder();
builder.WebHost.ConfigureKestrel(
(_, serverOptions) =>
{
serverOptions.Listen(IPAddress.Loopback, thePort);
}
);

var app = builder.Build();
var service = new CSharpierServiceImplementation(actualConfigPath, logger);
app.MapPost(
"/format",
(FormatFileParameter formatFileDto, CancellationToken cancellationToken) =>
service.FormatFile(formatFileDto, cancellationToken)
);
logger.LogInformation("Started on " + thePort);

await app.RunAsync();

Console.ReadKey();

return 0;
}

public static int FindFreePort()
{
const int startPort = 49152;
const int endPort = 65535;
var ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
var tcpConnInfoArray = ipGlobalProperties.GetActiveTcpConnections();
var ipEndPoint = ipGlobalProperties.GetActiveTcpListeners();

var usedPorts = ipEndPoint
.Select(o => o.Port)
.Concat(tcpConnInfoArray.Select(o => o.LocalEndPoint.Port))
.ToList();

for (var i = startPort; i < endPort; i++)
{
if (!usedPorts.Contains(i))
{
return i;
}
}

throw new InvalidOperationException(
$"Could not find any free TCP port between ports {startPort}-{endPort}"
);
}
}
8 changes: 8 additions & 0 deletions Src/CSharpier.Cli/Server/Status.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
namespace CSharpier.Cli.Server;

public enum Status
{
Formatted,
Ignored,
Failed
}
Loading

0 comments on commit 1ee22ea

Please sign in to comment.