Skip to content

Commit

Permalink
Making use of ILogger
Browse files Browse the repository at this point in the history
closes #406
  • Loading branch information
belav committed Aug 28, 2021
1 parent 30f9652 commit d633d98
Show file tree
Hide file tree
Showing 12 changed files with 169 additions and 136 deletions.
28 changes: 15 additions & 13 deletions Src/CSharpier.Tests/CommandLineFormatterTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public void Format_Writes_Failed_To_Compile()
lines.First()
.Should()
.Be(
$"Warn {Path.DirectorySeparatorChar}Invalid.cs - Failed to compile so was not formatted."
$"Warning {Path.DirectorySeparatorChar}Invalid.cs - Failed to compile so was not formatted."
);
}

Expand Down Expand Up @@ -85,7 +85,9 @@ public void Format_Checks_Unformatted_File()
this.GetFileContent(unformattedFilePath).Should().Be(UnformattedClassContent);
lines.First()
.Should()
.Be($"Warn {Path.DirectorySeparatorChar}Unformatted.cs - Was not formatted.");
.StartWith(
$"Warning {Path.DirectorySeparatorChar}Unformatted.cs - Was not formatted."
);
}

[Test]
Expand Down Expand Up @@ -208,11 +210,12 @@ public void Ignore_Reports_Errors()
var path = this.fileSystem.Path.Combine(GetRootPath(), ".csharpierignore");

exitCode.Should().Be(1);
lines.Should()
.Contain(
$"The .csharpierignore file at {path} could not be parsed due to the following line:"
lines.First()
.Should()
.StartWith(
$"Error The .csharpierignore file at {path} could not be parsed due to the following line:"
);
lines.Should().Contain(@"\Src\Uploads\*.cs");
lines.First().Should().Contain(@"\Src\Uploads\*.cs");
}

[Test]
Expand Down Expand Up @@ -267,7 +270,7 @@ public void File_With_Compilation_Error_In_If_Should_Not_Lose_Code()
lines.First()
.Should()
.Be(
$"Warn {Path.DirectorySeparatorChar}Invalid.cs - Failed to compile so was not formatted."
$"Warning {Path.DirectorySeparatorChar}Invalid.cs - Failed to compile so was not formatted."
);
}

Expand Down Expand Up @@ -330,6 +333,7 @@ params string[] directoryOrFilePaths
}

var fakeConsole = new TestConsole();
var testLogger = new ConsoleLogger(fakeConsole);
var result =
CommandLineFormatter.Format(
new CommandLineOptions
Expand All @@ -342,6 +346,7 @@ params string[] directoryOrFilePaths
},
this.fileSystem,
fakeConsole,
testLogger,
CancellationToken.None
).Result;

Expand Down Expand Up @@ -371,7 +376,7 @@ private void WhenAFileExists(string path, string contents)

private class TestConsole : IConsole
{
public readonly IList<string> Lines = new List<string>();
public readonly List<string> Lines = new();

private string nextLine = "";

Expand All @@ -395,12 +400,9 @@ public void Write(string value)
nextLine += value;
}

public void WriteWithColor(string value, ConsoleColor color)
{
this.Write(value);
}

public Encoding InputEncoding => Encoding.UTF8;
public ConsoleColor ForegroundColor { get; set; }
public void ResetColor() { }

public void Close()
{
Expand Down
31 changes: 1 addition & 30 deletions Src/CSharpier.Tests/Utilities/StringDifferTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -127,36 +127,7 @@ public void PrintDifference_Should_Print_Extra_Line_Difference()

private string PrintDifference(string expected, string actual)
{
var testConsole = new TestConsole();
StringDiffer.PrintFirstDifference(expected, actual, testConsole);
return testConsole.GetOutput();
}

private class TestConsole : IConsole
{
private readonly StringBuilder stringBuilder = new();

public void WriteLine(string line = null)
{
stringBuilder.AppendLine(line);
}

public void Write(string value)
{
stringBuilder.Append(value);
}

public void WriteWithColor(string value, ConsoleColor color)
{
this.Write(value);
}

public string GetOutput()
{
return stringBuilder.ToString();
}

public Encoding InputEncoding => Encoding.UTF8;
return StringDiffer.PrintFirstDifference(expected, actual);
}
}
}
3 changes: 2 additions & 1 deletion Src/CSharpier/CSharpier.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,9 @@
<ItemGroup>
<PackageReference Include="Ignore" Version="0.1.42" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="3.8.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="5.0.0" />
<PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
<PackageReference Include="System.CommandLine" Version="2.0.0-beta1.20574.7" />
<PackageReference Include="System.CommandLine" Version="2.0.0-beta1.21308.1" />
<PackageReference Include="System.IO.Abstractions" Version="13.2.29" />
<PackageReference Include="System.IO.Abstractions.TestingHelpers" Version="13.2.29" />
<PackageReference Include="System.Text.Encoding.CodePages" Version="5.0.0" />
Expand Down
69 changes: 21 additions & 48 deletions Src/CSharpier/CommandLineFormatter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@
using System.IO.Abstractions;
using System.Linq;
using System.Text;
using System.Text.Encodings.Web;
using System.Threading;
using System.Threading.Tasks;
using CSharpier.Utilities;
using Microsoft.Extensions.Logging;

