-
Notifications
You must be signed in to change notification settings - Fork 394
Add PSProvideDefaultParameterValue Rule #174
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
raghushantha
merged 14 commits into
PowerShell:development
from
GoodOlClint:PSProvideDefaultParameterValue
May 18, 2015
Merged
Changes from all commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
44574b5
Add new ProvideDefaultParameterValue rule.
GoodOlClint 513b04c
Tests for ProvideDefaultParameterValue rule
GoodOlClint 503d18e
Don't trigger PSAvoidUninitializedVariable on function parameters
GoodOlClint 2f5480d
Correct PSProvideDefaultParameterValue NoViolations test script
GoodOlClint 4e9732c
Updated strings for PSProvideDefaultParameterValue
GoodOlClint 55919be
Updated Tests for PSProvideDefaultParameterValue
GoodOlClint 94dcf51
Raise PSProvideDefaultParameterValues for parameters outside a param …
GoodOlClint fdd1198
Don't raise PSAvoidUninitalizedVariables for parameters outside a par…
GoodOlClint 67dbc2c
Updated PSProvideDefaultParameterValue Rules
GoodOlClint be83037
Do not trigger PSProvideDefaultParameterValue when parameters are use…
GoodOlClint ead2e6f
More robust PSProvideDefaultParameterValue tests
GoodOlClint 18678a3
Correct Engine tests for PSProvideDefaultParameterValue
GoodOlClint 2528ca6
Remove isDscResourceFile Check from PSAvoidUninitalizedVariables Rule
GoodOlClint 276f464
Add isDscResourceFile Check to PSProvideDefaultParameterValue
GoodOlClint File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,140 @@ | ||
// | ||
// Copyright (c) Microsoft Corporation. | ||
// | ||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN | ||
// THE SOFTWARE. | ||
// | ||
|
||
using System; | ||
using System.Linq; | ||
using System.Collections.Generic; | ||
using System.Management.Automation.Language; | ||
using Microsoft.Windows.Powershell.ScriptAnalyzer.Generic; | ||
using System.ComponentModel.Composition; | ||
using System.Globalization; | ||
|
||
namespace Microsoft.Windows.Powershell.ScriptAnalyzer.BuiltinRules | ||
{ | ||
/// <summary> | ||
/// ProvideDefaultParameterValue: Check if any uninitialized variable is used. | ||
/// </summary> | ||
[Export(typeof(IScriptRule))] | ||
public class ProvideDefaultParameterValue : IScriptRule | ||
{ | ||
/// <summary> | ||
/// AnalyzeScript: Check if any uninitialized variable is used. | ||
/// </summary> | ||
public IEnumerable<DiagnosticRecord> AnalyzeScript(Ast ast, string fileName) | ||
{ | ||
if (ast == null) throw new ArgumentNullException(Strings.NullAstErrorMessage); | ||
|
||
// Finds all functionAst | ||
IEnumerable<Ast> functionAsts = ast.FindAll(testAst => testAst is FunctionDefinitionAst, true); | ||
|
||
// Checks whether this is a dsc resource file (we don't raise this rule for get, set and test-target resource | ||
bool isDscResourceFile = Helper.Instance.IsDscResourceModule(fileName); | ||
|
||
List<string> targetResourcesFunctions = new List<string>(new string[] { "get-targetresource", "set-targetresource", "test-targetresource" }); | ||
|
||
|
||
foreach (FunctionDefinitionAst funcAst in functionAsts) | ||
{ | ||
// Finds all ParamAsts. | ||
IEnumerable<Ast> varAsts = funcAst.FindAll(testAst => testAst is VariableExpressionAst, true); | ||
|
||
// Iterrates all ParamAsts and check if their names are on the list. | ||
|
||
HashSet<string> dscVariables = new HashSet<string>(); | ||
if (isDscResourceFile && targetResourcesFunctions.Contains(funcAst.Name, StringComparer.OrdinalIgnoreCase)) | ||
{ | ||
// don't raise the rules for variables in the param block. | ||
if (funcAst.Body != null && funcAst.Body.ParamBlock != null && funcAst.Body.ParamBlock.Parameters != null) | ||
{ | ||
dscVariables.UnionWith(funcAst.Body.ParamBlock.Parameters.Select(paramAst => paramAst.Name.VariablePath.UserPath)); | ||
} | ||
} | ||
// only raise the rules for variables in the param block. | ||
if (funcAst.Body != null && funcAst.Body.ParamBlock != null && funcAst.Body.ParamBlock.Parameters != null) | ||
{ | ||
foreach (var paramAst in funcAst.Body.ParamBlock.Parameters) | ||
{ | ||
if (Helper.Instance.IsUninitialized(paramAst.Name, funcAst) && !dscVariables.Contains(paramAst.Name.VariablePath.UserPath)) | ||
{ | ||
yield return new DiagnosticRecord(string.Format(CultureInfo.CurrentCulture, Strings.ProvideDefaultParameterValueError, paramAst.Name.VariablePath.UserPath), | ||
paramAst.Name.Extent, GetName(), DiagnosticSeverity.Warning, fileName, paramAst.Name.VariablePath.UserPath); | ||
} | ||
} | ||
} | ||
|
||
if (funcAst.Parameters != null) | ||
{ | ||
foreach (var paramAst in funcAst.Parameters) | ||
{ | ||
if (Helper.Instance.IsUninitialized(paramAst.Name, funcAst) && !dscVariables.Contains(paramAst.Name.VariablePath.UserPath)) | ||
{ | ||
yield return new DiagnosticRecord(string.Format(CultureInfo.CurrentCulture, Strings.ProvideDefaultParameterValueError, paramAst.Name.VariablePath.UserPath), | ||
paramAst.Name.Extent, GetName(), DiagnosticSeverity.Warning, fileName, paramAst.Name.VariablePath.UserPath); | ||
} | ||
} | ||
} | ||
} | ||
} | ||
|
||
/// <summary> | ||
/// GetName: Retrieves the name of this rule. | ||
/// </summary> | ||
/// <returns>The name of this rule</returns> | ||
public string GetName() | ||
{ | ||
return string.Format(CultureInfo.CurrentCulture, Strings.NameSpaceFormat, GetSourceName(), Strings.ProvideDefaultParameterValueName); | ||
} | ||
|
||
/// <summary> | ||
/// GetCommonName: Retrieves the common name of this rule. | ||
/// </summary> | ||
/// <returns>The common name of this rule</returns> | ||
public string GetCommonName() | ||
{ | ||
return string.Format(CultureInfo.CurrentCulture, Strings.ProvideDefaultParameterValueCommonName); | ||
} | ||
|
||
/// <summary> | ||
/// GetDescription: Retrieves the description of this rule. | ||
/// </summary> | ||
/// <returns>The description of this rule</returns> | ||
public string GetDescription() | ||
{ | ||
return string.Format(CultureInfo.CurrentCulture, Strings.ProvideDefaultParameterValueDescription); | ||
} | ||
|
||
/// <summary> | ||
/// Method: Retrieves the type of the rule: builtin, managed or module. | ||
/// </summary> | ||
public SourceType GetSourceType() | ||
{ | ||
return SourceType.Builtin; | ||
} | ||
|
||
/// <summary> | ||
/// GetSeverity: Retrieves the severity of the rule: error, warning of information. | ||
/// </summary> | ||
/// <returns></returns> | ||
public RuleSeverity GetSeverity() | ||
{ | ||
return RuleSeverity.Warning; | ||
} | ||
|
||
/// <summary> | ||
/// Method: Retrieves the module/assembly name the rule is from. | ||
/// </summary> | ||
public string GetSourceName() | ||
{ | ||
return string.Format(CultureInfo.CurrentCulture, Strings.SourceName); | ||
} | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
function BadFunc | ||
{ | ||
param( | ||
[Parameter(Mandatory=$true)] | ||
[ValidateNotNullOrEmpty()] | ||
[string] | ||
$Param1, | ||
[Parameter(Mandatory=$false)] | ||
[ValidateNotNullOrEmpty()] | ||
[string] | ||
$Param2 | ||
) | ||
$Param1 | ||
$Param1 = "test" | ||
} | ||
|
||
function BadFunc2($Param1) | ||
{ | ||
$Param1 | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
Import-Module PSScriptAnalyzer | ||
$violationName = "PSProvideDefaultParameterValue" | ||
$violationMessage = "Parameter 'Param2' is not initialized. Parameters must have a default value. To fix a violation of this rule, please specify a default value for all parameters" | ||
$directory = Split-Path -Parent $MyInvocation.MyCommand.Path | ||
$violations = Invoke-ScriptAnalyzer $directory\ProvideDefaultParameterValue.ps1 | Where-Object {$_.RuleName -match $violationName} | ||
$noViolations = Invoke-ScriptAnalyzer $directory\ProvideDefaultParameterValueNoViolations.ps1 | ||
|
||
Describe "ProvideDefaultParameters" { | ||
Context "When there are violations" { | ||
It "has 2 provide default parameter value violation" { | ||
$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 | ||
} | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
function GoodFunc | ||
{ | ||
param( | ||
[Parameter(Mandatory=$true)] | ||
[ValidateNotNullOrEmpty()] | ||
[string] | ||
$Param1, | ||
[Parameter(Mandatory=$false)] | ||
[ValidateNotNullOrEmpty()] | ||
[string] | ||
$Param2=$null | ||
) | ||
$Param1 | ||
} | ||
|
||
function GoodFunc2($Param1 = $null) | ||
{ | ||
$Param1 | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
If we don't raise this error for param block, I think you can remove the checking for whether this is a DSC resource file.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Taken care of in 2528ca6