Skip to content

Commit 00c7824

Browse files
Merge pull request #1533 from PowerShell/andschwa/dotnet-analysis
Enable and fix many .NET Code Analysis warnings
2 parents 75bc4fb + 707cad6 commit 00c7824

File tree

53 files changed

+244
-249
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

53 files changed

+244
-249
lines changed

.editorconfig

+27
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,33 @@ trim_trailing_whitespace = true
1313
csharp_space_before_open_square_brackets = true
1414
csharp_space_after_keywords_in_control_flow_statements = true
1515

16+
# CS0168: The variable 'var' is declared but never used
17+
dotnet_diagnostic.CS0168.severity = error
18+
# CS0169: The private field 'class member' is never used
19+
dotnet_diagnostic.CS0169.severity = error
20+
# CS0219: The variable 'variable' is assigned but its value is never used
21+
dotnet_diagnostic.CS0219.severity = error
22+
# CS0414: The private field 'field' is assigned but its value is never used
23+
dotnet_diagnostic.CS0414.severity = error
24+
# CA1068: CancellationToken parameters must come last
25+
dotnet_diagnostic.CA1068.severity = error
26+
# CA1822: Mark members as static
27+
dotnet_diagnostic.CA1822.severity = error
28+
# CA1823: Avoid unused private fields
29+
dotnet_diagnostic.CA1823.severity = error
30+
# CA2007: Do not directly await a Task
31+
dotnet_diagnostic.CA2007.severity = error
32+
# CA2016: Forward the CancellationToken parameter to methods that take one
33+
dotnet_diagnostic.CA2016.severity = error
34+
# All maintainability issues (dead code etc.)
35+
# See: https://docs.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/maintainability-warnings
36+
dotnet_analyzer_diagnostic.category-Maintainability.severity = error
37+
# VSTHRD002: Synchronously waiting on tasks or awaiters may cause deadlocks
38+
# TODO: Fix all of these issues and explicitly ignore the intentional ones.
39+
dotnet_diagnostic.VSTHRD002.severity = silent
40+
# VSTHRD200: Use "Async" suffix for awaitable methods
41+
dotnet_diagnostic.VSTHRD200.severity = silent
42+
1643
[*.{json}]
1744
indent_size = 2
1845
trim_trailing_whitespace = true

PowerShellEditorServices.Common.props

+3
Original file line numberDiff line numberDiff line change
@@ -11,5 +11,8 @@
1111
<RepositoryType>git</RepositoryType>
1212
<RepositoryUrl>https://github.com/PowerShell/PowerShellEditorServices</RepositoryUrl>
1313
<DebugType>portable</DebugType>
14+
<!-- See: https://docs.microsoft.com/en-us/dotnet/fundamentals/code-analysis/overview -->
15+
<EnableNETAnalyzers>true</EnableNETAnalyzers>
16+
<!-- TODO: Enable `EnforceCodeStyleInBuild` -->
1417
</PropertyGroup>
1518
</Project>

src/PowerShellEditorServices.Hosting/EditorServicesLoader.cs

+3-3
Original file line numberDiff line numberDiff line change
@@ -226,7 +226,7 @@ public void Dispose()
226226
// This is not high priority, since the PSES process shouldn't be reused
227227
}
228228

229-
private void LoadEditorServices()
229+
private static void LoadEditorServices()
230230
{
231231
// This must be in its own method, since the actual load happens when the calling method is called
232232
// The call within this method is therefore a total no-op
@@ -317,7 +317,7 @@ private void LogHostInformation()
317317
LogOperatingSystemDetails();
318318
}
319319

