-
Notifications
You must be signed in to change notification settings - Fork 410
Add new InvalidMultiDotValue rule #2180
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
4
commits into
PowerShell:main
Choose a base branch
from
iRon7:#1698InvalidVersionConstruction
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
4 commits
Select commit
Hold shift + click to select a range
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,100 @@ | ||
| // 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; | ||
|
|
||
| #if !CORECLR | ||
| using System.ComponentModel.Composition; | ||
| #endif | ||
|
|
||
| namespace Microsoft.Windows.PowerShell.ScriptAnalyzer.BuiltinRules | ||
| { | ||
| #if !CORECLR | ||
| [Export(typeof(IScriptRule))] | ||
| #endif | ||
|
|
||
| /// <summary> | ||
| /// Rule that reports an error when an unquoted value contains multiple dots, | ||
| /// which is likely an attempt to construct a version number (e.g., 1.2.3) | ||
| /// that is not properly quoted and thus misinterpreted as a double with member access. | ||
| /// </summary> | ||
| public class InvalidMultiDotValue : IScriptRule | ||
| { | ||
| /// <summary> | ||
| /// Analyzes the PowerShell unquoted values that contain multiple dots. | ||
| /// </summary> | ||
| /// <param name="ast">The PowerShell Abstract Syntax Tree to analyze.</param> | ||
| /// <param name="fileName">The name of the file being analyzed (for diagnostic reporting).</param> | ||
| /// <returns>A collection of diagnostic records for each violation.</returns> | ||
| public IEnumerable<DiagnosticRecord> AnalyzeScript(Ast ast, string fileName) | ||
| { | ||
| if (ast == null) throw new ArgumentNullException(Strings.NullAstErrorMessage); | ||
|
|
||
| // Find all MemberExpressionAst nodes representing invalid unquoted multi-dot values | ||
| IEnumerable<Ast> invalidAsts = ast.FindAll(testAst => | ||
| // An expression with 3 or more dots is seen as a double with an additional property | ||
| testAst is MemberExpressionAst memberAst && | ||
| // The first two values are seen as a double | ||
| memberAst.Expression.StaticType == typeof(double) && | ||
| // the rest is seen as a member of type int or double | ||
| memberAst.Member is ConstantExpressionAst constantAst && | ||
| ( | ||
| constantAst.StaticType == typeof(int) || // e.g.: [Version]1.2.3 | ||
| constantAst.StaticType == typeof(double) // e.g.: [Version]1.2.3.4 | ||
| ), | ||
| true | ||
| ); | ||
|
|
||
| if (invalidAsts != null) { | ||
| var correctionDescription = Strings.InvalidMultiDotValueCorrectionDescription; | ||
| foreach (MemberExpressionAst invalidAst in invalidAsts) | ||
| { | ||
| var corrections = new List<CorrectionExtent> { | ||
| new CorrectionExtent( | ||
| invalidAst.Extent.StartLineNumber, | ||
| invalidAst.Extent.EndLineNumber, | ||
| invalidAst.Extent.StartColumnNumber, | ||
| invalidAst.Extent.EndColumnNumber, | ||
| "'" + invalidAst.Extent.Text + "'", | ||
| fileName, | ||
| correctionDescription | ||
| ) | ||
| }; | ||
| yield return new DiagnosticRecord( | ||
| string.Format( | ||
| CultureInfo.CurrentCulture, | ||
| Strings.InvalidMultiDotValueError, | ||
| invalidAst.Extent.Text | ||
| ), | ||
| invalidAst.Extent, | ||
| GetName(), | ||
| DiagnosticSeverity.Error, | ||
| fileName, | ||
| invalidAst.Extent.Text, | ||
| suggestedCorrections: corrections | ||
| ); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| public string GetCommonName() => Strings.InvalidMultiDotValueCommonName; | ||
|
|
||
| public string GetDescription() => Strings.InvalidMultiDotValueDescription; | ||
|
|
||
| public string GetName() => string.Format( | ||
| CultureInfo.CurrentCulture, | ||
| Strings.NameSpaceFormat, | ||
| GetSourceName(), | ||
| Strings.InvalidMultiDotValueName); | ||
|
|
||
| public RuleSeverity GetSeverity() => RuleSeverity.Error; | ||
|
|
||
| public string GetSourceName() => Strings.SourceName; | ||
|
|
||
| public SourceType GetSourceType() => 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
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,167 @@ | ||
| # Copyright (c) Microsoft Corporation. All rights reserved. | ||
| # Licensed under the MIT License. | ||
|
|
||
| [Diagnostics.CodeAnalysis.SuppressMessage('PSUseDeclaredVarsMoreThanAssignments', '', Justification = 'False positive')] | ||
| param() | ||
|
|
||
| BeforeAll { | ||
| $ruleName = "PSInvalidMultiDotValue" | ||
| $ruleMessage = "The unquoted '{0}' expression is not a valid syntax. Types with multiple dots need to be constructed from either a quoted string or individual components." | ||
| $correctionDescription = 'Quote the value that contains multiple dots' | ||
| } | ||
|
|
||
| Describe "InvalidMultiDotValue" { | ||
| Context "Violates" { | ||
| It "3 version components" { | ||
| $scriptDefinition = { $version = 1.2.3 }.ToString() | ||
| $violations = Invoke-ScriptAnalyzer -ScriptDefinition $scriptDefinition -IncludeRule @($ruleName) | ||
| $violations.Count | Should -Be 1 | ||
| $violations.Severity | Should -Be Error | ||
| $violations.Extent.Text | Should -Be '1.2.3' | ||
| $violations.Message | Should -Be ($ruleMessage -f '1.2.3') | ||
| $violations.RuleSuppressionID | Should -Be '1.2.3' | ||
| $violations.SuggestedCorrections.Text | Should -Be "'1.2.3'" | ||
| $violations.SuggestedCorrections.Description | Should -Be $correctionDescription | ||
| } | ||
|
|
||
| It "4 version components" { | ||
| $scriptDefinition = { $version = 1.2.3.4 }.ToString() | ||
| $violations = Invoke-ScriptAnalyzer -ScriptDefinition $scriptDefinition -IncludeRule @($ruleName) | ||
| $violations.Count | Should -Be 1 | ||
| $violations.Severity | Should -Be Error | ||
| $violations.Extent.Text | Should -Be '1.2.3.4' | ||
| $violations.Message | Should -Be ($ruleMessage -f '1.2.3.4') | ||
| $violations.RuleSuppressionID | Should -Be '1.2.3.4' | ||
| $violations.SuggestedCorrections.Text | Should -Be "'1.2.3.4'" | ||
| $violations.SuggestedCorrections.Description | Should -Be $correctionDescription | ||
| } | ||
|
|
||
|
|
||
| It "With class initializer" { | ||
| $scriptDefinition = { $version = [Version]1.2.3 }.ToString() | ||
| $violations = Invoke-ScriptAnalyzer -ScriptDefinition $scriptDefinition -IncludeRule @($ruleName) | ||
| $violations.Count | Should -Be 1 | ||
| $violations.Severity | Should -Be Error | ||
| $violations.Extent.Text | Should -Be '1.2.3' | ||
| $violations.Message | Should -Be ($ruleMessage -f '1.2.3') | ||
| $violations.RuleSuppressionID | Should -Be '1.2.3' | ||
| $violations.SuggestedCorrections.Text | Should -Be "'1.2.3'" | ||
| $violations.SuggestedCorrections.Description | Should -Be $correctionDescription | ||
| } | ||
|
|
||
| It "As parameter" { | ||
| $scriptDefinition = { | ||
| param( | ||
| [Version]$version = 1.2.3 | ||
| ) | ||
| Write-Verbose $version | ||
| }.ToString() | ||
| $violations = Invoke-ScriptAnalyzer -ScriptDefinition $scriptDefinition -IncludeRule @($ruleName) | ||
| $violations.Count | Should -Be 1 | ||
| $violations.Severity | Should -Be Error | ||
| $violations.Extent.Text | Should -Be '1.2.3' | ||
| $violations.Message | Should -Be ($ruleMessage -f '1.2.3') | ||
| $violations.RuleSuppressionID | Should -Be '1.2.3' | ||
| $violations.SuggestedCorrections.Text | Should -Be "'1.2.3'" | ||
| $violations.SuggestedCorrections.Description | Should -Be $correctionDescription | ||
| } | ||
|
|
||
| # Even an IP address is apparently expect below. | ||
| # The violation message and description presume a version | ||
| # is expected because this is the more commonly used type. | ||
| It "IP Address" { | ||
| $scriptDefinition = { $IP = [System.Net.IPAddress]127.0.0.1 }.ToString() | ||
| $violations = Invoke-ScriptAnalyzer -ScriptDefinition $scriptDefinition -IncludeRule @($ruleName) | ||
| $violations.Count | Should -Be 1 | ||
| $violations.Severity | Should -Be Error | ||
| $violations.Extent.Text | Should -Be '127.0.0.1' | ||
| $violations.Message | Should -Be ($ruleMessage -f '127.0.0.1') | ||
| $violations.RuleSuppressionID | Should -Be '127.0.0.1' | ||
| $violations.SuggestedCorrections.Text | Should -Be "'127.0.0.1'" | ||
| $violations.SuggestedCorrections.Description | Should -Be $correctionDescription | ||
| } | ||
| } | ||
|
|
||
| Context "Compliant" { | ||
| It "From string" { | ||
| $scriptDefinition = { $Version = [Version]'1.2.3' }.ToString() | ||
| $violations = Invoke-ScriptAnalyzer -ScriptDefinition $scriptDefinition -IncludeRule @($ruleName) | ||
| $violations | Should -BeNullOrEmpty | ||
| } | ||
|
|
||
| It "From version components" { | ||
| $scriptDefinition = { $Version = [Version]::new(1, 2, 3, 4) }.ToString() | ||
| $violations = Invoke-ScriptAnalyzer -ScriptDefinition $scriptDefinition -IncludeRule @($ruleName) | ||
| $violations | Should -BeNullOrEmpty | ||
| } | ||
|
|
||
| It "From (bare) double" { | ||
| $scriptDefinition = { $Version = [Version]1.2 }.ToString() | ||
| $violations = Invoke-ScriptAnalyzer -ScriptDefinition $scriptDefinition -IncludeRule @($ruleName) | ||
| $violations | Should -BeNullOrEmpty | ||
| } | ||
|
|
||
|
|
||
| It "Dot notation" { #PowerShell:27356 | ||
| $scriptDefinition = { | ||
| $1.2.3.4 | ||
| $intKeys = @{ 1 = @{ 2 = @{ 3 = @{ 4 = 'test' } } } } | ||
| $intKeys.1.2.3.4 | ||
| }.ToString() | ||
| $violations = Invoke-ScriptAnalyzer -ScriptDefinition $scriptDefinition -IncludeRule @($ruleName) | ||
| $violations | Should -BeNullOrEmpty | ||
| } | ||
| } | ||
|
|
||
| Context "Suppressed" { | ||
| It "All" { | ||
| $scriptDefinition = { | ||
| [Diagnostics.CodeAnalysis.SuppressMessage('PSInvalidMultiDotValue', '', Justification = 'Test')] | ||
| param() | ||
| $version = 1.2.3 | ||
| $IP = [System.Net.IPAddress]127.0.0.1 | ||
| }.ToString() | ||
| $violations = Invoke-ScriptAnalyzer -ScriptDefinition $scriptDefinition -IncludeRule @($ruleName) | ||
| $violations | Should -BeNullOrEmpty | ||
| } | ||
|
|
||
| It "1.2.3" { | ||
| $scriptDefinition = { | ||
| [Diagnostics.CodeAnalysis.SuppressMessage('PSInvalidMultiDotValue', '1.2.3', Justification = 'Test')] | ||
| param() | ||
| $version = 1.2.3 | ||
| }.ToString() | ||
| $violations = Invoke-ScriptAnalyzer -ScriptDefinition $scriptDefinition -IncludeRule @($ruleName) | ||
| $violations | Should -BeNullOrEmpty | ||
| } | ||
|
|
||
| It "127.0.0.1" { | ||
| $scriptDefinition = { | ||
| [Diagnostics.CodeAnalysis.SuppressMessage('PSInvalidMultiDotValue', '127.0.0.1', Justification = 'Test')] | ||
| param() | ||
| $IP = [System.Net.IPAddress]127.0.0.1 | ||
| }.ToString() | ||
| $violations = Invoke-ScriptAnalyzer -ScriptDefinition $scriptDefinition -IncludeRule @($ruleName) | ||
| $violations | Should -BeNullOrEmpty | ||
| } | ||
| } | ||
|
|
||
| Context "Fixing" { | ||
|
|
||
| BeforeAll { # See request: #1938 | ||
| $tempFile = Join-Path $TestDrive 'TestScript.ps1' | ||
| } | ||
|
|
||
| It "Version" { | ||
| Set-Content -LiteralPath $tempFile -Value {$version = 1.2.3}.ToString() -NoNewLine | ||
| $violations = Invoke-ScriptAnalyzer -Path $tempFile -fix | ||
| Get-Content -LiteralPath $tempFile -Raw | Should -Be {$version = '1.2.3'}.ToString() | ||
| } | ||
|
|
||
| It "IP Address" { | ||
| Set-Content -LiteralPath $tempFile -Value {$IP = [System.Net.IPAddress]127.0.0.1}.ToString() -NoNewLine | ||
| $violations = Invoke-ScriptAnalyzer -Path $tempFile -fix | ||
| Get-Content -LiteralPath $tempFile -Raw | Should -Be {$IP = [System.Net.IPAddress]'127.0.0.1'}.ToString() | ||
| } | ||
| } | ||
| } |
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,45 @@ | ||
| --- | ||
| description: Invalid unquoted multi-dot value construction | ||
| ms.date: 04/24/2024 | ||
| ms.topic: reference | ||
| title: InvalidMultiDotValue | ||
| --- | ||
| # InvalidMultiDotValue | ||
|
|
||
| **Severity Level: Error** | ||
|
|
||
| ## Description | ||
|
|
||
| PowerShell does not support an implicit value with multiple dots. | ||
| Any *unquoted* value with 2 or more dots will not be treated as any special type (like a `version` or `IPAddress`) | ||
| but result in `$null`. These objects need to be constructed from either a quoted string (e.g. `[Version]'1.2.3'`) | ||
| or their individual components (e.g. `[Version]::new(1, 2, 3)`). | ||
|
|
||
|
|
||
| ## Example | ||
|
|
||
| ### Wrong | ||
|
|
||
| ```powershell | ||
| $version = 1.2.3 | ||
| ``` | ||
|
|
||
| or even: | ||
|
|
||
| ```powershell | ||
| $IP = [System.Net.IPAddress]127.0.0.1 | ||
| ``` | ||
|
|
||
| Where both examples will result in `$null` instead of any specific object. | ||
|
|
||
| ### Correct | ||
|
|
||
| ```powershell | ||
| $version = [Version]'1.2.3' | ||
| # or: | ||
| $version = [Version]::new(1, 2, 3) | ||
| ``` | ||
|
|
||
| ```powershell | ||
| $IP = [System.Net.IPAddress]'127.0.0.1' | ||
| ``` |
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
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.