Skip to content

Commit 140a2e0

Browse files
authored
Reduce issues (Buildalyzer#264)
1 parent ffe7787 commit 140a2e0

File tree

14 files changed

+83
-133
lines changed

14 files changed

+83
-133
lines changed

src/Buildalyzer.Workspaces/AnalyzerManagerExtensions.cs

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,8 @@ internal static AdhocWorkspace CreateWorkspace(this IAnalyzerManager manager)
1616
{
1717
ILogger logger = manager.LoggerFactory?.CreateLogger<AdhocWorkspace>();
1818
AdhocWorkspace workspace = new AdhocWorkspace();
19-
workspace.WorkspaceChanged += (sender, args) => logger?.LogDebug($"Workspace changed: {args.Kind.ToString()}{System.Environment.NewLine}");
20-
workspace.WorkspaceFailed += (sender, args) => logger?.LogError($"Workspace failed: {args.Diagnostic}{System.Environment.NewLine}");
19+
workspace.WorkspaceChanged += (sender, args) => logger?.LogDebug("Workspace changed: {Kind}{NewLine}", args.Kind, System.Environment.NewLine);
20+
workspace.WorkspaceFailed += (sender, args) => logger?.LogError("Workspace failed: {Diagnostic}{NewLine}", args.Diagnostic, System.Environment.NewLine);
2121
return workspace;
2222
}
2323

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

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

5250
// Add each result to the new workspace (sorted in solution order above, if we have a solution)

src/Buildalyzer.Workspaces/AnalyzerResultExtensions.cs

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,7 @@ public static Project AddToWorkspace(this IAnalyzerResult analyzerResult, Worksp
111111
{
112112
ProjectReference projectReference = projectReferenceStack.Pop();
113113
Project nestedProject = workspace.CurrentSolution.GetProject(projectReference.ProjectId);
114-
if (nestedProject is object && visitedProjectIds.Add(nestedProject.Id))
114+
if (nestedProject is not null && visitedProjectIds.Add(nestedProject.Id))
115115
{
116116
foreach (ProjectReference nestedProjectReference in nestedProject.ProjectReferences)
117117
{
@@ -257,20 +257,19 @@ private static CompilationOptions CreateCompilationOptions(IAnalyzerResult analy
257257
private static IEnumerable<ProjectReference> GetExistingProjectReferences(IAnalyzerResult analyzerResult, Workspace workspace) =>
258258
analyzerResult.ProjectReferences
259259
.Select(x => workspace.CurrentSolution.Projects.FirstOrDefault(y => y.FilePath.Equals(x, StringComparison.OrdinalIgnoreCase)))
260-
261260
.Where(x => x != null)
262261
.Select(x => new ProjectReference(x.Id))
263-
?? Array.Empty<ProjectReference>();
262+
?? [];
264263

265264
private static IEnumerable<IProjectAnalyzer> GetReferencedAnalyzerProjects(IAnalyzerResult analyzerResult) =>
266265
analyzerResult.ProjectReferences
267266
.Select(x => analyzerResult.Manager.Projects.TryGetValue(x, out IProjectAnalyzer a) ? a : analyzerResult.Manager.GetProject(x))
268267
.Where(x => x != null)
269-
?? Array.Empty<ProjectAnalyzer>();
268+
?? [];
270269

271270
private static IEnumerable<DocumentInfo> GetDocuments(IAnalyzerResult analyzerResult, ProjectId projectId)
272271
{
273-
string[] sourceFiles = analyzerResult.SourceFiles ?? Array.Empty<string>();
272+
string[] sourceFiles = analyzerResult.SourceFiles ?? [];
274273
return GetDocuments(sourceFiles, projectId);
275274
}
276275

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

294293
private static IEnumerable<MetadataReference> GetMetadataReferences(IAnalyzerResult analyzerResult) =>
295294
analyzerResult
296295
.References?.Where(File.Exists)
297296
.Select(x => MetadataReference.CreateFromFile(x))
298-
?? (IEnumerable<MetadataReference>)Array.Empty<MetadataReference>();
297+
?? [];
299298

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

310309
private static bool TryGetSupportedLanguageName(string projectPath, out string languageName)

src/Buildalyzer/AnalyzerManager.cs

Lines changed: 11 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,6 @@
11
extern alias StructuredLogger;
2-
3-
using System;
42
using System.Collections.Concurrent;
5-
using System.Collections.Generic;
63
using System.IO;
7-
using System.Linq;
84
using Buildalyzer.Logging;
95
using Microsoft.Build.Construction;
106
using Microsoft.Extensions.Logging;
@@ -14,11 +10,11 @@ namespace Buildalyzer;
1410

1511
public class AnalyzerManager : IAnalyzerManager
1612
{
17-
internal static readonly SolutionProjectType[] SupportedProjectTypes = new SolutionProjectType[]
18-
{
13+
internal static readonly SolutionProjectType[] SupportedProjectTypes =
14+
[
1915
SolutionProjectType.KnownToBeMSBuildFormat,
2016
SolutionProjectType.WebProject
21-
};
17+
];
2218

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

@@ -50,7 +46,7 @@ public AnalyzerManager(AnalyzerManagerOptions options = null)
5046

5147
public AnalyzerManager(string solutionFilePath, AnalyzerManagerOptions options = null)
5248
{
53-
options = options ?? new AnalyzerManagerOptions();
49+
options ??= new AnalyzerManagerOptions();
5450
LoggerFactory = options.LoggerFactory;
5551

5652
if (!string.IsNullOrEmpty(solutionFilePath))
@@ -99,22 +95,18 @@ public IAnalyzerResults Analyze(string binLogPath, IEnumerable<Microsoft.Build.F
9995
}
10096

10197
BinLogReader reader = new BinLogReader();
102-
using (EventProcessor eventProcessor = new EventProcessor(this, null, buildLoggers, reader, true))
98+
99+
using EventProcessor eventProcessor = new EventProcessor(this, null, buildLoggers, reader, true);
100+
reader.Replay(binLogPath);
101+
return new AnalyzerResults
103102
{
104-
reader.Replay(binLogPath);
105-
return new AnalyzerResults
106-
{
107-
{ eventProcessor.Results, eventProcessor.OverallSuccess }
108-
};
109-
}
103+
{ eventProcessor.Results, eventProcessor.OverallSuccess }
104+
};
110105
}
111106

112107
private IProjectAnalyzer GetProject(string projectFilePath, ProjectInSolution projectInSolution)
113108
{
114-
if (projectFilePath == null)
115-
{
116-
throw new ArgumentNullException(nameof(projectFilePath));
117-
}
109+
Guard.NotNull(projectFilePath);
118110

119111
projectFilePath = NormalizePath(projectFilePath);
120112
if (!File.Exists(projectFilePath))

src/Buildalyzer/AnalyzerManagerOptions.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ public TextWriter LogWriter
2626
return;
2727
}
2828

29-
LoggerFactory = LoggerFactory ?? new LoggerFactory();
29+
LoggerFactory ??= new LoggerFactory();
3030
LoggerFactory.AddProvider(new TextWriterLoggerProvider(value));
3131
}
3232
}

src/Buildalyzer/AnalyzerResult.cs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -61,8 +61,8 @@ public string GetProperty(string name) =>
6161
public string TargetFramework =>
6262
ProjectFile.GetTargetFrameworks(
6363
null, // Don't want all target frameworks since the result is just for one
64-
new[] { GetProperty(ProjectFileNames.TargetFramework) },
65-
new[] { (GetProperty(ProjectFileNames.TargetFrameworkIdentifier), GetProperty(ProjectFileNames.TargetFrameworkVersion)) })
64+
[GetProperty(ProjectFileNames.TargetFramework)],
65+
[(GetProperty(ProjectFileNames.TargetFrameworkIdentifier), GetProperty(ProjectFileNames.TargetFrameworkVersion))])
6666
.FirstOrDefault();
6767

6868
public string[] SourceFiles =>
@@ -84,13 +84,13 @@ public string GetProperty(string name) =>
8484
? items.Distinct(new ProjectItemItemSpecEqualityComparer())
8585
.Select(x => AnalyzerManager.NormalizePath(
8686
Path.Combine(Path.GetDirectoryName(ProjectFilePath), x.ItemSpec)))
87-
: Array.Empty<string>();
87+
: [];
8888

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

9595
internal void ProcessProject(PropertiesAndItems propertiesAndItems)
9696
{

src/Buildalyzer/Compiler/Compiler.cs

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -35,16 +35,13 @@ public static CompilerCommand Parse(DirectoryInfo? baseDir, string commandLine,
3535
Arguments = args.ToImmutableArray(),
3636
};
3737

38-
CompilerCommand Parse(string? baseDir, string? root, string[] args, CompilerLanguage language)
38+
static CompilerCommand Parse(string? baseDir, string? root, string[] args, CompilerLanguage language) => language switch
3939
{
40-
return language switch
41-
{
42-
CompilerLanguage.CSharp => CSharpParser.Parse(args, baseDir, root),
43-
CompilerLanguage.VisualBasic => VisualBasicParser.Parse(args, baseDir, root),
44-
CompilerLanguage.FSharp => FSharpParser.Parse(args),
45-
_ => throw new NotSupportedException($"The {language} language is not supported."),
46-
};
47-
}
40+
CompilerLanguage.CSharp => CSharpParser.Parse(args, baseDir, root),
41+
CompilerLanguage.VisualBasic => VisualBasicParser.Parse(args, baseDir, root),
42+
CompilerLanguage.FSharp => FSharpParser.Parse(args),
43+
_ => throw new NotSupportedException($"The {language} language is not supported."),
44+
};
4845
}
4946
}
5047

src/Buildalyzer/Construction/ProjectFile.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -49,11 +49,11 @@ internal ProjectFile(string path)
4949

5050
/// <inheritdoc />
5151
public string[] TargetFrameworks => _targetFrameworks
52-
?? (_targetFrameworks = GetTargetFrameworks(
52+
??= GetTargetFrameworks(
5353
_projectElement.GetDescendants(ProjectFileNames.TargetFrameworks).Select(x => x.Value),
5454
_projectElement.GetDescendants(ProjectFileNames.TargetFramework).Select(x => x.Value),
5555
_projectElement.GetDescendants(ProjectFileNames.TargetFrameworkVersion)
56-
.Select(x => (x.Parent.GetDescendants(ProjectFileNames.TargetFrameworkIdentifier).FirstOrDefault()?.Value ?? ".NETFramework", x.Value))));
56+
.Select(x => (x.Parent.GetDescendants(ProjectFileNames.TargetFrameworkIdentifier).FirstOrDefault()?.Value ?? ".NETFramework", x.Value)));
5757

5858
/// <inheritdoc />
5959
public bool UsesSdk =>

src/Buildalyzer/Environment/BuildEnvironment.cs

Lines changed: 8 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,4 @@
1-
using System;
2-
using System.Collections.Generic;
3-
using System.IO;
4-
using System.Net.NetworkInformation;
1+
using System.IO;
52

63
namespace Buildalyzer.Environment;
74

@@ -44,7 +41,7 @@ public sealed class BuildEnvironment
4441

4542
public string DotnetExePath { get; }
4643

47-
public string WorkingDirectory { get; }
44+
public string? WorkingDirectory { get; }
4845

4946
/// <summary>
5047
/// Indicates if the <c>-noAutoResponse</c> argument should be set (the default is <c>true</c>).
@@ -68,14 +65,14 @@ public BuildEnvironment(
6865
string msBuildExePath,
6966
string dotnetExePath,
7067
IEnumerable<string> arguments,
71-
IDictionary<string, string> additionalGlobalProperties = null,
72-
IDictionary<string, string> additionalEnvironmentVariables = null,
73-
string workingDirectory = null)
68+
IDictionary<string, string>? additionalGlobalProperties = null,
69+
IDictionary<string, string>? additionalEnvironmentVariables = null,
70+
string? workingDirectory = null)
7471
{
7572
DesignTime = designTime;
7673
Restore = restore;
77-
TargetsToBuild = targetsToBuild ?? throw new ArgumentNullException(nameof(targetsToBuild));
78-
Arguments = arguments ?? throw new ArgumentNullException(nameof(arguments));
74+
TargetsToBuild = Guard.NotNull(targetsToBuild);
75+
Arguments = Guard.NotNull(arguments);
7976
WorkingDirectory = workingDirectory;
8077

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

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

9390
// Set global properties
9491
_globalProperties = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)

src/Buildalyzer/Environment/EnvironmentFactory.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ public BuildEnvironment GetBuildEnvironment(EnvironmentOptions options) =>
3434

3535
public BuildEnvironment GetBuildEnvironment(string targetFramework, EnvironmentOptions options)
3636
{
37-
options = options ?? new EnvironmentOptions();
37+
options ??= new EnvironmentOptions();
3838
BuildEnvironment buildEnvironment;
3939

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

197197
private bool OnlyTargetsFramework(string targetFramework)
198-
=> targetFramework == null
198+
=> targetFramework == null
199199
? _projectFile.TargetFrameworks.TrueForAll(IsFrameworkTargetFramework)
200200
: IsFrameworkTargetFramework(targetFramework);
201201

src/Buildalyzer/Guard.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,5 +38,5 @@ public static T NotNull<T>([ValidatedNotNull] T? parameter, [CallerArgumentExpre
3838
/// </remarks>
3939
[Conditional("Analysis")]
4040
[AttributeUsage(AttributeTargets.Parameter)]
41-
private sealed class ValidatedNotNullAttribute : Attribute { }
41+
private sealed class ValidatedNotNullAttribute : Attribute;
4242
}

0 commit comments

Comments
 (0)