320-
private string GetPSOutputEncoding()
320+
private static string GetPSOutputEncoding()
321321
{
322322
using (var pwsh = SMA.PowerShell.Create())
323323
{
@@ -346,7 +346,7 @@ private void LogOperatingSystemDetails()
346346
");
347347
}
348348

349-
private string GetOSArchitecture()
349+
private static string GetOSArchitecture()
350350
{
351351
#if CoreCLR
352352
if (Environment.OSVersion.Platform != PlatformID.Win32NT)

src/PowerShellEditorServices.Hosting/PowerShellEditorServices.Hosting.csproj

-4
Original file line numberDiff line numberDiff line change
@@ -31,10 +31,6 @@
3131

3232
<ItemGroup>
3333
<ProjectReference Include="..\PowerShellEditorServices\PowerShellEditorServices.csproj" PrivateAssets="all" />
34-
<PackageReference Include="Microsoft.CodeAnalysis.FxCopAnalyzers" Version="3.3.2">
35-
<PrivateAssets>all</PrivateAssets>
36-
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
37-
</PackageReference>
3834
</ItemGroup>
3935

4036
<ItemGroup Condition="'$(TargetFramework)'=='net461'">

src/PowerShellEditorServices.VSCode/CustomViews/CustomViewBase.cs

+9-18
Original file line numberDiff line numberDiff line change
@@ -28,40 +28,31 @@ public CustomViewBase(
2828
this.languageServer = languageServer;
2929
}
3030

31-
internal async Task CreateAsync()
32-
{
33-
await languageServer.SendRequestAsync(
31+
internal Task CreateAsync() =>
32+
languageServer.SendRequestAsync(
3433
NewCustomViewRequest.Method,
3534
new NewCustomViewRequest
3635
{
3736
Id = this.Id,
3837
Title = this.Title,
3938
ViewType = this.ViewType,
40-
}
41-
);
42-
}
39+
});
4340

44-
public async Task Show(ViewColumn viewColumn)
45-
{
46-
await languageServer.SendRequestAsync(
41+
public Task Show(ViewColumn viewColumn) =>
42+
languageServer.SendRequestAsync(
4743
ShowCustomViewRequest.Method,
4844
new ShowCustomViewRequest
4945
{
5046
Id = this.Id,
5147
ViewColumn = viewColumn
52-
}
53-
);
54-
}
48+
});
5549

56-
public async Task Close()
57-
{
58-
await languageServer.SendRequestAsync(
50+
public Task Close() =>
51+
languageServer.SendRequestAsync(
5952
CloseCustomViewRequest.Method,
6053
new CloseCustomViewRequest
6154
{
6255
Id = this.Id,
63-
}
64-
);
65-
}
56+
});
6657
}
6758
}

src/PowerShellEditorServices.VSCode/CustomViews/HtmlContentView.cs

