Skip to content

Commit

Permalink
Clean code
Browse files Browse the repository at this point in the history
  • Loading branch information
NikolayPianikov authored and NikolayPianikov committed Aug 4, 2021
1 parent 81e5071 commit 68d76b9
Show file tree
Hide file tree
Showing 39 changed files with 149 additions and 165 deletions.
8 changes: 4 additions & 4 deletions TeamCity.MSBuild.Logger.Tests/ColorStorageTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ public void ShouldReturnNullColorByDefault()
// When

// Then
storage.Color.ShouldBe(default(Color?));
storage.Color.ShouldBe(default);
}

[Fact]
Expand Down Expand Up @@ -42,7 +42,7 @@ public void ShouldResetColor()
storage.ResetColor();

// Then
storage.Color.ShouldBe(default(Color?));
storage.Color.ShouldBe(default);
}

[Fact]
Expand All @@ -56,7 +56,7 @@ public void ShouldResetToNullWhenLastReset()
storage.ResetColor();

// Then
storage.Color.ShouldBe(default(Color?));
storage.Color.ShouldBe(default);
}

[Fact]
Expand All @@ -73,7 +73,7 @@ public void ShouldResetToNullWhenTooManyReset()
storage.ResetColor();

// Then
storage.Color.ShouldBe(default(Color?));
storage.Color.ShouldBe(default);
}
}
}
27 changes: 15 additions & 12 deletions TeamCity.MSBuild.Logger.Tests/Helpers/CommandLine.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
namespace TeamCity.MSBuild.Logger.Tests.Helpers
// ReSharper disable MemberCanBePrivate.Global
namespace TeamCity.MSBuild.Logger.Tests.Helpers
{
using System;
using System.Collections.Generic;
Expand Down Expand Up @@ -42,25 +43,25 @@ public bool TryExecute(out CommandLineResult result)
}
};

foreach (var envVar in _environmentVariables)
foreach (var (key, value) in _environmentVariables)
{
#if NET45
if (envVar.Value == null)
if (value == null)
{
process.StartInfo.EnvironmentVariables.Remove(envVar.Key);
process.StartInfo.EnvironmentVariables.Remove(key);
}
else
{
process.StartInfo.EnvironmentVariables[envVar.Key] = envVar.Value;
process.StartInfo.EnvironmentVariables[key] = value;
}
#else
if (envVar.Value == null)
if (value == null)
{
process.StartInfo.Environment.Remove(envVar.Key);
process.StartInfo.Environment.Remove(key);
}
else
{
process.StartInfo.Environment[envVar.Key] = envVar.Value;
process.StartInfo.Environment[key] = value;
}
#endif
}
Expand All @@ -78,19 +79,21 @@ public bool TryExecute(out CommandLineResult result)

process.ErrorDataReceived += (sender, args) =>
{
if (args.Data != null)
if (args.Data == null)
{
stdError.Add(args.Data);
Console.Error.WriteLine(args.Data);
return;
}

stdError.Add(args.Data);
Console.Error.WriteLine(args.Data);
};

// ReSharper disable once LocalizableElement
Console.WriteLine($"Run: {process.StartInfo.FileName} {process.StartInfo.Arguments}");
var stopwatch = new Stopwatch();
if (!process.Start())
{
result = default(CommandLineResult);
result = default;
return false;
}

