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

Implement logging #57

Merged
merged 2 commits into from
Sep 7, 2023
Merged
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
6 changes: 6 additions & 0 deletions Sources/Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
</PropertyGroup>
<ItemGroup>
<PackageVersion Include="codeessentials.Extensions.Logging.Demystifier" Version="1.1.66" />
<PackageVersion Include="Kysect.CommonLib" Version="0.1.6" />
<PackageVersion Include="Kysect.Editorconfig" Version="1.0.5" />
<PackageVersion Include="Microsoft.Extensions.Configuration" Version="7.0.0" />
Expand All @@ -11,8 +12,13 @@
<PackageVersion Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="7.0.0" />
<PackageVersion Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" />
<PackageVersion Include="Microsoft.Extensions.Hosting" Version="7.0.1" />
<PackageVersion Include="Microsoft.Extensions.Logging.Abstractions" Version="7.0.1" />
<PackageVersion Include="Microsoft.Extensions.Options" Version="7.0.1" />
<PackageVersion Include="Microsoft.Extensions.Options.DataAnnotations" Version="7.0.0" />
<PackageVersion Include="Serilog" Version="3.0.1" />
<PackageVersion Include="Serilog.Extensions.Logging" Version="7.0.0" />
<PackageVersion Include="Serilog.Settings.Configuration" Version="7.0.1" />
<PackageVersion Include="Serilog.Sinks.Console" Version="4.1.0" />
<PackageVersion Include="System.ComponentModel.Annotations" Version="5.0.0" />
<PackageVersion Include="Markdig" Version="0.33.0" />
<PackageVersion Include="FluentAssertions" Version="[6.12.0, )" />
Expand Down
26 changes: 24 additions & 2 deletions Sources/Kysect.Configuin.Console/DependencyBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,10 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Serilog;
using ILogger = Microsoft.Extensions.Logging.ILogger;

namespace Kysect.Configuin.Console;

Expand All @@ -22,6 +25,7 @@ public static IServiceProvider InitializeServiceProvider()
IServiceCollection serviceCollection = builder.Services;

serviceCollection.AddOptionsWithValidation<ConfiguinConfiguration>(nameof(ConfiguinConfiguration));
serviceCollection.AddSingleton(CreateLogger);

serviceCollection.AddSingleton<IEditorConfigContentProvider>(sp =>
{
Expand All @@ -39,15 +43,33 @@ public static IServiceProvider InitializeServiceProvider()
return new MsLearnDocumentationInfoLocalProvider(options.Value.MsLearnRepositoryPath);
});

serviceCollection.AddSingleton<IMsLearnDocumentationParser>(_ => new MsLearnDocumentationParser(PlainTextExtractor.Create()));
serviceCollection.AddSingleton<IMsLearnDocumentationParser>(sp =>
{
ILogger logger = sp.GetRequiredService<ILogger>();
return new MsLearnDocumentationParser(PlainTextExtractor.Create(), logger);
});
serviceCollection.AddSingleton<ICodeStyleGenerator, CodeStyleGenerator>();
serviceCollection.AddSingleton<ICodeStyleWriter>(sp =>
{
IOptions<ConfiguinConfiguration> options = sp.GetRequiredService<IOptions<ConfiguinConfiguration>>();
ILogger logger = sp.GetRequiredService<ILogger>();

return new MarkdownCodeStyleWriter(options.Value.OutputPath);
return new MarkdownCodeStyleWriter(options.Value.OutputPath, logger);
});

return serviceCollection.BuildServiceProvider();
}

public static ILogger CreateLogger(IServiceProvider serviceProvider)
{
LoggerConfiguration loggerConfiguration = new LoggerConfiguration()
.MinimumLevel.Verbose()
.WriteTo.Console();

ILoggerFactory loggerFactory = new LoggerFactory()
.DemystifyExceptions()
.AddSerilog(loggerConfiguration.CreateLogger());

return loggerFactory.CreateLogger("Tests");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,16 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="codeessentials.Extensions.Logging.Demystifier" />
<PackageReference Include="Kysect.CommonLib" />
<PackageReference Include="Kysect.Editorconfig" />
<PackageReference Include="Microsoft.Extensions.Configuration" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" />
<PackageReference Include="Serilog" />
<PackageReference Include="Serilog.Extensions.Logging" />
<PackageReference Include="Serilog.Settings.Configuration" />
<PackageReference Include="Serilog.Sinks.Console" />
</ItemGroup>

<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,4 +29,9 @@ public void ThrowIfAnyError()
throw new CmdProcessException($"Return {ExitCode} exit code.");
}
}

public bool IsAnyError()
{
return Errors.Any() || ExitCode != 0;
}
}
25 changes: 23 additions & 2 deletions Sources/Kysect.Configuin.Core/CliExecution/CmdProcess.cs
Original file line number Diff line number Diff line change
@@ -1,25 +1,46 @@
using System.Diagnostics;
using Kysect.CommonLib.Logging;
using Microsoft.Extensions.Logging;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace Kysect.Configuin.Core.CliExecution;

