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

Reduce issues #264

Merged
merged 6 commits into from
Apr 14, 2024
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
10 changes: 4 additions & 6 deletions src/Buildalyzer.Workspaces/AnalyzerManagerExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ internal static AdhocWorkspace CreateWorkspace(this IAnalyzerManager manager)
{
ILogger logger = manager.LoggerFactory?.CreateLogger<AdhocWorkspace>();
AdhocWorkspace workspace = new AdhocWorkspace();
workspace.WorkspaceChanged += (sender, args) => logger?.LogDebug($"Workspace changed: {args.Kind.ToString()}{System.Environment.NewLine}");
workspace.WorkspaceFailed += (sender, args) => logger?.LogError($"Workspace failed: {args.Diagnostic}{System.Environment.NewLine}");
workspace.WorkspaceChanged += (sender, args) => logger?.LogDebug("Workspace changed: {Kind}{NewLine}", args.Kind, System.Environment.NewLine);
workspace.WorkspaceFailed += (sender, args) => logger?.LogError("Workspace failed: {Diagnostic}{NewLine}", args.Diagnostic, System.Environment.NewLine);
return workspace;
}

Expand All @@ -43,10 +43,8 @@ public static AdhocWorkspace GetWorkspace(this IAnalyzerManager manager)
workspace.AddSolution(solutionInfo);

// Sort the projects so the order that they're added to the workspace in the same order as the solution file
List<ProjectInSolution> projectsInOrder = manager.SolutionFile.ProjectsInOrder.ToList();
results = results
.OrderBy(p => projectsInOrder.FindIndex(g => g.AbsolutePath == p.ProjectFilePath))
.ToList();
List<ProjectInSolution> projectsInOrder = [.. manager.SolutionFile.ProjectsInOrder];
results = [.. results.OrderBy(p => projectsInOrder.FindIndex(g => g.AbsolutePath == p.ProjectFilePath))];
}

