Skip to content

Support SuggestedCorrections property on DiagnosticRecord for script based rules #1000

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

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
5 changes: 3 additions & 2 deletions Engine/Generic/DiagnosticRecord.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ public class DiagnosticRecord
private DiagnosticSeverity severity;
private string scriptPath;
private string ruleSuppressionId;
private List<CorrectionExtent> suggestedCorrections;
private IEnumerable<CorrectionExtent> suggestedCorrections;

/// <summary>
/// Represents a string from the rule about why this diagnostic was created.
Expand Down Expand Up @@ -89,6 +89,7 @@ public string RuleSuppressionID
public IEnumerable<CorrectionExtent> SuggestedCorrections
{
get { return suggestedCorrections; }
set { suggestedCorrections = value; }
}

/// <summary>
Expand All @@ -108,7 +109,7 @@ public DiagnosticRecord()
/// <param name="severity">The severity of this diagnostic</param>
/// <param name="scriptPath">The full path of the script file being analyzed</param>
/// <param name="suggestedCorrections">The correction suggested by the rule to replace the extent text</param>
public DiagnosticRecord(string message, IScriptExtent extent, string ruleName, DiagnosticSeverity severity, string scriptPath, string ruleId = null, List<CorrectionExtent> suggestedCorrections = null)
public DiagnosticRecord(string message, IScriptExtent extent, string ruleName, DiagnosticSeverity severity, string scriptPath, string ruleId = null, IEnumerable<CorrectionExtent> suggestedCorrections = null)
{
Message = message;
RuleName = ruleName;
Expand Down
4 changes: 3 additions & 1 deletion Engine/ScriptAnalyzer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1267,6 +1267,7 @@ internal IEnumerable<DiagnosticRecord> GetExternalRecord(Ast ast, Token[] token,
IScriptExtent extent;
string message = string.Empty;
string ruleName = string.Empty;
IEnumerable<CorrectionExtent> suggestedCorrections;

if (psobject != null && psobject.ImmediateBaseObject != null)
{
Expand All @@ -1286,6 +1287,7 @@ internal IEnumerable<DiagnosticRecord> GetExternalRecord(Ast ast, Token[] token,
message = psobject.Properties["Message"].Value.ToString();
extent = (IScriptExtent)psobject.Properties["Extent"].Value;
ruleName = psobject.Properties["RuleName"].Value.ToString();
suggestedCorrections = (IEnumerable<CorrectionExtent>)psobject.Properties["SuggestedCorrections"].Value;
}
catch (Exception ex)
{
Expand All @@ -1295,7 +1297,7 @@ internal IEnumerable<DiagnosticRecord> GetExternalRecord(Ast ast, Token[] token,

if (!string.IsNullOrEmpty(message))
{
diagnostics.Add(new DiagnosticRecord(message, extent, ruleName, severity, filePath));
diagnostics.Add(new DiagnosticRecord(message, extent, ruleName, severity, filePath) { SuggestedCorrections = suggestedCorrections });
}
}
}
Expand Down
23 changes: 22 additions & 1 deletion ScriptRuleDocumentation.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ Param
)
```

- DiagnosticRecord should have four properties: Message, Extent, RuleName and Severity
- DiagnosticRecord should have at least four properties: Message, Extent, RuleName and Severity

``` PowerShell
$result = [Microsoft.Windows.PowerShell.ScriptAnalyzer.Generic.DiagnosticRecord[]]@{
Expand All @@ -61,6 +61,27 @@ $result = [Microsoft.Windows.PowerShell.ScriptAnalyzer.Generic.DiagnosticRecord[
"Severity" = "Warning"
}
```
Optionally, since version 1.17.0, a `SuggestedCorrections` property of type `IEnumerable<CorrectionExtent>` can also be added in script rules but care must be taken that the type is correct, an example is:
```powershell
[int]$startLineNumber = $ast.Extent.StartLineNumber
[int]$endLineNumber = $ast.Extent.EndLineNumber
[int]$startColumnNumber = $ast.Extent.StartColumnNumber
[int]$endColumnNumber = $ast.Extent.EndColumnNumber
[string]$correction = 'Correct text that replaces Extent text'
[string]$file = $MyInvocation.MyCommand.Definition
[string]$optionalDescription = 'Useful but optional description text'
$correctionExtent = New-Object 'Microsoft.Windows.PowerShell.ScriptAnalyzer.Generic.CorrectionExtent' $startLineNumber,$endLineNumber,$startColumnNumber,$endColumnNumber,$correction,$description
$suggestedCorrections = New-Object System.Collections.ObjectModel.Collection['Microsoft.Windows.PowerShell.ScriptAnalyzer.Generic.CorrectionExtent']
$suggestedCorrections.add($correctionExtent) | out-null

[Microsoft.Windows.Powershell.ScriptAnalyzer.Generic.DiagnosticRecord]@{
"Message" = "This is a rule with a suggested correction"
"Extent" = $ast.Extent
"RuleName" = $PSCmdlet.MyInvocation.InvocationName
"Severity" = "Warning"
"SuggestedCorrections" = $suggestedCorrections
}
```

- Make sure you export the function(s) at the end of the script using Export-ModuleMember

Expand Down
13 changes: 13 additions & 0 deletions Tests/Engine/CustomizedRule.tests.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,19 @@ Describe "Test importing correct customized rules" {
$violations[0].ScriptPath | Should -Be $expectedScriptPath
}

It "will set SuggestedCorrections" {
$violations = Invoke-ScriptAnalyzer $directory\TestScript.ps1 -CustomizedRulePath $directory\samplerule
$expectedScriptPath = Join-Path $directory 'TestScript.ps1'
$violations[0].SuggestedCorrections | Should -Not -BeNullOrEmpty
$violations[0].SuggestedCorrections.StartLineNumber | Should -Be 1
$violations[0].SuggestedCorrections.EndLineNumber | Should -Be 2
$violations[0].SuggestedCorrections.StartColumnNumber | Should -Be 3
$violations[0].SuggestedCorrections.EndColumnNumber | Should -Be 4
$violations[0].SuggestedCorrections.Text | Should -Be 'text'
$violations[0].SuggestedCorrections.File | Should -Be 'filePath'
$violations[0].SuggestedCorrections.Description | Should -Be 'description'
}

if (!$testingLibraryUsage)
{
It "will show the custom rule in the results when given a rule folder path with trailing backslash" {
Expand Down
9 changes: 6 additions & 3 deletions Tests/Engine/samplerule/samplerule.psm1
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,12 @@ function Measure-RequiresRunAsAdministrator
[System.Management.Automation.Language.ScriptBlockAst]
$testAst
)
$dr = New-Object `
$l=(new-object System.Collections.ObjectModel.Collection["Microsoft.Windows.PowerShell.ScriptAnalyzer.Generic.CorrectionExtent"])
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

in PowerShellCore tests, we're moving away from using new-object in favor of this:

$l = [System.Collections.ObjectModel.Collection[Microsoft.Windows.PowerShell.ScriptAnalyzer.Generic.CorrectionExtent]]::new()
$c = [Microsoft.Windows.PowerShell.ScriptAnalyzer.Generic.CorrectionExtent]::new(1,2,3,4,'text','filePath','description')
$null = $l.Add($c)
$dr = [Microsoft.Windows.PowerShell.ScriptAnalyzer.Generic.DiagnosticRecord]::new(
    "This is help", 
    $ast.Extent,$PSCmdlet.MyInvocation.InvocationName,
    "Warning",
    $null,
    $null,
    $l)
return $dr

which I think is much tidier. I know it's inconsistent, but that's ok - we can go back where we need to.

Copy link
Collaborator Author

@bergmeister bergmeister May 17, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@JamesWTruher I tried it at first but then had to revert this change because the [Type]::new() constructor was only introduced in version 5, therefore it failed the WMF4 build and we should not document examples that do not work on supported PS versions. Will therefore merge

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yah - I thought about this again last night and realized this wouldn't work because of the downlevel requirements. We won't be able to support the modern constructor syntax until we drop support for ps v3/4

$c = (new-object Microsoft.Windows.PowerShell.ScriptAnalyzer.Generic.CorrectionExtent 1,2,3,4,'text','filePath','description')
$l.Add($c)
$dr = New-Object `
-Typename "Microsoft.Windows.PowerShell.ScriptAnalyzer.Generic.DiagnosticRecord" `
-ArgumentList "This is help",$ast.Extent,$PSCmdlet.MyInvocation.InvocationName,Warning,$null
return @($dr)
-ArgumentList "This is help",$ast.Extent,$PSCmdlet.MyInvocation.InvocationName,Warning,$null,$null,$l
return $dr
}
Export-ModuleMember -Function Measure*