namespace CSharpier
{
Expand All @@ -22,6 +22,7 @@ public class CommandLineFormatter
protected readonly IFileSystem FileSystem;
protected readonly IConsole Console;
protected readonly IgnoreFile IgnoreFile;
protected readonly ILogger Logger;

protected CommandLineFormatter(
string baseDirectoryPath,
Expand All @@ -31,7 +32,8 @@ protected CommandLineFormatter(
IFileSystem fileSystem,
IConsole console,
IgnoreFile ignoreFile,
CommandLineFormatterResult result
CommandLineFormatterResult result,
ILogger logger
) {
this.BaseDirectoryPath = baseDirectoryPath;
this.Path = path;
Expand All @@ -41,12 +43,14 @@ CommandLineFormatterResult result
this.Console = console;
this.IgnoreFile = ignoreFile;
this.Result = result;
this.Logger = logger;
}

public static async Task<int> Format(
CommandLineOptions commandLineOptions,
IFileSystem fileSystem,
IConsole console,
ILogger logger,
CancellationToken cancellationToken
) {
var stopwatch = Stopwatch.StartNew();
Expand Down Expand Up @@ -74,7 +78,7 @@ CancellationToken cancellationToken
var ignoreFile = await IgnoreFile.Create(
baseDirectoryPath,
fileSystem,
console,
logger,
cancellationToken
);
if (ignoreFile is null)
Expand All @@ -90,7 +94,8 @@ CancellationToken cancellationToken
fileSystem,
console,
ignoreFile,
result
result,
logger
);
}

Expand Down Expand Up @@ -128,7 +133,7 @@ await commandLineFormatter.FormatFile(
result.ElapsedMilliseconds = stopwatch.ElapsedMilliseconds;
if (!commandLineOptions.ShouldWriteStandardOut)
{
ResultPrinter.PrintResults(result, console, commandLineOptions);
ResultPrinter.PrintResults(result, logger, commandLineOptions);
}
return ReturnExitCode(commandLineOptions, result);
}
Expand Down Expand Up @@ -223,10 +228,7 @@ CancellationToken cancellationToken
catch (Exception ex)
{
Interlocked.Increment(ref this.Result.Files);
WriteError(filePath, "Threw exception while formatting.");
WriteLine(ex.Message);
WriteLine(ex.StackTrace);
WriteLine();
WriteError(filePath, "Threw exception while formatting.", ex);
Interlocked.Increment(ref this.Result.ExceptionsFormatting);
return;
}
Expand All @@ -252,7 +254,7 @@ CancellationToken cancellationToken
cancellationToken.ThrowIfCancellationRequested();
Interlocked.Increment(ref this.Result.Files);

WriteResult(filePath, result, fileContents, encoding);
WriteFormattedResult(filePath, result, fileContents, encoding);
}