+13-22
Original file line numberDiff line numberDiff line change
@@ -21,51 +21,42 @@ public HtmlContentView(
2121
{
2222
}
2323

24-
public async Task SetContentAsync(string htmlBodyContent)
25-
{
26-
await languageServer.SendRequestAsync(
24+
public Task SetContentAsync(string htmlBodyContent) =>
25+
languageServer.SendRequestAsync(
2726
SetHtmlContentViewRequest.Method,
2827
new SetHtmlContentViewRequest
2928
{
3029
Id = this.Id,
3130
HtmlContent = new HtmlContent { BodyContent = htmlBodyContent }
3231
}
3332
);
34-
}
35-
36-
public async Task SetContentAsync(HtmlContent htmlContent)
37-
{
38-
HtmlContent validatedContent =
39-
new HtmlContent()
40-
{
41-
BodyContent = htmlContent.BodyContent,
42-
JavaScriptPaths = this.GetUriPaths(htmlContent.JavaScriptPaths),
43-
StyleSheetPaths = this.GetUriPaths(htmlContent.StyleSheetPaths)
44-
};
4533

46-
await languageServer.SendRequestAsync(
34+
public Task SetContentAsync(HtmlContent htmlContent) =>
35+
languageServer.SendRequestAsync(
4736
SetHtmlContentViewRequest.Method,
4837
new SetHtmlContentViewRequest
4938
{
5039
Id = this.Id,
51-
HtmlContent = validatedContent
40+
HtmlContent = new HtmlContent()
41+
{
42+
BodyContent = htmlContent.BodyContent,
43+
JavaScriptPaths = HtmlContentView.GetUriPaths(htmlContent.JavaScriptPaths),
44+
StyleSheetPaths = HtmlContentView.GetUriPaths(htmlContent.StyleSheetPaths)
45+
}
5246
}
5347
);
54-
}
5548

56-
public async Task AppendContentAsync(string appendedHtmlBodyContent)
57-
{
58-
await languageServer.SendRequestAsync(
49+
public Task AppendContentAsync(string appendedHtmlBodyContent) =>
50+
languageServer.SendRequestAsync(
5951
AppendHtmlContentViewRequest.Method,
6052
new AppendHtmlContentViewRequest
6153
{
6254
Id = this.Id,
6355
AppendedHtmlBodyContent = appendedHtmlBodyContent
6456
}
6557
);
66-
}
6758

68-
private string[] GetUriPaths(string[] filePaths)
59+
private static string[] GetUriPaths(string[] filePaths)
6960
{
7061
return
7162
filePaths?

src/PowerShellEditorServices.VSCode/CustomViews/HtmlContentViewsFeature.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ public async Task<IHtmlContentView> CreateHtmlContentViewAsync(string viewTitle)
2121
viewTitle,
2222
languageServer);
2323

24-
await htmlView.CreateAsync();
24+
await htmlView.CreateAsync().ConfigureAwait(false);
2525
this.AddView(htmlView);
2626

2727
return htmlView;

src/PowerShellEditorServices/Extensions/Api/EditorExtensionServiceProvider.cs

+2-2
Original file line numberDiff line numberDiff line change
@@ -156,7 +156,7 @@ public object GetService(Type serviceType)
156156
/// In .NET Framework, this returns null.
157157
/// </summary>
158158
/// <returns>The assembly load context used for loading PSES, or null in .NET Framework.</returns>
159-
public object GetPsesAssemblyLoadContext()
159+
public static object GetPsesAssemblyLoadContext()
160160
{
161161
if (!VersionUtils.IsNetCore)
162162
{
@@ -172,7 +172,7 @@ public object GetPsesAssemblyLoadContext()
172172
/// </summary>
173173
/// <param name="assemblyPath">The absolute path of the assembly to load.</param>
174174
/// <returns>The loaded assembly object.</returns>
175-
public Assembly LoadAssemblyInPsesLoadContext(string assemblyPath)
175+
public static Assembly LoadAssemblyInPsesLoadContext(string assemblyPath)
176176
{
177177
if (!VersionUtils.IsNetCore)
178178
{

src/PowerShellEditorServices/Extensions/Api/EditorUIService.cs

+3-3
Original file line numberDiff line numberDiff line change
@@ -116,7 +116,7 @@ public async Task<string> PromptInputAsync(string message)
116116
new ShowInputPromptRequest
117117
{
118118
Name = message,
119-
}).Returning<ShowInputPromptResponse>(CancellationToken.None);
119+
}).Returning<ShowInputPromptResponse>(CancellationToken.None).ConfigureAwait(false);
120120

121121
if (response.PromptCancelled)
122122
{
@@ -142,7 +142,7 @@ public async Task<IReadOnlyList<string>> PromptMultipleSelectionAsync(string mes
142142
Message = message,
143143
Choices = choiceDetails,
144144
DefaultChoices = defaultChoiceIndexes?.ToArray(),
145-
}).Returning<ShowChoicePromptResponse>(CancellationToken.None);
145+
}).Returning<ShowChoicePromptResponse>(CancellationToken.None).ConfigureAwait(false);
146146

147147
if (response.PromptCancelled)
148148
{
@@ -168,7 +168,7 @@ public async Task<string> PromptSelectionAsync(string message, IReadOnlyList<Pro
168168
Message = message,
169169
Choices = choiceDetails,
170170
DefaultChoices = defaultChoiceIndex > -1 ? new[] { defaultChoiceIndex } : null,
171-
}).Returning<ShowChoicePromptResponse>(CancellationToken.None);
171+
}).Returning<ShowChoicePromptResponse>(CancellationToken.None).ConfigureAwait(false);
172172

173173
if (response.PromptCancelled)
174174
{

src/PowerShellEditorServices/Extensions/Api/WorkspaceService.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -147,7 +147,7 @@ public IReadOnlyList<IEditorScriptFile> GetOpenedFiles()
147147
return files.AsReadOnly();
148148
}
149149

150-
private IEditorScriptFile GetEditorFileFromScriptFile(ScriptFile file)
150+
private static IEditorScriptFile GetEditorFileFromScriptFile(ScriptFile file)
151151
{
152152
return new EditorScriptFile(file);
153153
}

src/PowerShellEditorServices/PowerShellEditorServices.csproj

-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
<Project Sdk="Microsoft.NET.Sdk">
2-
32
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), PowerShellEditorServices.Common.props))\PowerShellEditorServices.Common.props" />
43

