Skip to content

Add suggested correction to PSMissingModuleManifestField rule #515

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
merged 3 commits into from
May 3, 2016
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
80 changes: 77 additions & 3 deletions Rules/MissingModuleManifestField.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
using Microsoft.Windows.PowerShell.ScriptAnalyzer.Generic;
using System.ComponentModel.Composition;
using System.Globalization;
using System.Text;

namespace Microsoft.Windows.PowerShell.ScriptAnalyzer.BuiltinRules
{
Expand Down Expand Up @@ -46,16 +47,89 @@ public IEnumerable<DiagnosticRecord> AnalyzeScript(Ast ast, string fileName)
{
if (Helper.IsMissingManifestMemberException(errorRecord))
{
System.Diagnostics.Debug.Assert(errorRecord.Exception != null && !String.IsNullOrWhiteSpace(errorRecord.Exception.Message), Strings.NullErrorMessage);
yield return
new DiagnosticRecord(errorRecord.Exception.Message, ast.Extent, GetName(), DiagnosticSeverity.Warning, fileName);
System.Diagnostics.Debug.Assert(
errorRecord.Exception != null && !String.IsNullOrWhiteSpace(errorRecord.Exception.Message),
Strings.NullErrorMessage);
var hashTableAst = ast.Find(x => x is HashtableAst, false);
yield return new DiagnosticRecord(
errorRecord.Exception.Message,
hashTableAst.Extent,
GetName(),
DiagnosticSeverity.Warning,
fileName,
suggestedCorrections:GetCorrectionExtent(hashTableAst as HashtableAst));
}

}
}
}

}

/// <summary>
/// Gets the correction extent
/// </summary>
/// <param name="ast"></param>
/// <returns>A List of CorrectionExtent</returns>
private List<CorrectionExtent> GetCorrectionExtent(HashtableAst ast)
{
int startLineNumber;
int startColumnNumber;

// for empty hashtable insert after after "@{"
if (ast.KeyValuePairs.Count == 0)
{
// check if ast starts with "@{"
if (ast.Extent.Text.IndexOf("@{") != 0)
{
return null;
}
startLineNumber = ast.Extent.StartLineNumber;
startColumnNumber = ast.Extent.StartColumnNumber + 2; // 2 for "@{",
}
else // for non-empty hashtable insert after the last element
{
int maxLine = 0;
int lastCol = 0;
foreach (var keyVal in ast.KeyValuePairs)
{
if (keyVal.Item2.Extent.EndLineNumber > maxLine)
{
maxLine = keyVal.Item2.Extent.EndLineNumber;
lastCol = keyVal.Item2.Extent.EndColumnNumber;
}
}
startLineNumber = maxLine;
startColumnNumber = lastCol;
}

var correctionExtents = new List<CorrectionExtent>();
string fieldName = "ModuleVersion";
string fieldValue = "1.0.0.0";
string description = string.Format(
CultureInfo.CurrentCulture,
Strings.MissingModuleManifestFieldCorrectionDescription,
fieldName,
fieldValue);
var correctionTextTemplate = @"
# Version number of this module.
{0} = '{1}'
";
var correctionText = string.Format(
correctionTextTemplate,
fieldName,
fieldValue);
var correctionExtent = new CorrectionExtent(
startLineNumber,
startLineNumber,
startColumnNumber,
startColumnNumber,
correctionText,
ast.Extent.File,
description);
correctionExtents.Add(correctionExtent);
return correctionExtents;
}

/// <summary>
/// GetName: Retrieves the name of this rule.
Expand Down
9 changes: 9 additions & 0 deletions Rules/Strings.Designer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions Rules/Strings.resx
Original file line number Diff line number Diff line change
Expand Up @@ -816,6 +816,9 @@
<data name="AvoidUsingPlainTextForPasswordCorrectionDescription" xml:space="preserve">
<value>Set {0} type to SecureString</value>
</data>
<data name="MissingModuleManifestFieldCorrectionDescription" xml:space="preserve">
<value>Add {0} = {1} to the module manifest</value>
</data>
<data name="UseToExportFieldsInManifestCorrectionDescription" xml:space="preserve">
<value>Replace {0} with {1}</value>
</data>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,19 @@
$missingMessage = "The member 'ModuleVersion' is not present in the module manifest."
$missingName = "PSMissingModuleManifestField"
$directory = Split-Path -Parent $MyInvocation.MyCommand.Path
$violations = Invoke-ScriptAnalyzer $directory\TestBadModule\TestBadModule.psd1 | Where-Object {$_.RuleName -eq $missingName}
$violationFilepath = Join-Path $directory "TestBadModule\TestBadModule.psd1"
$violations = Invoke-ScriptAnalyzer $violationFilepath | Where-Object {$_.RuleName -eq $missingName}
$noViolations = Invoke-ScriptAnalyzer $directory\TestGoodModule\TestGoodModule.psd1 | Where-Object {$_.RuleName -eq $missingName}

Describe "MissingRequiredFieldModuleManifest" {
BeforeAll {
Import-Module (Join-Path $directory "PSScriptAnalyzerTestHelper.psm1")
}

AfterAll{
Remove-Module PSScriptAnalyzerTestHelper
}

Context "When there are violations" {
It "has 1 missing required field module manifest violation" {
$violations.Count | Should Be 1
Expand All @@ -14,7 +23,22 @@ Describe "MissingRequiredFieldModuleManifest" {
It "has the correct description message" {
$violations.Message | Should Match $missingMessage
}
}

$numExpectedCorrections = 1
It "has $numExpectedCorrections suggested corrections" {
$violations.SuggestedCorrections.Count | Should Be $numExpectedCorrections
}


It "has the right suggested correction" {
$expectedText = @'
# Version number of this module.
ModuleVersion = '1.0.0.0'
'@
$violations[0].SuggestedCorrections[0].Text | Should Match $expectedText
Get-ExtentText $violations[0].SuggestedCorrections[0] $violationFilepath | Should Match ""
}
}

Context "When there are no violations" {
It "returns no violations" {
Expand Down