private async Task PerformSyntaxTreeValidation(
Expand All @@ -275,17 +277,15 @@ CancellationToken cancellationToken
if (!string.IsNullOrEmpty(failure))
{
Interlocked.Increment(ref this.Result.FailedSyntaxTreeValidation);
WriteError(file, "Failed syntax tree validation.");
WriteLine(failure);
// TODO this will look ugly
WriteError(file, $"Failed syntax tree validation.\n{failure}");
}
}
catch (Exception ex)
{
Interlocked.Increment(ref this.Result.ExceptionsValidatingSource);

WriteError(file, "Failed with exception during syntax tree validation.");
WriteLine(ex.Message);
WriteLine(ex.StackTrace);
WriteError(file, "Failed with exception during syntax tree validation.", ex);
}
}
}
Expand All @@ -297,13 +297,13 @@ private void PerformCheck(string filePath, CSharpierResult result, string fileCo
&& !this.CommandLineOptions.ShouldWriteStandardOut
&& result.Code != fileContents
) {
WriteWarning(filePath, "Was not formatted.");
StringDiffer.PrintFirstDifference(result.Code, fileContents, this.Console);
var difference = StringDiffer.PrintFirstDifference(result.Code, fileContents);
WriteWarning(filePath, $"Was not formatted.\n{difference}");
Interlocked.Increment(ref this.Result.UnformattedFiles);
}
}

private void WriteResult(
private void WriteFormattedResult(
string filePath,
CSharpierResult result,
string? fileContents,
Expand Down Expand Up @@ -353,41 +353,14 @@ private bool ShouldIgnoreFile(string filePath)
|| this.IgnoreFile.IsIgnored(filePath);
}

private void WriteError(string filePath, string value)
private void WriteError(string filePath, string value, Exception? exception = null)
{
this.WriteMessage(filePath, value, "Error", ConsoleColor.DarkRed);
this.Logger.LogError(exception, $"{GetPath(filePath)} - {value}");
}

private void WriteWarning(string filePath, string value)
{
this.WriteMessage(filePath, value, "Warn", ConsoleColor.DarkYellow);
}

private static readonly object ConsoleLock = new();

protected void WriteMessage(
string filePath,
string value,
string valueForColor,
ConsoleColor color
) {
if (this.CommandLineOptions.ShouldWriteStandardOut)
{
return;
}
lock (ConsoleLock)
{
this.Console.WriteWithColor($"{valueForColor} ", color);
this.Console.WriteLine($"{GetPath(filePath)} - {value}");
}
}

protected void WriteLine(string? line = null)
{
if (!this.CommandLineOptions.ShouldWriteStandardOut)
{
this.Console.WriteLine(line);
}
this.Logger.LogWarning($"{GetPath(filePath)} - {value}");
}
}

Expand Down
2 changes: 1 addition & 1 deletion Src/CSharpier/CommandLineOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ public static RootCommand Create()
rootCommand.AddValidator(
cmd =>
{
if (!Console.IsInputRedirected && cmd.Children["directoryOrFile"] == null)
if (!Console.IsInputRedirected && !cmd.Children.Contains("directoryOrFile"))
{
return "directoryOrFile is required when not piping stdin to CSharpier";
}
Expand Down
72 changes: 72 additions & 0 deletions Src/CSharpier/ConsoleLogger.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
using System;
using Microsoft.Extensions.Logging;

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

private readonly IConsole console;

public ConsoleLogger(IConsole console)
{
this.console = console;
}

public virtual void Log<TState>(
LogLevel logLevel,
EventId eventId,
TState state,
Exception? exception,
Func<TState, Exception, string> formatter
) {
if (!IsEnabled(logLevel))
{
return;
}

lock (ConsoleLock)
{
var message = formatter(state, exception!);

this.console.ForegroundColor = GetColorLevel(logLevel);
if (logLevel >= LogLevel.Warning)
{
this.console.Write($"{logLevel} ");
}
this.console.WriteLine(message);
this.console.ResetColor();

if (exception == null)
{
return;
}
this.console.WriteLine(exception.Message);
this.console.WriteLine(exception.StackTrace);
this.console.WriteLine();
}
}

private ConsoleColor GetColorLevel(LogLevel logLevel) =>
logLevel switch
{
LogLevel.Critical => ConsoleColor.DarkRed,
LogLevel.Error => ConsoleColor.DarkRed,
LogLevel.Warning => ConsoleColor.DarkYellow,
LogLevel.Debug => ConsoleColor.Gray,
LogLevel.Trace => ConsoleColor.Gray,
_ => ConsoleColor.White,
};

public bool IsEnabled(LogLevel logLevel)
{
return true;
}

public IDisposable BeginScope<TState>(TState state)
{
throw new NotImplementedException();
}
}
}
Loading

0 comments on commit d633d98

Please sign in to comment.