54
<PropertyGroup>

src/PowerShellEditorServices/Services/Analysis/PssaCmdletAnalysisEngine.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -362,7 +362,7 @@ private PowerShellResult InvokePowerShell(PSCommand command)
362362
/// </summary>
363363
/// <param name="powershell">The PowerShell instance to execute.</param>
364364
/// <returns>The output of PowerShell execution.</returns>
365-
private Collection<PSObject> InvokePowerShellWithModulePathPreservation(System.Management.Automation.PowerShell powershell)
365+
private static Collection<PSObject> InvokePowerShellWithModulePathPreservation(System.Management.Automation.PowerShell powershell)
366366
{
367367
using (PSModulePathPreserver.Take())
368368
{

src/PowerShellEditorServices/Services/CodeLens/PesterCodeLensProvider.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ public PesterCodeLensProvider(ConfigurationService configurationService)
4242
/// <param name="pesterSymbol">The Pester symbol to get CodeLenses for.</param>
4343
/// <param name="scriptFile">The script file the Pester symbol comes from.</param>
4444
/// <returns>All CodeLenses for the given Pester symbol.</returns>
45-
private CodeLens[] GetPesterLens(PesterSymbolReference pesterSymbol, ScriptFile scriptFile)
45+
private static CodeLens[] GetPesterLens(PesterSymbolReference pesterSymbol, ScriptFile scriptFile)
4646
{
4747
string word = pesterSymbol.Command == PesterCommandType.It ? "test" : "tests";
4848
var codeLensResults = new CodeLens[]

src/PowerShellEditorServices/Services/CodeLens/ReferencesCodeLensProvider.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,7 @@ public CodeLens ResolveCodeLens(CodeLens codeLens, ScriptFile scriptFile)
8686
ScriptFile[] references = _workspaceService.ExpandScriptReferences(
8787
scriptFile);
8888

89-
SymbolReference foundSymbol = _symbolsService.FindFunctionDefinitionAtLocation(
89+
SymbolReference foundSymbol = SymbolsService.FindFunctionDefinitionAtLocation(
9090
scriptFile,
9191
codeLens.Range.Start.Line + 1,
9292
codeLens.Range.Start.Character + 1);

src/PowerShellEditorServices/Services/DebugAdapter/BreakpointService.cs

+4-4
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ public async Task<List<Breakpoint>> GetBreakpointsAsync()
4747
// Legacy behavior
4848
PSCommand psCommand = new PSCommand();
4949
psCommand.AddCommand(@"Microsoft.PowerShell.Utility\Get-PSBreakpoint");
50-
IEnumerable<Breakpoint> breakpoints = await _powerShellContextService.ExecuteCommandAsync<Breakpoint>(psCommand);
50+
IEnumerable<Breakpoint> breakpoints = await _powerShellContextService.ExecuteCommandAsync<Breakpoint>(psCommand).ConfigureAwait(false);
5151
return breakpoints.ToList();
5252
}
5353

@@ -133,7 +133,7 @@ public async Task<IEnumerable<BreakpointDetails>> SetBreakpointsAsync(string esc
133133
if (psCommand != null)
134134
{
135135
IEnumerable<Breakpoint> setBreakpoints =
136-
await _powerShellContextService.ExecuteCommandAsync<Breakpoint>(psCommand);
136+
await _powerShellContextService.ExecuteCommandAsync<Breakpoint>(psCommand).ConfigureAwait(false);
137137
configuredBreakpoints.AddRange(
138138
setBreakpoints.Select(BreakpointDetails.Create));
139139
}
@@ -210,7 +210,7 @@ public async Task<IEnumerable<CommandBreakpointDetails>> SetCommandBreakpoints(I
210210
if (psCommand != null)
211211
{
212212
IEnumerable<Breakpoint> setBreakpoints =
213-
await _powerShellContextService.ExecuteCommandAsync<Breakpoint>(psCommand);
213+
await _powerShellContextService.ExecuteCommandAsync<Breakpoint>(psCommand).ConfigureAwait(false);
214214
configuredBreakpoints.AddRange(
215215
setBreakpoints.Select(CommandBreakpointDetails.Create));
216216
}
@@ -301,7 +301,7 @@ public async Task RemoveBreakpointsAsync(IEnumerable<Breakpoint> breakpoints)
301301
psCommand.AddCommand(@"Microsoft.PowerShell.Utility\Remove-PSBreakpoint");
302302
psCommand.AddParameter("Id", breakpoints.Select(b => b.Id).ToArray());
303303

304-
await _powerShellContextService.ExecuteCommandAsync<object>(psCommand);
304+
await _powerShellContextService.ExecuteCommandAsync<object>(psCommand).ConfigureAwait(false);
305305
}
306306
}
307307

src/PowerShellEditorServices/Services/DebugAdapter/DebugService.cs

+6-6
Original file line numberDiff line numberDiff line change
@@ -43,8 +43,6 @@ internal class DebugService
4343
private StackFrameDetails[] stackFrameDetails;
4444
private readonly PropertyInfo invocationTypeScriptPositionProperty;
4545

46-
private static int breakpointHitCounter;
47-
4846
private readonly SemaphoreSlim debugInfoHandle = AsyncUtils.CreateSimpleLockingSemaphore();
4947
#endregion
5048

@@ -190,7 +188,7 @@ public async Task<BreakpointDetails[]> SetLineBreakpointsAsync(
190188
return await dscBreakpoints.SetLineBreakpointsAsync(
191189
this.powerShellContext,
192190
escapedScriptPath,
193-
breakpoints);
191+
breakpoints).ConfigureAwait(false);
194192
}
195193

196194
/// <summary>
@@ -208,7 +206,9 @@ public async Task<CommandBreakpointDetails[]> SetCommandBreakpointsAsync(
208206
if (clearExisting)
209207
{
210208
// Flatten dictionary values into one list and remove them all.
211-
await _breakpointService.RemoveBreakpointsAsync((await _breakpointService.GetBreakpointsAsync()).Where( i => i is CommandBreakpoint)).ConfigureAwait(false);
209+
await _breakpointService.RemoveBreakpointsAsync(
210+
(await _breakpointService.GetBreakpointsAsync().ConfigureAwait(false))
211+
.Where( i => i is CommandBreakpoint)).ConfigureAwait(false);
212212
}
213213

214214
if (breakpoints.Length > 0)
@@ -854,7 +854,7 @@ private async Task FetchStackFramesAsync(string scriptNameOverride)
854854
}
855855
}
856856

857-
private string TrimScriptListingLine(PSObject scriptLineObj, ref int prefixLength)
857+
private static string TrimScriptListingLine(PSObject scriptLineObj, ref int prefixLength)
858858
{
859859
string scriptLine = scriptLineObj.ToString();
860860

@@ -906,7 +906,7 @@ await this.powerShellContext.ExecuteCommandAsync<PSObject>(
906906
string.Join(
907907
Environment.NewLine,
908908
scriptListingLines
909-
.Select(o => this.TrimScriptListingLine(o, ref linePrefixLength))
909+
.Select(o => DebugService.TrimScriptListingLine(o, ref linePrefixLength))
910910
.Where(s => s != null));
911911

912912
this.temporaryScriptListingPath =

src/PowerShellEditorServices/Services/DebugAdapter/Handlers/DisconnectHandler.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,7 @@ public async Task<DisconnectResponse> Handle(DisconnectArguments request, Cancel
7575

7676
#pragma warning disable CS4014
7777
// Trigger the clean up of the debugger. No need to wait for it.
78-
Task.Run(_psesDebugServer.OnSessionEnded);
78+
Task.Run(_psesDebugServer.OnSessionEnded, cancellationToken);
7979
#pragma warning restore CS4014
8080

8181
return new DisconnectResponse();

0 commit comments

Comments
 (0)