Skip to content

Commit

Permalink
Clean-up code by introducing String compare helpers (#288)
Browse files Browse the repository at this point in the history
  • Loading branch information
Corniel authored Nov 12, 2024
1 parent cbfd66e commit 8f1096b
Show file tree
Hide file tree
Showing 11 changed files with 56 additions and 26 deletions.
4 changes: 4 additions & 0 deletions src/Buildalyzer/Buildalyzer.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@
<PackageValidationBaselineVersion>7.0.1</PackageValidationBaselineVersion>
<OutputType>library</OutputType>
<PackageReleaseNotes>
<![CDATA[
ToBeReleased
- Drop Buildalyzer.EmptyDisposable. (BREAKING)
]]>
</PackageReleaseNotes>
</PropertyGroup>

Expand Down
6 changes: 4 additions & 2 deletions src/Buildalyzer/Compiler/FSharpCommandLineParser.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
#nullable enable

using System;

namespace Buildalyzer;

internal static class FSharpCommandLineParser
Expand Down Expand Up @@ -52,8 +54,8 @@ private static IEnumerable<string> Tokenize(string arg)

[Pure]
public static bool NotCompilerLocation(string s)
=> !s.EndsWith("fsc.dll", StringComparison.OrdinalIgnoreCase)
&& !s.EndsWith("fsc.exe", StringComparison.OrdinalIgnoreCase);
=> !s.IsMatchEnd("fsc.dll")
&& !s.IsMatchEnd("fsc.exe");

private static readonly char[] Splitters = ['\r', '\n'];
}
3 changes: 2 additions & 1 deletion src/Buildalyzer/Compiler/RoslynCommandLineParser.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#nullable enable

using System;
using Microsoft.CodeAnalysis;

