Skip to content
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

Fix PSUseDeclaredVarsMoreThanAssignments when variable is assigned more than once to still give a warning #836

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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
12 changes: 11 additions & 1 deletion Rules/UseDeclaredVarsMoreThanAssignments.cs
Expand Up @@ -166,7 +166,17 @@ private IEnumerable<DiagnosticRecord> AnalyzeScriptBlockAst(ScriptBlockAst scrip
// Checks if this variableAst is part of the logged assignment
foreach (VariableExpressionAst varInAssignment in varsInAssignment)
{
inAssignment |= varInAssignment.Equals(varAst);
// Try casting to AssignmentStatementAst to be able to catch case where a variable is assigned more than once (https://github.com/PowerShell/PSScriptAnalyzer/issues/833)
var varInAssignmentAsStatementAst = varInAssignment.Parent as AssignmentStatementAst;
var varAstAsAssignmentStatementAst = varAst.Parent as AssignmentStatementAst;
if (varInAssignmentAsStatementAst != null && varAstAsAssignmentStatementAst != null)
{
inAssignment = varInAssignmentAsStatementAst.Left.Extent.Text.Equals(varAstAsAssignmentStatementAst.Left.Extent.Text, StringComparison.OrdinalIgnoreCase);
}
else
{
inAssignment = varInAssignment.Equals(varAst);
}
}

if (!inAssignment)
Expand Down
12 changes: 12 additions & 0 deletions Tests/Rules/UseDeclaredVarsMoreThanAssignments.tests.ps1
Expand Up @@ -49,6 +49,18 @@ function MyFunc2() {
Get-Count | `
Should Be 0
}

It "flags a variable that is defined twice but never used" {
Invoke-ScriptAnalyzer -ScriptDefinition '$myvar=1;$myvar=2' -IncludeRule $violationName | `
Get-Count | `
Should Be 1
}

It "does not flag a variable that is defined twice but gets assigned to another variable and flags the other variable instead" {
$results = Invoke-ScriptAnalyzer -ScriptDefinition '$myvar=1;$myvar=2;$mySecondvar=$myvar' -IncludeRule $violationName
$results | Get-Count | Should Be 1
$results[0].Extent | Should Be '$mySecondvar'
}
}

Context "When there are no violations" {
Expand Down