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

PSReviewUnusedParameter: Add CommandsToTraverse option #1921

Merged
merged 5 commits into from
Feb 13, 2024
Merged
Changes from 1 commit
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
91 changes: 87 additions & 4 deletions Rules/ReviewUnusedParameter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,60 @@ namespace Microsoft.Windows.PowerShell.ScriptAnalyzer.BuiltinRules
#endif
public class ReviewUnusedParameter : IScriptRule
{
private readonly string TraverseArgName = "traverseList";
bergmeister marked this conversation as resolved.
Show resolved Hide resolved
public List<string> TraverseCommands { get; private set; }

/// <summary>
/// Configure the rule.
///
/// Sets the list of commands to traverse of this rule
/// </summary>
private void SetProperties()
{
TraverseCommands = new List<string>() { "Where-Object", "ForEach-Object" };

Dictionary<string, object> ruleArgs = Helper.Instance.GetRuleArguments(GetName());
if (ruleArgs == null)
{
return;
}

if (!ruleArgs.TryGetValue(TraverseArgName, out object obj))
{
return;
}
IEnumerable<string> commands = obj as IEnumerable<string>;
if (commands == null)
{
// try with enumerable objects
var enumerableObjs = obj as IEnumerable<object>;
if (enumerableObjs == null)
{
return;
}
foreach (var x in enumerableObjs)
{
var y = x as string;
if (y == null)
{
return;
}
else
{
TraverseCommands.Add(y);
}
}
}
else
{
TraverseCommands.AddRange(commands);
}
}

public IEnumerable<DiagnosticRecord> AnalyzeScript(Ast ast, string fileName)
{
SetProperties();

if (ast == null)
{
throw new ArgumentNullException(Strings.NullAstErrorMessage);
Expand All @@ -46,10 +98,7 @@ public IEnumerable<DiagnosticRecord> AnalyzeScript(Ast ast, string fileName)
IEnumerable<Ast> parameterAsts = scriptBlockAst.FindAll(oneAst => oneAst is ParameterAst, false);

// list all variables
IDictionary<string, int> variableCount = scriptBlockAst.FindAll(oneAst => oneAst is VariableExpressionAst, false)
.Select(variableExpressionAst => ((VariableExpressionAst)variableExpressionAst).VariablePath.UserPath)
.GroupBy(variableName => variableName, StringComparer.OrdinalIgnoreCase)
.ToDictionary(variableName => variableName.Key, variableName => variableName.Count(), StringComparer.OrdinalIgnoreCase);
IDictionary<string, int> variableCount = GetVariableCount(scriptBlockAst);

foreach (ParameterAst parameterAst in parameterAsts)
{
Expand Down Expand Up @@ -164,5 +213,39 @@ public string GetSourceName()
{
return string.Format(CultureInfo.CurrentCulture, Strings.SourceName);
}

/// <summary>
/// Returns a dictionary including all variables in the scriptblock and their count
/// </summary>
/// <param name="ast">The scriptblock ast to scan</param>
/// <param name="data">Previously generated data. New findings are added to any existing dictionary if present</param>
/// <returns>a dictionary including all variables in the scriptblock and their count</returns>
IDictionary<string, int> GetVariableCount(ScriptBlockAst ast, Dictionary<string, int> data = null)
{
Dictionary<string, int> content = data;
if (null == data)
content = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
IDictionary<string, int> result = ast.FindAll(oneAst => oneAst is VariableExpressionAst, false)
.Select(variableExpressionAst => ((VariableExpressionAst)variableExpressionAst).VariablePath.UserPath)
.GroupBy(variableName => variableName, StringComparer.OrdinalIgnoreCase)
.ToDictionary(variableName => variableName.Key, variableName => variableName.Count(), StringComparer.OrdinalIgnoreCase);

foreach (string key in result.Keys)
{
if (content.ContainsKey(key))
content[key] = content[key] + result[key];
else
content[key] = result[key];
}

IEnumerable<Ast> foundScriptBlocks = ast.FindAll(oneAst => oneAst is ScriptBlockExpressionAst, false)
.Where(oneAst => oneAst?.Parent is CommandAst && ((CommandAst)oneAst.Parent).CommandElements[0] is StringConstantExpressionAst && TraverseCommands.Contains(((StringConstantExpressionAst)((CommandAst)oneAst.Parent).CommandElements[0]).Value))
.Select(oneAst => ((ScriptBlockExpressionAst)oneAst).ScriptBlock);
foreach (Ast astItem in foundScriptBlocks)
if (astItem != ast)
GetVariableCount((ScriptBlockAst)astItem, content);

return content;
}
}
}