public class CmdProcess
{
private readonly ILogger _logger;

public CmdProcess(ILogger logger)
{
_logger = logger;
}

public CmdExecutionResult ExecuteCommand(string command)
{

using var process = new Process();

ProcessStartInfo startInfo = CreateProcessStartInfo(command);

_logger.LogTrace("Execute cmd command {command} {arguments}", startInfo.FileName, startInfo.Arguments);

process.StartInfo = startInfo;
process.Start();
process.WaitForExit();

int exitCode = process.ExitCode;
IReadOnlyCollection<string> errors = GetErrors(process);
var cmdExecutionResult = new CmdExecutionResult(exitCode, errors);

if (cmdExecutionResult.IsAnyError())
{
_logger.LogError("Finished with {exitCode} and {errorCount} errors.", exitCode, errors.Count);
foreach (string error in cmdExecutionResult.Errors)
_logger.LogTabError(1, error);
}

process.Close();

return new CmdExecutionResult(exitCode, errors);
return cmdExecutionResult;
}

private ProcessStartInfo CreateProcessStartInfo(string command)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,29 +3,42 @@
using Kysect.Configuin.Core.EditorConfigParsing;
using Kysect.Configuin.Core.EditorConfigParsing.Settings;
using Kysect.Configuin.Core.RoslynRuleModels;
using Microsoft.Extensions.Logging;

namespace Kysect.Configuin.Core.CodeStyleGeneration;

public class CodeStyleGenerator : ICodeStyleGenerator
{
private readonly ILogger _logger;

public CodeStyleGenerator(ILogger logger)
{
_logger = logger;
}

public CodeStyle Generate(EditorConfigSettings editorConfigSettings, RoslynRules roslynRules)
{
_logger.LogInformation("Start code style generating.");

IReadOnlyCollection<RoslynStyleRuleOption> roslynRuleOptions = roslynRules.GetOptions();
IReadOnlyCollection<IEditorConfigSetting> notProcessedSettings = editorConfigSettings.Settings;

_logger.LogInformation("Try parse {count} settings", notProcessedSettings.Count);
notProcessedSettings = notProcessedSettings.Where(IsSupported).ToList();

IReadOnlyCollection<CodeStyleRoslynOptionConfiguration> optionConfigurations = notProcessedSettings
.OfType<RoslynOptionEditorConfigSetting>()
.Select(o => ParseOptionSettings(o, roslynRuleOptions))
.ToList();
_logger.LogInformation("Parsed {count} option configurations", optionConfigurations.Count);

notProcessedSettings = notProcessedSettings.Where(r => r is not RoslynOptionEditorConfigSetting).ToList();

IReadOnlyCollection<ICodeStyleElement> ruleConfiguration = notProcessedSettings
.OfType<RoslynSeverityEditorConfigSetting>()
.Select(severitySetting => ParseRuleSettings(severitySetting, optionConfigurations, roslynRules))
.ToList();
_logger.LogInformation("Parsed {count} rule severity", ruleConfiguration.Count);

notProcessedSettings = notProcessedSettings.Where(r => r is not RoslynSeverityEditorConfigSetting).ToList();

Expand All @@ -48,16 +61,23 @@ private bool IsSupported(IEditorConfigSetting setting)
if (setting is RoslynSeverityEditorConfigSetting severityEditorConfigRule
&& severityEditorConfigRule.RuleId.Equals(RoslynRuleId.Parse("IDE1006")))
{
_logger.LogWarning("Rule IDE0055 is not supported and will be skipped.");
return false;
}

// TODO: #35 Probably, most of this rules related to IDE1006
if (setting is CompositeRoslynOptionEditorConfigSetting)
if (setting is CompositeRoslynOptionEditorConfigSetting compositeSetting)
{
_logger.LogWarning("{setting} is not supported and will be skipped.", compositeSetting.ToDisplayString());
return false;
}

// TODO: Maybe we need to support it in some way
if (setting is GeneralEditorConfigSetting)
if (setting is GeneralEditorConfigSetting generalSetting)
{
_logger.LogWarning("{option} is not supported and will be skipped.", generalSetting.ToDisplayString());
return false;
}

return true;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,22 @@
using Kysect.CommonLib.Exceptions;
using Kysect.Configuin.Core.CodeStyleGeneration.Models;
using Microsoft.Extensions.Logging;

namespace Kysect.Configuin.Core.CodeStyleGeneration.Markdown;

public class MarkdownCodeStyleFormatter : ICodeStyleFormatter
{
private readonly ILogger _logger;

public MarkdownCodeStyleFormatter(ILogger logger)
{
_logger = logger;
}

public string Format(CodeStyle codeStyle)
{
_logger.LogInformation("Formatting code style to markdown.");

var strings = codeStyle.Elements
.Select(FormatRule)
.ToList();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,21 +1,26 @@
using Kysect.Configuin.Core.CodeStyleGeneration.Models;
using Microsoft.Extensions.Logging;

namespace Kysect.Configuin.Core.CodeStyleGeneration.Markdown;

public class MarkdownCodeStyleWriter : ICodeStyleWriter
{
private readonly MarkdownCodeStyleFormatter _formatter = new MarkdownCodeStyleFormatter();

private readonly string _filePath;
private readonly ILogger _logger;

private readonly MarkdownCodeStyleFormatter _formatter;

public MarkdownCodeStyleWriter(string filePath)
public MarkdownCodeStyleWriter(string filePath, ILogger logger)
{
_formatter = new MarkdownCodeStyleFormatter(logger);
_filePath = filePath;
_logger = logger;
}

public void Write(CodeStyle codeStyle)
{
string content = _formatter.Format(codeStyle);
_logger.LogInformation("Writing code style as markdown to file {filePath}", _filePath);
File.WriteAllText(_filePath, content);
}
}
13 changes: 11 additions & 2 deletions Sources/Kysect.Configuin.Core/DotnetFormat/DotnetFormatCli.cs
Original file line number Diff line number Diff line change
@@ -1,19 +1,28 @@
using Kysect.Configuin.Core.CliExecution;
using Microsoft.Extensions.Logging;

namespace Kysect.Configuin.Core.DotnetFormat;

public class DotnetFormatCli
{
private readonly CmdProcess _cmdProcess = new CmdProcess();
private readonly ILogger _logger;
private readonly CmdProcess _cmdProcess;

public DotnetFormatCli(ILogger logger)
{
_cmdProcess = new CmdProcess(logger);
_logger = logger;
}

public void Validate()
{
_logger.LogInformation("Try to use dotnet format");
_cmdProcess.ExecuteCommand("dotnet format -h").ThrowIfAnyError();
}

public void GenerateWarnings(string pathToSolution, string pathToJson)
{

_logger.LogInformation("Generate warnings for {pathToSolution} and write result to {pathToJson}", pathToSolution, pathToJson);
_cmdProcess.ExecuteCommand($"dotnet format \"{pathToSolution}\" --verify-no-changes --report \"{pathToJson}\"").ThrowIfAnyError();
}
}
Original file line number Diff line number Diff line change
@@ -1,18 +1,28 @@
using Kysect.CommonLib.BaseTypes.Extensions;
using Kysect.CommonLib.Collections.Diff;
using Microsoft.Extensions.Logging;
using System.Text.Json;

namespace Kysect.Configuin.Core.DotnetFormat;

public class DotnetFormatReportComparator
{
public static CollectionDiff<DotnetFormatFileReport> Compare(string left, string right)
private readonly ILogger _logger;

public DotnetFormatReportComparator(ILogger logger)
{
_logger = logger;
}

public CollectionDiff<DotnetFormatFileReport> Compare(string left, string right)
{
_logger.LogInformation("Comparing dotnet format report between {left} and {right}", left, right);

IReadOnlyCollection<DotnetFormatFileReport> leftReports = JsonSerializer.Deserialize<IReadOnlyCollection<DotnetFormatFileReport>>(left).ThrowIfNull();
IReadOnlyCollection<DotnetFormatFileReport> rightReports = JsonSerializer.Deserialize<IReadOnlyCollection<DotnetFormatFileReport>>(right).ThrowIfNull();

var diff = CollectionDiff.Create(leftReports, rightReports, DotnetFormatFileReportComparator.Instance);

_logger.LogInformation("Same: {same}, added: {added}, removed: {removed}", diff.Same, diff.Added, diff.Removed);
return diff;
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,17 +1,21 @@
using Kysect.Configuin.Core.EditorConfigParsing.Settings;
using Kysect.Configuin.Core.IniParsing;
using Kysect.Configuin.Core.RoslynRuleModels;
using Microsoft.Extensions.Logging;

namespace Kysect.Configuin.Core.EditorConfigParsing;

public class EditorConfigSettingsParser : IEditorConfigSettingsParser
{
private readonly IniParser _iniParser = new IniParser();
private readonly ILogger _logger;

private readonly IniParser _iniParser = new IniParser();
private readonly HashSet<string> _generalRuleKeys;

public EditorConfigSettingsParser()
public EditorConfigSettingsParser(ILogger logger)
{
_logger = logger;

// TODO: Investigate other rules
_generalRuleKeys = new HashSet<string>
{
Expand All @@ -23,6 +27,8 @@ public EditorConfigSettingsParser()

public EditorConfigSettings Parse(string content)
{
_logger.LogInformation("Parse .editorconfig file");

IReadOnlyCollection<IniFileLine> iniFileLines = _iniParser.Parse(content);

var rules = iniFileLines
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,23 @@ public interface IEditorConfigSetting
public record CompositeRoslynOptionEditorConfigSetting(
IReadOnlyCollection<string> KeyParts,
string Value,
RoslynRuleSeverity? Severity) : IEditorConfigSetting;
RoslynRuleSeverity? Severity) : IEditorConfigSetting
{
public string ToDisplayString()
{
return $"{string.Join('.', KeyParts)} = {Value} (Severity: {Severity})";
}
}

public record GeneralEditorConfigSetting(
string Key,
string Value) : IEditorConfigSetting;
string Value) : IEditorConfigSetting
{
public string ToDisplayString()
{
return $"{Key} = {Value}";
}
}

public record RoslynOptionEditorConfigSetting(
string Key,
Expand Down
Loading