Skip to content

Commit 1e78842

Browse files
committed
Add check for builtin variables for GlobalVar rule
1 parent f6ba095 commit 1e78842

File tree

4 files changed

+27
-11
lines changed

4 files changed

+27
-11
lines changed

Engine/Helper.cs

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -494,6 +494,23 @@ public bool IsVariableGlobalOrEnvironment(VariableExpressionAst varAst, Ast ast)
494494
return VariableAnalysisDictionary[ast].IsGlobalOrEnvironment(varAst);
495495
}
496496

497+
498+
/// <summary>
499+
/// Checks whether a variable is a built-in variable.
500+
/// </summary>
501+
/// <param name="ast"></param>
502+
/// <returns></returns>
503+
public bool IsVariableGlobal(VariableExpressionAst varAst)
504+
{
505+
if (varAst.VariablePath.IsGlobal)
506+
{
507+
string varName = varAst.VariablePath.UserPath.Remove(varAst.VariablePath.UserPath.IndexOf("global:", StringComparison.OrdinalIgnoreCase), "global:".Length);
508+
return !SpecialVars.InitializedVariables.Contains(varName, StringComparer.OrdinalIgnoreCase);
509+
}
510+
return false;
511+
}
512+
513+
497514
/// <summary>
498515
/// Checks whether all the code path of ast returns.
499516
/// Runs InitializeVariableAnalysis before calling this method

Rules/AvoidGlobalVars.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ public IEnumerable<DiagnosticRecord> AnalyzeScript(Ast ast, string fileName)
4141
{
4242
foreach (VariableExpressionAst varAst in varAsts)
4343
{
44-
if (varAst.VariablePath.IsGlobal)
44+
if (Helper.Instance.IsVariableGlobal(varAst))
4545
{
4646
yield return
4747
new DiagnosticRecord(

Tests/Rules/AvoidGlobalOrUnitializedVars.ps1

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
1-
$Global:1 = "Globalization?"
1+
$Global:1 = "globalVar
2+
$Global:DebugPreference
3+
4+
25

36
function NotGlobal {
47
$localVars = "Localization?"

Tests/Rules/AvoidGlobalOrUnitializedVarsNoViolations.ps1

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
1-
function Test {
1+
$Global:DebugPreference
2+
3+
4+
function Test {
25
$initialized = "Initialized"
36
$noglobal = "local"
47
$env:ShouldNotRaiseError
@@ -31,18 +34,11 @@ $proc[0]
3134

3235
function Test-PreferenceVariable
3336
{
34-
Param(
35-
[switch]
36-
$a,
37-
38-
[System.Management.Automation.SwitchParameter]
39-
$b
40-
)
4137

4238
if (-not $PSBoundParameters.ContainsKey('Verbose')) {
4339
$VerbosePreference = $PSCmdlet.GetVariableValue('VerbosePreference') -as
4440
[System.Management.Automation.ActionPreference]
4541
}
4642

4743
$VerbosePreference
48-
}
44+
}

0 commit comments

Comments
 (0)