Skip to content

Rule to validate the presence of Verbose statements in DSC Resource #238

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 6 commits into from
Jun 10, 2015
Merged
Show file tree
Hide file tree
Changes from 5 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
2 changes: 1 addition & 1 deletion Rules/ScriptAnalyzerBuiltinRules.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@
<Compile Include="MissingModuleManifestField.cs" />
<Compile Include="PossibleIncorrectComparisonWithNull.cs" />
<Compile Include="ProvideCommentHelp.cs" />
<Compile Include="ProvideVerboseMessage.cs" />
<Compile Include="UseVerboseMessageInDSCResource.cs" />
<Compile Include="Strings.Designer.cs">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
Expand Down
83 changes: 37 additions & 46 deletions Rules/Strings.Designer.cs

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

19 changes: 8 additions & 11 deletions Rules/Strings.resx
Original file line number Diff line number Diff line change
Expand Up @@ -276,17 +276,14 @@
<data name="SourceName" xml:space="preserve">
<value>PS</value>
</data>
<data name="ProvideVerboseMessageDescription" xml:space="preserve">
<value>Checks that Write-Verbose is called at least once in every cmdlet or script. This is in line with the PowerShell best practices.</value>
<data name="UseVerboseMessageInDSCResourceDescription" xml:space="preserve">
<value>It is a best practice to emit informative, verbose messages in DSC resource functions. This helps in debugging issues when a DSC configuration is executed.</value>
</data>
<data name="ProvideVerboseMessageErrorFunction" xml:space="preserve">
<value>There is no call to Write-Verbose in the function ‘{0}’.</value>
<data name="UseVerboseMessageInDSCResourceErrorFunction" xml:space="preserve">
<value>There is no call to Write-Verbose in DSC function ‘{0}’. If you are using Write-Verbose in a helper function, suppress this rule application.</value>
</data>
<data name="ProvideVerboseMessageCommonName" xml:space="preserve">
<value>Verbose</value>
</data>
<data name="ProvideVerboseMessageScript" xml:space="preserve">
<value>There is no call to Write-Verbose in the script.</value>
<data name="UseVerboseMessageInDSCResourceCommonName" xml:space="preserve">
<value>Use verbose message in DSC resource</value>
</data>
<data name="MissingModuleManifestFieldDescription" xml:space="preserve">
<value>Some fields of the module manifest (such as ModuleVersion) are required.</value>
Expand Down Expand Up @@ -459,8 +456,8 @@
<data name="MissingModuleManifestFieldName" xml:space="preserve">
<value>MissingModuleManifestField</value>
</data>
<data name="ProvideVerboseMessageName" xml:space="preserve">
<value>ProvideVerboseMessage</value>
<data name="UseVerboseMessageInDSCResourceName" xml:space="preserve">
<value>UseVerboseMessageInDSCResource</value>
</data>
<data name="CommandNotFoundCommonName" xml:space="preserve">
<value>Command Not Found</value>
Expand Down
3 changes: 1 addition & 2 deletions Rules/UseDeclaredVarsMoreThanAssignments.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,7 @@ public IEnumerable<DiagnosticRecord> AnalyzeScript(Ast ast, string fileName)
{
if (ast == null) throw new ArgumentNullException(Strings.NullAstErrorMessage);

IEnumerable<Ast> assignmentAsts = ast.FindAll(testAst => testAst is AssignmentStatementAst, true);
IEnumerable<Ast> assingmentVarAsts;
IEnumerable<Ast> assignmentAsts = ast.FindAll(testAst => testAst is AssignmentStatementAst, true);
IEnumerable<Ast> varAsts = ast.FindAll(testAst => testAst is VariableExpressionAst, true);
IEnumerable<Ast> varsInAssignment;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,78 +22,66 @@
namespace Microsoft.Windows.PowerShell.ScriptAnalyzer.BuiltinRules
{
/// <summary>
/// ProvideVerboseMessage: Analyzes the ast to check that Write-Verbose is called at least once in every cmdlet or script.
/// ProvideVerboseMessage: Analyzes the ast to check that Write-Verbose is called for DSC Resources
/// </summary>
[Export(typeof(IScriptRule))]
public class ProvideVerboseMessage : SkipNamedBlock, IScriptRule
[Export(typeof(IDSCResourceRule))]
public class UseVerboseMessageInDSCResource : SkipNamedBlock, IDSCResourceRule
{
/// <summary>
/// AnalyzeScript: Analyzes the ast to check that Write-Verbose is called at least once in every cmdlet or script.
/// AnalyzeDSCResource: Analyzes the ast to check that Write-Verbose is called for DSC Resources
/// <param name="ast">The script's ast</param>
/// <param name="fileName">The script's file name</param>
/// </summary>
public IEnumerable<DiagnosticRecord> AnalyzeScript(Ast ast, string fileName)
public IEnumerable<DiagnosticRecord> AnalyzeDSCResource(Ast ast, string fileName)
{
if (ast == null) throw new ArgumentNullException(Strings.NullAstErrorMessage);

ClearList();
this.AddNames(new List<string>() { "Configuration", "Workflow" });
DiagnosticRecords.Clear();

this.fileName = fileName;
//We only check that advanced functions should have Write-Verbose
ast.Visit(this);

return DiagnosticRecords;
}

/// <summary>
/// Visit function and checks that it has write verbose
/// </summary>
/// <param name="funcAst"></param>
/// <returns></returns>
public override AstVisitAction VisitFunctionDefinition(FunctionDefinitionAst funcAst)
{
if (funcAst == null)
if (ast == null)
{
return AstVisitAction.SkipChildren;
throw new ArgumentNullException(Strings.NullAstErrorMessage);
}

//Write-Verbose is not required for non-advanced functions
if (funcAst.Body == null || funcAst.Body.ParamBlock == null
|| funcAst.Body.ParamBlock.Attributes == null ||
funcAst.Body.ParamBlock.Parameters == null ||
!funcAst.Body.ParamBlock.Attributes.Any(attr => attr.TypeName.GetReflectionType() == typeof(CmdletBindingAttribute)))
{
return AstVisitAction.Continue;
}
List<string> expectedTargetResourceFunctionNames = new List<string>(new string[] { "Set-TargetResource", "Test-TargetResource", "Get-TargetResource" });

Choose a reason for hiding this comment

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

I don't think we use this anywhere in the code?

Copy link
Member Author

Choose a reason for hiding this comment

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

Quoc. I did not understand your comment.

Since this rule is enabled only for cmdlet based DSC resources, we do not need to validate for advanced functions...

Choose a reason for hiding this comment

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

Oh I mean the DscResourceFunctions in the Helper class already takes out the set, get and test targetresource functions. Also what I mean is we didn't use the variable expectedTargetResourceFunctionNames anywhere in this file?


var commandAsts = funcAst.Body.FindAll(testAst => testAst is CommandAst, false);
bool hasVerbose = false;
IEnumerable<Ast> functionDefinitionAsts = Helper.Instance.DscResourceFunctions(ast);

if (commandAsts != null)
foreach (FunctionDefinitionAst functionDefinitionAst in functionDefinitionAsts)
{
foreach (CommandAst commandAst in commandAsts)
var commandAsts = functionDefinitionAst.Body.FindAll(testAst => testAst is CommandAst, false);
bool hasVerbose = false;

if (null != commandAsts)
{
hasVerbose |= String.Equals(commandAst.GetCommandName(), "Write-Verbose", StringComparison.OrdinalIgnoreCase);
foreach (CommandAst commandAst in commandAsts)
{
hasVerbose |= String.Equals(commandAst.GetCommandName(), "Write-Verbose", StringComparison.OrdinalIgnoreCase);
}
}
}

if (!hasVerbose)
{
DiagnosticRecords.Add(new DiagnosticRecord(string.Format(CultureInfo.CurrentCulture, Strings.ProvideVerboseMessageErrorFunction, funcAst.Name),
funcAst.Extent, GetName(), DiagnosticSeverity.Information, fileName));
}
if (!hasVerbose)
{
yield return new DiagnosticRecord(string.Format(CultureInfo.CurrentCulture, Strings.UseVerboseMessageInDSCResourceErrorFunction, functionDefinitionAst.Name),
functionDefinitionAst.Extent, GetName(), DiagnosticSeverity.Information, fileName);
}

return AstVisitAction.Continue;
}
}

/// <summary>
/// AnalyzeDSCClass: This function returns nothing in the case of dsc class.
/// </summary>
/// <param name="ast"></param>
/// <param name="fileName"></param>
/// <returns></returns>
public IEnumerable<DiagnosticRecord> AnalyzeDSCClass(Ast ast, string fileName)
{
return Enumerable.Empty<DiagnosticRecord>();
}

/// <summary>
/// Method: Retrieves the name of this rule.
/// </summary>
public string GetName()
{
return string.Format(CultureInfo.CurrentCulture, Strings.NameSpaceFormat, GetSourceName(), Strings.ProvideVerboseMessageName);
return string.Format(CultureInfo.CurrentCulture, Strings.NameSpaceFormat, GetSourceName(), Strings.UseVerboseMessageInDSCResourceName);
}

/// <summary>
Expand All @@ -102,7 +90,7 @@ public string GetName()
/// <returns>The common name of this rule</returns>
public string GetCommonName()
{
return string.Format(CultureInfo.CurrentCulture, Strings.ProvideVerboseMessageCommonName);
return string.Format(CultureInfo.CurrentCulture, Strings.UseVerboseMessageInDSCResourceCommonName);
}

/// <summary>
Expand All @@ -111,7 +99,7 @@ public string GetCommonName()
/// <returns>The description of this rule</returns>
public string GetDescription()
{
return string.Format(CultureInfo.CurrentCulture, Strings.ProvideVerboseMessageDescription);
return string.Format(CultureInfo.CurrentCulture, Strings.UseVerboseMessageInDSCResourceDescription);
}

/// <summary>
Expand All @@ -136,7 +124,7 @@ public RuleSeverity GetSeverity()
/// </summary>
public string GetSourceName()
{
return string.Format(CultureInfo.CurrentCulture, Strings.SourceName);
return string.Format(CultureInfo.CurrentCulture, Strings.DSCSourceName);
}
}
}
}
4 changes: 2 additions & 2 deletions Tests/Engine/GetScriptAnalyzerRule.tests.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -130,11 +130,11 @@ Describe "TestSeverity" {
Describe "TestWildCard" {
It "filters rules based on the -Name wild card input" {
$rules = Get-ScriptAnalyzerRule -Name PSDSC*
$rules.Count | Should be 6
$rules.Count | Should be 7
}

It "filters rules based on wild card input and severity"{
$rules = Get-ScriptAnalyzerRule -Name PSDSC* -Severity Information
$rules.Count | Should be 3
$rules.Count | Should be 4
}
}
2 changes: 1 addition & 1 deletion Tests/Engine/RuleSuppression.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ Param(

function SuppressMe ()
{
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSProvideVerboseMessage")]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSProvideCommentHelp")]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSProvideDefaultParameterValue", "unused1")]
Param([string]$unUsed1, [int] $unUsed2)
{
Expand Down
2 changes: 1 addition & 1 deletion Tests/Engine/RuleSuppression.tests.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ $violations = Invoke-ScriptAnalyzer $directory\RuleSuppression.ps1
Describe "RuleSuppressionWithoutScope" {
Context "Function" {
It "Does not raise violations" {
$suppression = $violations | Where-Object { $_.RuleName -eq "PSProvideVerboseMessage" }
$suppression = $violations | Where-Object { $_.RuleName -eq "PSProvideCommentHelp" }
$suppression.Count | Should Be 0
}
}
Expand Down
8 changes: 8 additions & 0 deletions Tests/Rules/DSCResources/MSFT_WaitForAny/MSFT_WaitForAny.psm1
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ function Get-TargetResource
[Uint32] $ThrottleLimit = 32 #Powershell New-CimSession default throttle value
)

Write-Verbose "In Get-TargetResource"

Import-Module $PSScriptRoot\..\..\PSDSCxMachine.psm1

$b = @{"hash" = "table"}
Expand Down Expand Up @@ -75,10 +77,14 @@ function Set-TargetResource
[Uint32] $ThrottleLimit = 32 #Powershell New-CimSession default throttle value
)

Write-Verbose "In Set-TargetResource"

Import-Module $PSScriptRoot\..\..\PSDSCxMachine.psm1

if ($PSBoundParameters["Verbose"])
{
Write-Verbose "Calling xMachine with Verbose parameter"

PSDSCxMachine\Set-_InternalPSDscXMachineTR `
-RemoteResourceId $ResourceName `
-RemoteMachine $NodeName `
Expand Down Expand Up @@ -130,6 +136,8 @@ function Test-TargetResource
[Uint32] $ThrottleLimit = 32 #Powershell New-CimSession default throttle value
)

Write-Verbose "In Test-TargetResource"

Import-Module $PSScriptRoot\..\..\PSDSCxMachine.psm1

$a = $true
Expand Down
26 changes: 26 additions & 0 deletions Tests/Rules/UseVerboseMessageInDSCResource.Tests.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
Import-Module PSScriptAnalyzer

$violationMessage = "There is no call to Write-Verbose in DSC function ‘Set-TargetResource’. If you are using Write-Verbose in a helper function, suppress this rule application."
$violationName = "PSDSCUseVerboseMessageInDSCResource"
$directory = Split-Path -Parent $MyInvocation.MyCommand.Path
$violations = Invoke-ScriptAnalyzer $directory\DSCResources\MSFT_WaitForAll\MSFT_WaitForAll.psm1 | Where-Object {$_.RuleName -eq $violationName}
$noViolations = Invoke-ScriptAnalyzer $directory\DSCResources\MSFT_WaitForAny\MSFT_WaitForAny.psm1 | Where-Object {$_.RuleName -eq $violationName}
$noClassViolations = Invoke-ScriptAnalyzer -ErrorAction SilentlyContinue $directory\DSCResources\MyDscResource\MyDscResource.psm1 | Where-Object {$_.RuleName -eq $violationName}

Describe "UseVerboseMessageInDSCResource" {
Context "When there are violations" {
It "has 2 Verbose Message violations" {
$violations.Count | Should Be 2
}

It "has the correct description message" {
$violations[0].Message | Should Match $violationMessage
}
}

Context "When there are no violations" {
It "returns no violations" {
$noViolations.Count | Should Be 0
}
}
}