Expand Down
37 changes: 7 additions & 30 deletions TeamCity.MSBuild.Logger.Tests/Helpers/IntegrationTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ public static void ResultShouldBe([NotNull] this CommandLineResult actualResult,
if (actualResult == null) throw new ArgumentNullException(nameof(actualResult));
if (expectedResult == null) throw new ArgumentNullException(nameof(expectedResult));
actualResult.ExitCode.ShouldBe(expectedResult.ExitCode);
CheckOutput(actualResult.StdOut, expectedResult.StdOut);
CheckOutput(actualResult.StdError, expectedResult.StdError);
CheckOutput(actualResult.StdOut);
CheckOutput(actualResult.StdError);
if (producesTeamCityServiceMessages.HasValue)
{
(ServiceMessages.GetNumberServiceMessage(actualResult.StdOut) > 0).ShouldBe(producesTeamCityServiceMessages.Value);
Expand All @@ -27,10 +27,9 @@ public static void ResultShouldBe([NotNull] this CommandLineResult actualResult,
ServiceMessages.ResultShouldContainCorrectStructureAndSequence(actualResult.StdError);
}

private static void CheckOutput([NotNull] this IEnumerable<string> actualLines, [NotNull] IEnumerable<string> expectedLines)
private static void CheckOutput([NotNull] this IEnumerable<string> actualLines)
{
if (actualLines == null) throw new ArgumentNullException(nameof(actualLines));
if (expectedLines == null) throw new ArgumentNullException(nameof(expectedLines));
// ReSharper disable once PossibleMultipleEnumeration
var filteredActualLines = ServiceMessages.FilterTeamCityServiceMessages(actualLines).ToList();
// ReSharper disable once PossibleMultipleEnumeration
Expand All @@ -44,25 +43,17 @@ private static void CheckOutput([NotNull] this IEnumerable<string> actualLines,

private static void CheckLines([CanBeNull] this string actualLine, [CanBeNull] string expectedLine)
{
var modifiedActualLine = ReplaceChangableItems(actualLine);
var modifiedExpectedLine = ReplaceChangableItems(expectedLine);
var modifiedActualLine = ReplaceChangeableItems(actualLine);
var modifiedExpectedLine = ReplaceChangeableItems(expectedLine);
if (modifiedActualLine != modifiedExpectedLine)
{
Assert.Equal(modifiedActualLine, modifiedExpectedLine);
}
}

private static string ReplaceChangableItems([CanBeNull] string line)
{
if (string.IsNullOrWhiteSpace(line))
{
return line;
}
private static string ReplaceChangeableItems([CanBeNull] string line) => string.IsNullOrWhiteSpace(line) ? line : new string(ExcludeChangeableChars(line).ToArray());

return new string(ExcludeChangableChars(line).ToArray());
}

private static IEnumerable<char> ExcludeChangableChars([NotNull] IEnumerable<char> chars)
private static IEnumerable<char> ExcludeChangeableChars([NotNull] IEnumerable<char> chars)
{
if (chars == null) throw new ArgumentNullException(nameof(chars));
foreach (var c in chars)
Expand Down Expand Up @@ -95,19 +86,5 @@ public static string CreateLoggerString(

return $"TeamCity.MSBuild.Logger.TeamCityMSBuildLogger,{loggerPath}{parameters}";
}

public static IDictionary<string, string> ExtractDictionary([CanBeNull] string dict)
{
if (string.IsNullOrWhiteSpace(dict))
{
return new Dictionary<string, string>();
}

return (
from item in dict.Split(';')
let parts = item.Split('=')
where parts.Length == 2
select new { name = parts[0].Trim(), value = parts[1].Trim() }).ToDictionary(i => i.name, i => i.value);
}
}
}
2 changes: 2 additions & 0 deletions TeamCity.MSBuild.Logger.Tests/Helpers/ServiceMessages.cs
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,8 @@ public Message(IServiceMessage message)

public string OutAttr { get; }

// ReSharper disable once MemberCanBePrivate.Local
// ReSharper disable once UnusedAutoPropertyAccessor.Local
public string MessageAttr { get; }

public string DetailsAttr { get; }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ public void ShouldSendMessageAsIsWhenCannotParseAnyServiceMessages()
{
// Given
var writer = CreateInstance();
var serviceMessage = "##teamcity[abc]";
const string serviceMessage = "##teamcity[abc]";
_serviceMessageParser.Setup(i => i.ParseServiceMessages(serviceMessage.Trim())).Returns(Enumerable.Empty<IServiceMessage>());

// When
Expand Down
1 change: 0 additions & 1 deletion TeamCity.MSBuild.Logger/AnsiLogWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
{
using System;
using JetBrains.Annotations;
using JetBrains.Annotations;

// ReSharper disable once ClassNeverInstantiated.Global
internal class AnsiLogWriter : ILogWriter
Expand Down
6 changes: 3 additions & 3 deletions TeamCity.MSBuild.Logger/BuildEventManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ public void AddProjectStartedEvent(ProjectStartedEventArgs e, bool requireTimest

if (!_projectKey.TryGetValue(e.ProjectFile, out projectIncrementKey))
{
_projectIncrementKey = _projectIncrementKey + 1;
_projectIncrementKey += 1;
_projectKey.Add(e.ProjectFile, _projectIncrementKey);
projectIncrementKey = _projectIncrementKey;
}
Expand Down Expand Up @@ -98,13 +98,13 @@ select string.IsNullOrEmpty(projectCall.TargetNames)
public ProjectStartedEventMinimumFields GetProjectStartedEvent(BuildEventContext e)
{
if (e == null) throw new ArgumentNullException(nameof(e));
return _projectStartedEvents.TryGetValue(e, out ProjectStartedEventMinimumFields result) ? result : null;
return _projectStartedEvents.TryGetValue(e, out var result) ? result : null;
}

public TargetStartedEventMinimumFields GetTargetStartedEvent(BuildEventContext e)
{
if (e == null) throw new ArgumentNullException(nameof(e));
return _targetStartedEvents.TryGetValue(e, out TargetStartedEventMinimumFields result) ? result : null;
return _targetStartedEvents.TryGetValue(e, out var result) ? result : null;
}

public void RemoveProjectStartedEvent(BuildEventContext e)
Expand Down
14 changes: 3 additions & 11 deletions TeamCity.MSBuild.Logger/ColorStorage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,10 @@
// ReSharper disable once ClassNeverInstantiated.Global
internal class ColorStorage : IColorStorage
{
private Color? _color = default(Color?);
public Color? Color { get; private set; }

public Color? Color => _color;
public void SetColor(Color color) => Color = color;

public void SetColor(Color color)
{
_color = color;
}

public void ResetColor()
{
_color = default(Color?);
}
public void ResetColor() => Color = default;
}
}
1 change: 1 addition & 0 deletions TeamCity.MSBuild.Logger/DefaultColorTheme.cs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ public ConsoleColor GetConsoleColor(Color color)

public string GetAnsiColor(Color color)
{
// ReSharper disable once SwitchStatementHandlesSomeKnownEnumValuesWithDefault
switch (color)
{
case Color.Task:
Expand Down
30 changes: 16 additions & 14 deletions TeamCity.MSBuild.Logger/DefaultConsole.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,21 +22,23 @@ public DefaultConsole([NotNull] IDiagnostics diagnostics)

public void Write(string text)
{
if (!string.IsNullOrEmpty(text))
if (string.IsNullOrEmpty(text))
{
// ReSharper disable once IdentifierTypo
var reentrancy = Interlocked.Increment(ref _reentrancy) - 1;
// ReSharper disable once AccessToModifiedClosure
_diagnostics.Send(() => $"[{reentrancy} +] Write({text.Trim()})");
try
{
_out.Write(text);
}
finally
{
reentrancy = Interlocked.Decrement(ref _reentrancy);
_diagnostics.Send(() => $"[{reentrancy} -] Write({text.Trim()})");
}
return;
}

// ReSharper disable once IdentifierTypo
var reentrancy = Interlocked.Increment(ref _reentrancy) - 1;
// ReSharper disable once AccessToModifiedClosure
_diagnostics.Send(() => $"[{reentrancy} +] Write({text.Trim()})");
try
{
_out.Write(text);
}
finally
{
reentrancy = Interlocked.Decrement(ref _reentrancy);
_diagnostics.Send(() => $"[{reentrancy} -] Write({text.Trim()})");
}
}
}
Expand Down
1 change: 1 addition & 0 deletions TeamCity.MSBuild.Logger/DefaultLogWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ private static ConsoleColor BackgroundColor
{
get
{
// ReSharper disable once InvertIf
if (_supportReadingBackgroundColor)
{
try
Expand Down
29 changes: 10 additions & 19 deletions TeamCity.MSBuild.Logger/EventHandlers/BuildFinishedHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -69,14 +69,7 @@ public void Handle(BuildFinishedEventArgs e)
}
else
{
if (_context.ErrorCount > 0)
{
_logWriter.SetColor(Color.Error);
}
else
{
_logWriter.SetColor(Color.Warning);
}
_logWriter.SetColor(_context.ErrorCount > 0 ? Color.Error : Color.Warning);
}

_messageWriter.WriteNewLine();
Expand Down Expand Up @@ -228,7 +221,7 @@ private void ShowErrorWarningSummary<T>([CanBeNull] IEnumerable<T> events) where
}

var key = new ErrorWarningSummaryDictionaryKey(warningEventArgs.BuildEventContext, targetName);
if (!dictionary.TryGetValue(key, out List<T> list))
if (!dictionary.TryGetValue(key, out var list))
{
list = new List<T>();
dictionary.Add(key, list);
Expand Down Expand Up @@ -256,25 +249,23 @@ private void ShowErrorWarningSummary<T>([CanBeNull] IEnumerable<T> events) where
{
if (!string.IsNullOrEmpty(keyValuePair.Key.TargetName))
{
_messageWriter.WriteMessageAligned(_stringService.FormatResourceString("ErrorWarningInTarget", (object)keyValuePair.Key.TargetName), false);
_messageWriter.WriteMessageAligned(_stringService.FormatResourceString("ErrorWarningInTarget", keyValuePair.Key.TargetName), false);
}

curTargetName = keyValuePair.Key.TargetName;
}

foreach (var obj in keyValuePair.Value)
{
var errorEventArgs = obj as BuildErrorEventArgs;
if (errorEventArgs != null)
switch (obj)
{
_messageWriter.WriteMessageAligned(" " + _eventFormatter.FormatEventMessage(errorEventArgs, false, _context.Parameters.ShowProjectFile), false);
continue;
}
case BuildErrorEventArgs errorEventArgs:
_messageWriter.WriteMessageAligned(" " + _eventFormatter.FormatEventMessage(errorEventArgs, false, _context.Parameters.ShowProjectFile), false);
continue;

var warningEventArgs = obj as BuildWarningEventArgs;
if (warningEventArgs != null)
{
_messageWriter.WriteMessageAligned(" " + _eventFormatter.FormatEventMessage(warningEventArgs, false, _context.Parameters.ShowProjectFile), false);
case BuildWarningEventArgs warningEventArgs:
_messageWriter.WriteMessageAligned(" " + _eventFormatter.FormatEventMessage(warningEventArgs, false, _context.Parameters.ShowProjectFile), false);
break;
}
}

Expand Down
2 changes: 1 addition & 1 deletion TeamCity.MSBuild.Logger/EventHandlers/ErrorHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public void Handle(BuildErrorEventArgs e)
if (e == null) throw new ArgumentNullException(nameof(e));
if (e.BuildEventContext == null) throw new ArgumentException(nameof(e));

_context.ErrorCount = _context.ErrorCount + 1;
_context.ErrorCount += 1;
_buildEventManager.SetErrorWarningFlagOnCallStack(e.BuildEventContext);
var targetStartedEvent = _buildEventManager.GetTargetStartedEvent(e.BuildEventContext);
if (targetStartedEvent != null)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ public void Handle(ProjectStartedEventArgs e)
_performanceCounterFactory.GetOrCreatePerformanceCounter(e.ProjectFile, _context.ProjectPerformanceCounters).AddEventStarted(e.TargetNames, e.BuildEventContext, e.Timestamp, ComparerContextNodeId.Shared);
}

if (_context.DeferredMessages.TryGetValue(e.BuildEventContext, out IList<BuildMessageEventArgs> messages))
if (_context.DeferredMessages.TryGetValue(e.BuildEventContext, out var messages))
{
if (!_context.Parameters.ShowOnlyErrors && !_context.Parameters.ShowOnlyWarnings)
{
Expand Down Expand Up @@ -169,7 +169,7 @@ private void WriteProperties([NotNull] IEnumerable<Property> properties)
_messageWriter.WriteNewLine();
}

private void WriteProperties(BuildEventArgs e, IList<Property> properties)
private void WriteProperties(BuildEventArgs e, ICollection<Property> properties)
{
if (_context.Parameters.ShowOnlyErrors || _context.Parameters.ShowOnlyWarnings)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ public void Handle(TargetFinishedEventArgs e)
_logWriter.SetColor(Color.BuildStage);
if (_context.IsVerbosityAtLeast(LoggerVerbosity.Diagnostic) || (_context.Parameters.ShowEventId ?? false))
{
_messageWriter.WriteMessageAligned(_stringService.FormatResourceString("TargetMessageWithId", (object)e.Message, (object)e.BuildEventContext.TargetId), true);
_messageWriter.WriteMessageAligned(_stringService.FormatResourceString("TargetMessageWithId", e.Message, e.BuildEventContext.TargetId), true);
}
else
{
Expand Down
Loading

0 comments on commit 68d76b9

Please sign in to comment.