namespace Buildalyzer;
Expand All @@ -17,7 +18,7 @@ internal static class RoslynCommandLineParser
{
for (var i = 0; i < args.Length - 1; i++)
{
if (args[i].EndsWith(exec, StringComparison.OrdinalIgnoreCase))
if (args[i].IsMatchEnd(exec))
{
return args[i..];
}
Expand Down
7 changes: 4 additions & 3 deletions src/Buildalyzer/Construction/ProjectFile.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.IO;
using System;
using System.IO;
using System.Xml.Linq;

namespace Buildalyzer.Construction;
Expand Down Expand Up @@ -59,8 +60,8 @@ internal ProjectFile(string path)

/// <inheritdoc />
public bool RequiresNetFramework =>
_projectElement.GetDescendants(ProjectFileNames.Import).Any(x => ImportsThatRequireNetFramework.Exists(i => x.GetAttributeValue(ProjectFileNames.Project)?.EndsWith(i, StringComparison.OrdinalIgnoreCase) ?? false))
|| _projectElement.GetDescendants(ProjectFileNames.LanguageTargets).Any(x => ImportsThatRequireNetFramework.Exists(i => x.Value.EndsWith(i, StringComparison.OrdinalIgnoreCase)))
_projectElement.GetDescendants(ProjectFileNames.Import).Any(x => ImportsThatRequireNetFramework.Exists(i => x.GetAttributeValue(ProjectFileNames.Project)?.IsMatchEnd(i) ?? false))
|| _projectElement.GetDescendants(ProjectFileNames.LanguageTargets).Any(x => ImportsThatRequireNetFramework.Exists(i => x.Value.IsMatchEnd(i)))
|| ToolsVersion != null;

/// <inheritdoc />
Expand Down
2 changes: 1 addition & 1 deletion src/Buildalyzer/Environment/BuildEnvironment.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ public sealed class BuildEnvironment
!System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription
.Replace(" ", string.Empty)
.Trim()
.StartsWith(".NETFramework", StringComparison.OrdinalIgnoreCase);
.IsMatchStart(".NETFramework");

private readonly Dictionary<string, string> _globalProperties;
private readonly Dictionary<string, string> _environmentVariables;
Expand Down
12 changes: 5 additions & 7 deletions src/Buildalyzer/Environment/DotNetInfoParser.cs
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
#nullable enable

using System;
using System.IO;

namespace Buildalyzer.Environment;

internal static class DotNetInfoParser
{
private const StringComparison IgnoreCase = StringComparison.OrdinalIgnoreCase;

[Pure]
public static DotNetInfo Parse(IEnumerable<string> lines)
{
Expand Down Expand Up @@ -94,20 +93,20 @@ void AddRunTime(string line)

[Pure]
private static Version? Version(string prefix, string line)
=> line.StartsWith(prefix, IgnoreCase) && System.Version.TryParse(line[prefix.Length..].Trim(), out var parsed)
=> line.IsMatchStart(prefix) && System.Version.TryParse(line[prefix.Length..].Trim(), out var parsed)
? parsed
: null;

[Pure]
private static string? Label(string prefix, string line)
=> line.StartsWith(prefix, IgnoreCase) && line[prefix.Length..].Trim() is { Length: > 0 } label
=> line.IsMatchStart(prefix) && line[prefix.Length..].Trim() is { Length: > 0 } label
? label
: null;

[Pure]
private static string? BasePath(string line)
{
if (line.StartsWith("Base Path:", IgnoreCase))
if (line.IsMatchStart("Base Path:"))
{
var path = line[10..].Trim();

Expand Down Expand Up @@ -142,8 +141,7 @@ void AddRunTime(string line)
private static string UnifyPath(string path) => path.Replace('\\', '/').TrimEnd('/');

[Pure]
private static string? GlobalJson(string line)
=> line.Equals("Not found", IgnoreCase) ? null : line;
private static string? GlobalJson(string line) => line.IsMatch("Not found") ? null : line;

private static readonly HashSet<string> Headers = new(StringComparer.InvariantCultureIgnoreCase)
{
Expand Down
24 changes: 24 additions & 0 deletions src/Buildalyzer/Extensions/System.String.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
namespace System;

internal static class BuildalyzerStringExtensions
{
/// <summary>
/// Returns true if the <paramref name="value"/> string has the same value, ignoring casing.
/// </summary>
[Pure]
public static bool IsMatch(this string? self, string? value) => string.Equals(self, value, StringComparison.OrdinalIgnoreCase);

/// <summary>
/// Returns true if the string starts with <paramref name="value"/>, ignoring casing.
/// </summary>
[Pure]
public static bool IsMatchStart(this string self, string value)
=> self.StartsWith(value, StringComparison.OrdinalIgnoreCase);

/// <summary>
/// Returns true if the string ends with <paramref name="value"/>, ignoring casing.
/// </summary>
[Pure]
public static bool IsMatchEnd(this string self, string value)
=> self.EndsWith(value, StringComparison.OrdinalIgnoreCase);
}
4 changes: 3 additions & 1 deletion src/Buildalyzer/IO/IOPath.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,9 @@ public override bool Equals([NotNullWhen(true)] object? obj)
/// <inheritdoc />
[Pure]
public bool Equals(IOPath other, bool caseSensitive)
=> string.Equals(_path, other._path, caseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase);
=> caseSensitive
? _path == other._path
: _path.IsMatch(other._path);

/// <inheritdoc />
[Pure]
Expand Down
8 changes: 3 additions & 5 deletions src/Buildalyzer/Logging/EventProcessor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ private void MessageRaised(object sender, BuildMessageEventArgs e)
}

// Process the command line arguments for the Fsc task
if (e.SenderName?.Equals("Fsc", StringComparison.OrdinalIgnoreCase) == true
if (e.SenderName.IsMatch("Fsc")
&& !string.IsNullOrWhiteSpace(e.Message)
&& _targetStack.Any(x => x.TargetName == "CoreCompile")
&& result.CompilerCommand is null)
Expand All @@ -161,14 +161,12 @@ private void MessageRaised(object sender, BuildMessageEventArgs e)
}

// Process the command line arguments for the Csc task
if (e is TaskCommandLineEventArgs cmd
&& string.Equals(cmd.TaskName, "Csc", StringComparison.OrdinalIgnoreCase))
if (e is TaskCommandLineEventArgs cmd && cmd.TaskName.IsMatch("Csc"))
{
result.ProcessCscCommandLine(cmd.CommandLine, _targetStack.Any(x => x.TargetName == "CoreCompile"));
}

if (e is TaskCommandLineEventArgs cmdVbc &&
string.Equals(cmdVbc.TaskName, "Vbc", StringComparison.OrdinalIgnoreCase))
if (e is TaskCommandLineEventArgs cmdVbc && cmdVbc.TaskName.IsMatch("Vbc"))
{
result.ProcessVbcCommandLine(cmdVbc.CommandLine);
}
Expand Down
4 changes: 2 additions & 2 deletions src/Buildalyzer/ProjectAnalyzer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,7 @@ private string GetCommand(
string initialArguments = string.Empty;
bool isDotNet = false; // false=MSBuild.exe, true=dotnet.exe
if (string.IsNullOrWhiteSpace(buildEnvironment.MsBuildExePath)
|| Path.GetExtension(buildEnvironment.MsBuildExePath).Equals(".dll", StringComparison.OrdinalIgnoreCase))
|| Path.GetExtension(buildEnvironment.MsBuildExePath).IsMatch(".dll"))
{
// in case of no MSBuild path or a path to the MSBuild dll, run dotnet
fileName = buildEnvironment.DotnetExePath;
Expand Down Expand Up @@ -256,7 +256,7 @@ private string GetCommand(
// Setting the TargetFramework MSBuild property tells MSBuild which target framework to use for the outer build
effectiveGlobalProperties[MsBuildProperties.TargetFramework] = targetFramework;
}
if (Path.GetExtension(ProjectFile.Path).Equals(".fsproj", StringComparison.OrdinalIgnoreCase)
if (Path.GetExtension(ProjectFile.Path).IsMatch(".fsproj")
&& effectiveGlobalProperties.ContainsKey(MsBuildProperties.SkipCompilerExecution))
{
// We can't skip the compiler for design-time builds in F# (it causes strange errors regarding file copying)
Expand Down
8 changes: 4 additions & 4 deletions src/Buildalyzer/XDocumentExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,13 @@ namespace Buildalyzer;
internal static class XDocumentExtensions
{
public static IEnumerable<XElement> GetDescendants(this XDocument document, string name) =>
document.Descendants().Where(x => string.Equals(x.Name.LocalName, name, StringComparison.OrdinalIgnoreCase));
document.Descendants().Where(x => x.Name.LocalName.IsMatch(name));

public static IEnumerable<XElement> GetDescendants(this XElement element, string name) =>
element.Descendants().Where(x => string.Equals(x.Name.LocalName, name, StringComparison.OrdinalIgnoreCase));
element.Descendants().Where(x => x.Name.LocalName.IsMatch(name));

public static string GetAttributeValue(this XElement element, string name) =>
element.Attributes().FirstOrDefault(x => string.Equals(x.Name.LocalName, name, StringComparison.OrdinalIgnoreCase))?.Value;
public static string? GetAttributeValue(this XElement element, string name) =>
element.Attributes().FirstOrDefault(x => x.Name.LocalName.IsMatch(name))?.Value;

// Adds a child element with the same namespace as the parent
public static void AddChildElement(this XElement element, string name, string value) =>
Expand Down

0 comments on commit 8f1096b

Please sign in to comment.