Skip to content

Commit 7556149

Browse files
author
Kapil Borle
committed
Update AvoidUsingComputerNameHardcoded implementation
1 parent a329d98 commit 7556149

File tree

1 file changed

+29
-18
lines changed

1 file changed

+29
-18
lines changed

Rules/AvoidUsingComputerNameHardcoded.cs

Lines changed: 29 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,14 @@ namespace Microsoft.Windows.PowerShell.ScriptAnalyzer.BuiltinRules
3030
#endif
3131
public class AvoidUsingComputerNameHardcoded : AvoidParameterGeneric
3232
{
33+
private readonly string[] localhostRepresentations = new string[]
34+
{
35+
"localhost",
36+
".",
37+
"::1",
38+
"127.0.0.1"
39+
};
40+
3341
/// <summary>
3442
/// Condition on the cmdlet that must be satisfied for the error to be raised
3543
/// </summary>
@@ -54,37 +62,40 @@ public override bool ParameterCondition(CommandAst CmdAst, CommandElementAst CeA
5462

5563
if (String.Equals(cmdParamAst.ParameterName, "computername", StringComparison.OrdinalIgnoreCase))
5664
{
57-
List<string> localhostRepresentations = new List<string> { "localhost", ".", "::1", "127.0.0.1" };
58-
Ast computerNameArgument = GetComputerNameArg(CmdAst, cmdParamAst.Extent.StartOffset);
59-
60-
if (null != computerNameArgument)
65+
Ast computerNameArgument = cmdParamAst.Argument;
66+
if (computerNameArgument == null)
6167
{
62-
var constExprAst = computerNameArgument as ConstantExpressionAst;
63-
if (null != constExprAst)
68+
computerNameArgument = GetComputerNameArg(CmdAst, cmdParamAst.Extent.StartOffset);
69+
if (computerNameArgument == null)
6470
{
65-
var constExprVal = constExprAst.Value as string;
66-
if (null != constExprVal)
67-
{
68-
return !localhostRepresentations.Contains<string>(
69-
constExprVal,
70-
StringComparer.OrdinalIgnoreCase);
71-
}
72-
71+
return false;
7372
}
74-
75-
return false;
7673
}
7774

78-
if (null != cmdParamAst.Argument && !localhostRepresentations.Contains(cmdParamAst.Argument.ToString().Replace("\"", "").Replace("'", "").ToLower()))
75+
var constExprAst = computerNameArgument as ConstantExpressionAst;
76+
if (constExprAst != null)
7977
{
80-
return cmdParamAst.Argument is ConstantExpressionAst;
78+
return !IsLocalhost(constExprAst);
8179
}
8280
}
8381
}
8482

8583
return false;
8684
}
8785

86+
private bool IsLocalhost(ConstantExpressionAst constExprAst)
87+
{
88+
var constExprVal = constExprAst.Value as string;
89+
if (constExprVal != null)
90+
{
91+
return localhostRepresentations.Contains<string>(
92+
constExprVal,
93+
StringComparer.OrdinalIgnoreCase);
94+
}
95+
96+
return false;
97+
}
98+
8899
private Ast GetComputerNameArg(CommandAst CmdAst, int StartIndex)
89100
{
90101
int small = int.MaxValue;

0 commit comments

Comments
 (0)