-
Notifications
You must be signed in to change notification settings - Fork 415
Add new AvoidUsingNewObject rule #2186
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
Open
iRon7
wants to merge
7
commits into
PowerShell:main
Choose a base branch
from
iRon7:#2046-AvoidUsingNewObject
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
e14adb2
Add new AvoidUsingNewObject rule to flag usage of New-Object cmdlet a…
iRon7 0aad726
Implemented feedback from CoPilot
iRon7 d9e0e6b
Implemented more CoPilot suggestions
iRon7 e061335
Resolved minor the grammar
iRon7 12b4bb1
Merge branch 'main' into #2046-AvoidUsingNewObject
iRon7 b9fd316
Synced my fork and resolved "Cannot determine line endings" in PS5
iRon7 6b2ca61
Merge branch 'main' into #2046-AvoidUsingNewObject
iRon7 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,247 @@ | ||
| // Copyright (c) Microsoft Corporation. All rights reserved. | ||
| // Licensed under the MIT License. | ||
|
|
||
| using Microsoft.Windows.PowerShell.ScriptAnalyzer.Generic; | ||
| using System; | ||
| using System.Collections.Generic; | ||
| using System.Globalization; | ||
| using System.Management.Automation.Language; | ||
| using System.Linq; | ||
|
|
||
| #if !CORECLR | ||
| using System.ComponentModel.Composition; | ||
| #endif | ||
|
|
||
| namespace Microsoft.Windows.PowerShell.ScriptAnalyzer.BuiltinRules | ||
| { | ||
| #if !CORECLR | ||
| [Export(typeof(IScriptRule))] | ||
| #endif | ||
|
|
||
| /// <summary> | ||
| /// Rule that reports a warning when the New-Object cmdlet is used in a script. | ||
| /// The rule implements a correction that suggests using type-casting or type constructor. | ||
| /// | ||
| /// Note: | ||
| /// In most cases if there isn't an automatic correction available, | ||
| /// the rule won't report any violation either. | ||
| /// This is because if there isn't an automatic correction available, it generally means | ||
| /// that there isn't a simple type-casting or type constructor that can be used that would | ||
| /// be more efficient or has a better syntax than using New-Object. | ||
| /// In other words, if the common `-Verbose` parameter is used, or both the parameters | ||
| /// `-ArgumentList` and `-Property` are used, there won't be a simple type initializer | ||
| /// available and the rule won't report any violation for the `New-Object` cmdlet. | ||
| /// | ||
| /// Nevertheless, there are still some cases where the `New-Object` cmdlet might be | ||
| /// replaceable with a type initializer that would be more efficient or has a better syntax, | ||
| /// but an automatic correction can't be provided. | ||
| /// For example if the `-ArgumentList` parameter is used with a variable, | ||
| /// the rule will report a violation, but won't be able to provide a correction, | ||
| /// as it's not possible to determine from the AST alone whether the variable contains a | ||
| /// single value that can be used in a type initializer, | ||
| /// or if it contains multiple values that would require splatting. | ||
| /// </summary> | ||
| public class AvoidUsingNewObject : ConfigurableRule | ||
| { | ||
|
|
||
| /// <summary> | ||
| /// Construct an object of AvoidUsingNewObject type. | ||
| /// </summary> | ||
| public AvoidUsingNewObject() { | ||
| Enable = false; | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Analyzes the given ast to find the [violation] | ||
| /// </summary> | ||
| /// <param name="ast">AST to be analyzed. This should be non-null</param> | ||
| /// <param name="fileName">Name of file that corresponds to the input AST.</param> | ||
| /// <returns>An enumerable type containing the violations</returns> | ||
| public override IEnumerable<DiagnosticRecord> AnalyzeScript(Ast ast, string fileName) | ||
| { | ||
| if (ast == null) throw new ArgumentNullException(Strings.NullAstErrorMessage); | ||
|
bergmeister marked this conversation as resolved.
|
||
|
|
||
| IEnumerable<CommandAst> newObjectAsts = ast.FindAll(testAst => | ||
| testAst is CommandAst cmdAst && | ||
| (cmdAst.GetCommandName() as string) is string commandName && | ||
| commandName.Equals("New-Object", StringComparison.OrdinalIgnoreCase), | ||
| true | ||
| ).Cast<CommandAst>(); | ||
|
bergmeister marked this conversation as resolved.
|
||
|
|
||
| foreach (CommandAst cmdAst in newObjectAsts) | ||
| { | ||
| // Use StaticParameterBinder to reliably get parameter values | ||
| var bindingResult = StaticParameterBinder.BindCommand(cmdAst, true); | ||
|
|
||
| // Check for `-TypeName` and either a `-ArgumentList` or `-Property`. | ||
| // But not both, as that would mean there isn't a simple | ||
| // type initializer available as a replacement. | ||
| if ( | ||
| bindingResult.BoundParameters.Count <= 2 && | ||
| bindingResult.BoundParameters.TryGetValue("TypeName", out ParameterBindingResult asTypeName) && | ||
| asTypeName.ConstantValue is string typeName | ||
| ) { | ||
|
iRon7 marked this conversation as resolved.
|
||
| Boolean isProperty = bindingResult.BoundParameters.TryGetValue("Property", out ParameterBindingResult boundResult); | ||
| if (!isProperty) | ||
| { | ||
| Boolean isArgument = bindingResult.BoundParameters.TryGetValue("ArgumentList", out ParameterBindingResult argumentResult); | ||
| if (isArgument) { boundResult = argumentResult; } | ||
| } | ||
|
iRon7 marked this conversation as resolved.
|
||
|
|
||
| string correction = null; | ||
| if (boundResult == null) | ||
| { | ||
| // No `-Property` or `-ArgumentList` parameter was used, so we suggest a parameterless constructor call. | ||
| correction = "[" + typeName + "]::new()"; | ||
| } | ||
| else if (isProperty) | ||
| { | ||
| correction = "[" + typeName + "]" + boundResult.Value.Extent.Text; | ||
| } | ||
| else if (boundResult.ConstantValue != null) | ||
| { | ||
| string valueText = boundResult.Value.Extent.Text; | ||
| if ( | ||
| boundResult.Value is StringConstantExpressionAst stringConstant && | ||
| stringConstant.StringConstantType == StringConstantType.BareWord | ||
| ) | ||
| { | ||
| valueText = '"' + valueText.Replace("\"", string.Empty) + '"'; // Test""123 --> "Test123" | ||
| } | ||
| correction = "[" + typeName + "]" + valueText; | ||
| } | ||
|
Comment on lines
+101
to
+112
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I think I got this right, if the Monday, January 1, 0001 12:00:00 AM |
||
| else if ( | ||
| boundResult.Value is ParenExpressionAst parenExpressionAst && | ||
| !parenExpressionAst.Pipeline.Extent.Text.StartsWith(",") | ||
| ) | ||
|
Copilot marked this conversation as resolved.
|
||
| { | ||
| correction = "[" +typeName + "]::new" + parenExpressionAst.Extent.Text; | ||
| } | ||
| else if ( | ||
| boundResult.Value is ArrayExpressionAst arrayExpressionAst && | ||
| !arrayExpressionAst.SubExpression.Extent.Text.StartsWith(",") | ||
| ) | ||
| { | ||
| correction = "[" + typeName + "]::new(" + arrayExpressionAst.SubExpression.Extent.Text + ")"; | ||
| } | ||
| else if ( | ||
| boundResult.Value is SubExpressionAst subExpressionAst && | ||
| !subExpressionAst.SubExpression.Extent.Text.StartsWith(",") | ||
| ) | ||
| { | ||
| correction = "[" + typeName + "]::new(" + subExpressionAst.SubExpression.Extent.Text + ")"; | ||
| } | ||
| else if (boundResult.Value is VariableExpressionAst) | ||
| { | ||
| // correction == $null | ||
|
|
||
| // The correction is inconclusive, as we can't be sure if the variable contains | ||
| // a single value that can be used in a type initializer, | ||
| // or if it contains multiple values that would require splatting, | ||
| // which can't be automatically determined from the AST. | ||
| } | ||
| else | ||
| { | ||
| correction = "[" + typeName + "]::new(" + boundResult.Value.Extent.Text + ")"; | ||
| } | ||
|
|
||
| DiagnosticRecord diagnosticRecord = new DiagnosticRecord( | ||
| string.Format( | ||
| CultureInfo.CurrentCulture, | ||
| Strings.AvoidUsingNewObjectError, | ||
| typeName | ||
| ), | ||
| cmdAst.Extent, | ||
| GetName(), | ||
| DiagnosticSeverity.Warning, | ||
| fileName, | ||
| typeName | ||
| ); | ||
|
|
||
| if (correction != null) | ||
| { | ||
| diagnosticRecord.SuggestedCorrections = new List<CorrectionExtent> { | ||
| new CorrectionExtent( | ||
| cmdAst.Extent.StartLineNumber, | ||
| cmdAst.Extent.EndLineNumber, | ||
| cmdAst.Extent.StartColumnNumber, | ||
| cmdAst.Extent.EndColumnNumber, | ||
| correction, | ||
| fileName, | ||
| string.Format( | ||
| CultureInfo.CurrentCulture, | ||
| Strings.AvoidUsingNewObjectCorrectionDescription, | ||
| typeName | ||
| ) | ||
| ) | ||
| }; | ||
| } | ||
|
|
||
| yield return diagnosticRecord; | ||
| } | ||
| } | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Retrieves the common name of this rule. | ||
| /// </summary> | ||
| public override string GetCommonName() | ||
| { | ||
| return string.Format(CultureInfo.CurrentCulture, Strings.AvoidUsingNewObjectCommonName); | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Retrieves the description of this rule. | ||
| /// </summary> | ||
| public override string GetDescription() | ||
| { | ||
| return string.Format(CultureInfo.CurrentCulture, Strings.AvoidUsingNewObjectDescription); | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Retrieves the name of this rule. | ||
| /// </summary> | ||
| public override string GetName() | ||
| { | ||
| return string.Format( | ||
| CultureInfo.CurrentCulture, | ||
| Strings.NameSpaceFormat, | ||
| GetSourceName(), | ||
| Strings.AvoidUsingNewObjectName); | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Retrieves the severity of the rule: error, warning or information. | ||
| /// </summary> | ||
| public override RuleSeverity GetSeverity() | ||
| { | ||
| return RuleSeverity.Warning; | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Gets the severity of the returned diagnostic record: error, warning, or information. | ||
| /// </summary> | ||
| /// <returns></returns> | ||
| public DiagnosticSeverity GetDiagnosticSeverity() | ||
| { | ||
| return DiagnosticSeverity.Warning; | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Retrieves the name of the module/assembly the rule is from. | ||
| /// </summary> | ||
| public override string GetSourceName() | ||
| { | ||
| return string.Format(CultureInfo.CurrentCulture, Strings.SourceName); | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Retrieves the type of the rule, Builtin, Managed or Module. | ||
| /// </summary> | ||
| public override SourceType GetSourceType() | ||
| { | ||
| return SourceType.Builtin; | ||
| } | ||
| } | ||
| } | ||
|
|
||
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
Oops, something went wrong.
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.