// Add each result to the new workspace (sorted in solution order above, if we have a solution)
Expand Down
15 changes: 7 additions & 8 deletions src/Buildalyzer.Workspaces/AnalyzerResultExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ public static Project AddToWorkspace(this IAnalyzerResult analyzerResult, Worksp
{
ProjectReference projectReference = projectReferenceStack.Pop();
Project nestedProject = workspace.CurrentSolution.GetProject(projectReference.ProjectId);
if (nestedProject is object && visitedProjectIds.Add(nestedProject.Id))
if (nestedProject is not null && visitedProjectIds.Add(nestedProject.Id))
{
foreach (ProjectReference nestedProjectReference in nestedProject.ProjectReferences)
{
Expand Down Expand Up @@ -257,20 +257,19 @@ private static CompilationOptions CreateCompilationOptions(IAnalyzerResult analy
private static IEnumerable<ProjectReference> GetExistingProjectReferences(IAnalyzerResult analyzerResult, Workspace workspace) =>
analyzerResult.ProjectReferences
.Select(x => workspace.CurrentSolution.Projects.FirstOrDefault(y => y.FilePath.Equals(x, StringComparison.OrdinalIgnoreCase)))

.Where(x => x != null)
.Select(x => new ProjectReference(x.Id))
?? Array.Empty<ProjectReference>();
?? [];

private static IEnumerable<IProjectAnalyzer> GetReferencedAnalyzerProjects(IAnalyzerResult analyzerResult) =>
analyzerResult.ProjectReferences
.Select(x => analyzerResult.Manager.Projects.TryGetValue(x, out IProjectAnalyzer a) ? a : analyzerResult.Manager.GetProject(x))
.Where(x => x != null)
?? Array.Empty<ProjectAnalyzer>();
?? [];

private static IEnumerable<DocumentInfo> GetDocuments(IAnalyzerResult analyzerResult, ProjectId projectId)
{
string[] sourceFiles = analyzerResult.SourceFiles ?? Array.Empty<string>();
string[] sourceFiles = analyzerResult.SourceFiles ?? [];
return GetDocuments(sourceFiles, projectId);
}

Expand All @@ -287,15 +286,15 @@ private static IEnumerable<DocumentInfo> GetDocuments(IEnumerable<string> files,
private static IEnumerable<DocumentInfo> GetAdditionalDocuments(IAnalyzerResult analyzerResult, ProjectId projectId)
{
string projectDirectory = Path.GetDirectoryName(analyzerResult.ProjectFilePath);
string[] additionalFiles = analyzerResult.AdditionalFiles ?? Array.Empty<string>();
string[] additionalFiles = analyzerResult.AdditionalFiles ?? [];
return GetDocuments(additionalFiles.Select(x => Path.Combine(projectDirectory!, x)), projectId);
}

private static IEnumerable<MetadataReference> GetMetadataReferences(IAnalyzerResult analyzerResult) =>
analyzerResult
.References?.Where(File.Exists)
.Select(x => MetadataReference.CreateFromFile(x))
?? (IEnumerable<MetadataReference>)Array.Empty<MetadataReference>();
?? [];

private static IEnumerable<AnalyzerReference> GetAnalyzerReferences(IAnalyzerResult analyzerResult, Workspace workspace)
{
Expand All @@ -304,7 +303,7 @@ private static IEnumerable<AnalyzerReference> GetAnalyzerReferences(IAnalyzerRes
string projectDirectory = Path.GetDirectoryName(analyzerResult.ProjectFilePath);
return analyzerResult.AnalyzerReferences?.Where(x => File.Exists(Path.GetFullPath(x, projectDirectory!)))
.Select(x => new AnalyzerFileReference(Path.GetFullPath(x, projectDirectory!), loader))
?? (IEnumerable<AnalyzerReference>)Array.Empty<AnalyzerReference>();
?? [];
}

private static bool TryGetSupportedLanguageName(string projectPath, out string languageName)
Expand Down
30 changes: 11 additions & 19 deletions src/Buildalyzer/AnalyzerManager.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,6 @@
extern alias StructuredLogger;

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Buildalyzer.Logging;
using Microsoft.Build.Construction;
using Microsoft.Extensions.Logging;
Expand All @@ -14,11 +10,11 @@

public class AnalyzerManager : IAnalyzerManager
{
internal static readonly SolutionProjectType[] SupportedProjectTypes = new SolutionProjectType[]
{
internal static readonly SolutionProjectType[] SupportedProjectTypes =
[
SolutionProjectType.KnownToBeMSBuildFormat,
SolutionProjectType.WebProject
};
];

private readonly ConcurrentDictionary<string, IProjectAnalyzer> _projects = new ConcurrentDictionary<string, IProjectAnalyzer>();

Expand All @@ -43,14 +39,14 @@

public SolutionFile SolutionFile { get; }

public AnalyzerManager(AnalyzerManagerOptions options = null)

Check warning on line 42 in src/Buildalyzer/AnalyzerManager.cs

View workflow job for this annotation

GitHub Actions / Build (windows-latest)

Cannot convert null literal to non-nullable reference type.

Check warning on line 42 in src/Buildalyzer/AnalyzerManager.cs

View workflow job for this annotation

GitHub Actions / Build (ubuntu-latest)

Cannot convert null literal to non-nullable reference type.

Check warning on line 42 in src/Buildalyzer/AnalyzerManager.cs

View workflow job for this annotation

GitHub Actions / Build (macos-latest)

Cannot convert null literal to non-nullable reference type.
: this(null, options)
{
}

public AnalyzerManager(string solutionFilePath, AnalyzerManagerOptions options = null)

Check warning on line 47 in src/Buildalyzer/AnalyzerManager.cs

View workflow job for this annotation

GitHub Actions / Build (windows-latest)

Cannot convert null literal to non-nullable reference type.

Check warning on line 47 in src/Buildalyzer/AnalyzerManager.cs

View workflow job for this annotation

GitHub Actions / Build (ubuntu-latest)

Cannot convert null literal to non-nullable reference type.
{
options = options ?? new AnalyzerManagerOptions();
options ??= new AnalyzerManagerOptions();
LoggerFactory = options.LoggerFactory;

if (!string.IsNullOrEmpty(solutionFilePath))
Expand Down Expand Up @@ -90,7 +86,7 @@
public IProjectAnalyzer GetProject(string projectFilePath) => GetProject(projectFilePath, null);

/// <inheritdoc/>
public IAnalyzerResults Analyze(string binLogPath, IEnumerable<Microsoft.Build.Framework.ILogger> buildLoggers = null)

Check warning on line 89 in src/Buildalyzer/AnalyzerManager.cs

View workflow job for this annotation

GitHub Actions / Build (windows-latest)

Cannot convert null literal to non-nullable reference type.

Check warning on line 89 in src/Buildalyzer/AnalyzerManager.cs

View workflow job for this annotation

GitHub Actions / Build (ubuntu-latest)

Cannot convert null literal to non-nullable reference type.
{
binLogPath = NormalizePath(binLogPath);
if (!File.Exists(binLogPath))
Expand All @@ -99,22 +95,18 @@
}

BinLogReader reader = new BinLogReader();
using (EventProcessor eventProcessor = new EventProcessor(this, null, buildLoggers, reader, true))

using EventProcessor eventProcessor = new EventProcessor(this, null, buildLoggers, reader, true);
reader.Replay(binLogPath);
return new AnalyzerResults
{
reader.Replay(binLogPath);
return new AnalyzerResults
{
{ eventProcessor.Results, eventProcessor.OverallSuccess }
};
}
{ eventProcessor.Results, eventProcessor.OverallSuccess }
};
}

private IProjectAnalyzer GetProject(string projectFilePath, ProjectInSolution projectInSolution)
{
if (projectFilePath == null)
{
throw new ArgumentNullException(nameof(projectFilePath));
}
Guard.NotNull(projectFilePath);

projectFilePath = NormalizePath(projectFilePath);
if (!File.Exists(projectFilePath))
Expand Down
2 changes: 1 addition & 1 deletion src/Buildalyzer/AnalyzerManagerOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public TextWriter LogWriter
return;
}

LoggerFactory = LoggerFactory ?? new LoggerFactory();
LoggerFactory ??= new LoggerFactory();
LoggerFactory.AddProvider(new TextWriterLoggerProvider(value));
}
}
Expand Down
8 changes: 4 additions & 4 deletions src/Buildalyzer/AnalyzerResult.cs
Original file line number Diff line number Diff line change
Expand Up @@ -61,8 +61,8 @@
public string TargetFramework =>
ProjectFile.GetTargetFrameworks(
null, // Don't want all target frameworks since the result is just for one
new[] { GetProperty(ProjectFileNames.TargetFramework) },
new[] { (GetProperty(ProjectFileNames.TargetFrameworkIdentifier), GetProperty(ProjectFileNames.TargetFrameworkVersion)) })
[GetProperty(ProjectFileNames.TargetFramework)],
[(GetProperty(ProjectFileNames.TargetFrameworkIdentifier), GetProperty(ProjectFileNames.TargetFrameworkVersion))])
.FirstOrDefault();

public string[] SourceFiles =>
Expand All @@ -84,13 +84,13 @@
? items.Distinct(new ProjectItemItemSpecEqualityComparer())
.Select(x => AnalyzerManager.NormalizePath(
Path.Combine(Path.GetDirectoryName(ProjectFilePath), x.ItemSpec)))
: Array.Empty<string>();
: [];

/// <inheritdoc/>
public IReadOnlyDictionary<string, IReadOnlyDictionary<string, string>> PackageReferences =>
Items.TryGetValue("PackageReference", out IProjectItem[] items)
? items.Distinct(new ProjectItemItemSpecEqualityComparer()).ToDictionary(x => x.ItemSpec, x => x.Metadata)
: new Dictionary<string, IReadOnlyDictionary<string, string>>();
: [];

internal void ProcessProject(PropertiesAndItems propertiesAndItems)
{
Expand Down Expand Up @@ -129,7 +129,7 @@

private class ProjectItemItemSpecEqualityComparer : IEqualityComparer<IProjectItem>
{
public bool Equals(IProjectItem x, IProjectItem y) => x.ItemSpec.Equals(y.ItemSpec, StringComparison.OrdinalIgnoreCase);

Check warning on line 132 in src/Buildalyzer/AnalyzerResult.cs

View workflow job for this annotation

GitHub Actions / Build (windows-latest)

Nullability of reference types in type of parameter 'x' of 'bool ProjectItemItemSpecEqualityComparer.Equals(IProjectItem x, IProjectItem y)' doesn't match implicitly implemented member 'bool IEqualityComparer<IProjectItem>.Equals(IProjectItem? x, IProjectItem? y)' (possibly because of nullability attributes).

Check warning on line 132 in src/Buildalyzer/AnalyzerResult.cs

View workflow job for this annotation

GitHub Actions / Build (windows-latest)

Nullability of reference types in type of parameter 'y' of 'bool ProjectItemItemSpecEqualityComparer.Equals(IProjectItem x, IProjectItem y)' doesn't match implicitly implemented member 'bool IEqualityComparer<IProjectItem>.Equals(IProjectItem? x, IProjectItem? y)' (possibly because of nullability attributes).

Check warning on line 132 in src/Buildalyzer/AnalyzerResult.cs

View workflow job for this annotation

GitHub Actions / Build (ubuntu-latest)

Nullability of reference types in type of parameter 'x' of 'bool ProjectItemItemSpecEqualityComparer.Equals(IProjectItem x, IProjectItem y)' doesn't match implicitly implemented member 'bool IEqualityComparer<IProjectItem>.Equals(IProjectItem? x, IProjectItem? y)' (possibly because of nullability attributes).

Check warning on line 132 in src/Buildalyzer/AnalyzerResult.cs

View workflow job for this annotation

GitHub Actions / Build (ubuntu-latest)

Nullability of reference types in type of parameter 'y' of 'bool ProjectItemItemSpecEqualityComparer.Equals(IProjectItem x, IProjectItem y)' doesn't match implicitly implemented member 'bool IEqualityComparer<IProjectItem>.Equals(IProjectItem? x, IProjectItem? y)' (possibly because of nullability attributes).

Check warning on line 132 in src/Buildalyzer/AnalyzerResult.cs

View workflow job for this annotation

GitHub Actions / Build (macos-latest)

Nullability of reference types in type of parameter 'x' of 'bool ProjectItemItemSpecEqualityComparer.Equals(IProjectItem x, IProjectItem y)' doesn't match implicitly implemented member 'bool IEqualityComparer<IProjectItem>.Equals(IProjectItem? x, IProjectItem? y)' (possibly because of nullability attributes).

Check warning on line 132 in src/Buildalyzer/AnalyzerResult.cs

View workflow job for this annotation

GitHub Actions / Build (macos-latest)

Nullability of reference types in type of parameter 'y' of 'bool ProjectItemItemSpecEqualityComparer.Equals(IProjectItem x, IProjectItem y)' doesn't match implicitly implemented member 'bool IEqualityComparer<IProjectItem>.Equals(IProjectItem? x, IProjectItem? y)' (possibly because of nullability attributes).

public int GetHashCode(IProjectItem obj) => obj.ItemSpec.ToLowerInvariant().GetHashCode();
}
Expand Down
15 changes: 6 additions & 9 deletions src/Buildalyzer/Compiler/Compiler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,16 +35,13 @@ public static CompilerCommand Parse(DirectoryInfo? baseDir, string commandLine,
Arguments = args.ToImmutableArray(),
};

CompilerCommand Parse(string? baseDir, string? root, string[] args, CompilerLanguage language)
static CompilerCommand Parse(string? baseDir, string? root, string[] args, CompilerLanguage language) => language switch
{
return language switch
{
CompilerLanguage.CSharp => CSharpParser.Parse(args, baseDir, root),
CompilerLanguage.VisualBasic => VisualBasicParser.Parse(args, baseDir, root),
CompilerLanguage.FSharp => FSharpParser.Parse(args),
_ => throw new NotSupportedException($"The {language} language is not supported."),
};
}
CompilerLanguage.CSharp => CSharpParser.Parse(args, baseDir, root),
CompilerLanguage.VisualBasic => VisualBasicParser.Parse(args, baseDir, root),
CompilerLanguage.FSharp => FSharpParser.Parse(args),
_ => throw new NotSupportedException($"The {language} language is not supported."),
};
}
}

Expand Down
4 changes: 2 additions & 2 deletions src/Buildalyzer/Construction/ProjectFile.cs
Original file line number Diff line number Diff line change
Expand Up @@ -49,11 +49,11 @@ internal ProjectFile(string path)

/// <inheritdoc />
public string[] TargetFrameworks => _targetFrameworks
?? (_targetFrameworks = GetTargetFrameworks(
??= GetTargetFrameworks(
_projectElement.GetDescendants(ProjectFileNames.TargetFrameworks).Select(x => x.Value),
_projectElement.GetDescendants(ProjectFileNames.TargetFramework).Select(x => x.Value),
_projectElement.GetDescendants(ProjectFileNames.TargetFrameworkVersion)
.Select(x => (x.Parent.GetDescendants(ProjectFileNames.TargetFrameworkIdentifier).FirstOrDefault()?.Value ?? ".NETFramework", x.Value))));
.Select(x => (x.Parent.GetDescendants(ProjectFileNames.TargetFrameworkIdentifier).FirstOrDefault()?.Value ?? ".NETFramework", x.Value)));

/// <inheritdoc />
public bool UsesSdk =>
Expand Down
19 changes: 8 additions & 11 deletions src/Buildalyzer/Environment/BuildEnvironment.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.NetworkInformation;
using System.IO;

namespace Buildalyzer.Environment;

Expand Down Expand Up @@ -44,7 +41,7 @@ public sealed class BuildEnvironment

public string DotnetExePath { get; }

public string WorkingDirectory { get; }
public string? WorkingDirectory { get; }

/// <summary>
/// Indicates if the <c>-noAutoResponse</c> argument should be set (the default is <c>true</c>).
Expand All @@ -68,14 +65,14 @@ public BuildEnvironment(
string msBuildExePath,
string dotnetExePath,
IEnumerable<string> arguments,
IDictionary<string, string> additionalGlobalProperties = null,
IDictionary<string, string> additionalEnvironmentVariables = null,
string workingDirectory = null)
IDictionary<string, string>? additionalGlobalProperties = null,
IDictionary<string, string>? additionalEnvironmentVariables = null,
string? workingDirectory = null)
{
DesignTime = designTime;
Restore = restore;
TargetsToBuild = targetsToBuild ?? throw new ArgumentNullException(nameof(targetsToBuild));
Arguments = arguments ?? throw new ArgumentNullException(nameof(arguments));
TargetsToBuild = Guard.NotNull(targetsToBuild);
Arguments = Guard.NotNull(arguments);
WorkingDirectory = workingDirectory;

// Check if we've already specified a path to MSBuild
Expand All @@ -88,7 +85,7 @@ public BuildEnvironment(
}

// The dotnet path defaults to "dotnet" - if it's null then the user changed it and we should warn them
DotnetExePath = dotnetExePath ?? throw new ArgumentNullException(nameof(dotnetExePath));
DotnetExePath = Guard.NotNull(dotnetExePath);

// Set global properties
_globalProperties = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
Expand Down
4 changes: 2 additions & 2 deletions src/Buildalyzer/Environment/EnvironmentFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ public BuildEnvironment GetBuildEnvironment(EnvironmentOptions options) =>

public BuildEnvironment GetBuildEnvironment(string targetFramework, EnvironmentOptions options)
{
options = options ?? new EnvironmentOptions();
options ??= new EnvironmentOptions();
BuildEnvironment buildEnvironment;

// Use the .NET Framework if that's the preference
Expand Down Expand Up @@ -195,7 +195,7 @@ private bool GetFrameworkMsBuildExePath(out string msBuildExePath)
}

private bool OnlyTargetsFramework(string targetFramework)
=> targetFramework == null
=> targetFramework == null
? _projectFile.TargetFrameworks.TrueForAll(IsFrameworkTargetFramework)
: IsFrameworkTargetFramework(targetFramework);

Expand Down
2 changes: 1 addition & 1 deletion src/Buildalyzer/Guard.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,5 +38,5 @@ public static T NotNull<T>([ValidatedNotNull] T? parameter, [CallerArgumentExpre
/// </remarks>
[Conditional("Analysis")]
[AttributeUsage(AttributeTargets.Parameter)]
private sealed class ValidatedNotNullAttribute : Attribute { }
private sealed class ValidatedNotNullAttribute : Attribute;
}
Loading
Loading