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

OSOE-580: Custom analyzer rule for parameter and variable name styling #42

Merged
merged 63 commits into from
Jun 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
63 commits
Select commit Hold shift + click to select a range
449d092
New cmdlet Measure-VariableNameStyling can determine whether paramete…
BenedekFarkas Jun 12, 2024
eccc851
Updating Measure-VariableNameStyling with checks on variables against…
BenedekFarkas Jun 12, 2024
79814fb
Renaming cmdlet to Measure-VariableNameCasing
BenedekFarkas Jun 12, 2024
c5c1e1b
Fixing that automatic variables in a Param block shouldn't be treated…
BenedekFarkas Jun 12, 2024
9618f9e
Minor improvement in Measure-VariableNameCasing for files with multip…
BenedekFarkas Jun 12, 2024
f106d3b
Merge branch 'dev' into issue/OSOE-580
BenedekFarkas Jun 12, 2024
bb8ebaa
Updating rule IDs
BenedekFarkas Jun 12, 2024
5007d4a
Checking out the issue branch in static-code-analysis
BenedekFarkas Jun 12, 2024
56110be
Really using the issue branch version of PS Analysis
BenedekFarkas Jun 12, 2024
2305938
Fixing PSUseParameterNameDeclaredCasing in Measure-VariableNameCasing
BenedekFarkas Jun 12, 2024
8d21496
Updating Measure-VariableNameCasing to handle inline parameter lists too
BenedekFarkas Jun 13, 2024
221617e
Looking for variable tokens inside the whole file or function body
BenedekFarkas Jun 13, 2024
c1e9788
Fixing that finding an automatic variable should prevent processing o…
BenedekFarkas Jun 13, 2024
59864df
Fixing that parenthesis depth should take the AtParen and DollarParen…
BenedekFarkas Jun 13, 2024
5ed2569
Displaying the $ character in analyzer messages
BenedekFarkas Jun 13, 2024
a3d913e
Skipping path-like expressions, such as $Env:SOMETHING
BenedekFarkas Jun 13, 2024
162c723
Completing the list of automatic variables
BenedekFarkas Jun 13, 2024
4288b10
Adding/updating documentation
BenedekFarkas Jun 14, 2024
850fbee
Upgrading projects to net8.0 target framework
BenedekFarkas Jun 14, 2024
4bd0da5
Updating Violate-Analyzers to test warnings in Measure-VariableNameCa…
BenedekFarkas Jun 14, 2024
a59a12d
Updating test solution to use the beta release
BenedekFarkas Jun 14, 2024
dceb258
Fixing typo
BenedekFarkas Jun 14, 2024
6cdf214
Refactoring Measure-VariableNameCasing to work with the Abstract Synt…
BenedekFarkas Jun 20, 2024
b416050
A bit of code styling
BenedekFarkas Jun 20, 2024
7e73c10
Updating AstFunctions with code styling and mandatory attribute for p…
BenedekFarkas Jun 21, 2024
2967ef6
Updating comments, fixing that finding certain violations should cont…
BenedekFarkas Jun 21, 2024
22f00e0
A bit of refactoring from ForEach-Object to foreach, to rely less on …
BenedekFarkas Jun 21, 2024
6fb22a4
Fixing that Measure-VariableNameCasing should only care about the who…
BenedekFarkas Jun 21, 2024
86c14f4
Adding useful instructions to the description
BenedekFarkas Jun 21, 2024
8b7bdb6
Fixing the message of PSUseParameterNameDeclaredCasing
BenedekFarkas Jun 21, 2024
f0824e6
Fixing that parameters in the root script should be validated and add…
BenedekFarkas Jun 21, 2024
f0db141
Simplifying the ctor usage of CorrectionExtent in Measure-AutomaticVa…
BenedekFarkas Jun 21, 2024
fcc0a22
Fix PSUseBOMForUnicodeEncodedFile in Measure-VariableNameCasing
BenedekFarkas Jun 21, 2024
d87a3d3
Fix PSUseParameterNameDeclaredCasing in Measure-VariableNameCasing
BenedekFarkas Jun 21, 2024
ff3aded
Fixing that splatted variables shouldn't raise a false positive PSUse…
BenedekFarkas Jun 21, 2024
53b078d
Removing braces-enclosed variable usage from Invoke-Analyzer
BenedekFarkas Jun 21, 2024
ab7be26
Updating anonymous function parameters to use lowercase first charact…
BenedekFarkas Jun 21, 2024
64a05a0
Fixing that static-code-analysis-this-repo should use the issue branc…
BenedekFarkas Jun 21, 2024
487e4c0
Adding support to handle variable names surrounded by braces
BenedekFarkas Jun 21, 2024
45d7cb3
Dropping support for variable expressions enclosed in braces for now,…
BenedekFarkas Jun 21, 2024
6e10a7b
Updating AstFunctions not to trip spell checking
BenedekFarkas Jun 21, 2024
77b5527
Updating warning messages and expected code analysis errors
BenedekFarkas Jun 25, 2024
3b48ccd
Fixing the detection of path-like expressions
BenedekFarkas Jun 25, 2024
84985f9
Updating comments and formatting
BenedekFarkas Jun 25, 2024
35a02f5
Adding support for braced variables when checking against automatic v…
BenedekFarkas Jun 25, 2024
c431133
Standardizing correction and warning messages
BenedekFarkas Jun 25, 2024
c5f94b7
Adding PSAvoidUsingUnnecessaryBracesInVariableNames warning
BenedekFarkas Jun 25, 2024
2655b3f
Updating description
BenedekFarkas Jun 25, 2024
395a51f
Adding separate parameter to Violate-Analyzers that raises PSAvoidUsi…
BenedekFarkas Jun 25, 2024
7aaa632
Renaming analyzer module to Measure-VariableNameFormat
BenedekFarkas Jun 25, 2024
6c7be57
Restoring the expected list of analyzer warnings for the NuGet packag…
BenedekFarkas Jun 25, 2024
b6f130b
Re-adding the expected warnings for the NuGet pacakge
BenedekFarkas Jun 25, 2024
fa6bdcb
Skip scoped variables and path-like expressions, regardless of braces…
BenedekFarkas Jun 25, 2024
73f16b9
Disabling test-analysis-failure on the NuGet solution for now
BenedekFarkas Jun 25, 2024
0421cc4
Updating NuGet package version and the list of expected warnings
BenedekFarkas Jun 25, 2024
89c06c5
Using singular nouns in AstFunctions
BenedekFarkas Jun 26, 2024
1b31108
Apply suggestions to comments from code review
BenedekFarkas Jun 26, 2024
dec5511
Removing trailing whitespace
BenedekFarkas Jun 26, 2024
53929a8
Fixing that Join-Path parameters shouldn't use slahes for the sake of…
BenedekFarkas Jun 26, 2024
e2493c3
Adding information message when a scoped variable or path-like expres…
BenedekFarkas Jun 26, 2024
291854b
Updating comment about the root index
BenedekFarkas Jun 26, 2024
0e2685f
Apply suggestions from code review
BenedekFarkas Jun 26, 2024
6f35b74
Updating NuGet package version
BenedekFarkas Jun 26, 2024
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
2 changes: 1 addition & 1 deletion .github/workflows/static-code-analysis-this-repo.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ on:
jobs:
powershell-static-code-analysis:
name: PowerShell Static Code Analysis
uses: Lombiq/PowerShell-Analyzers/.github/workflows/static-code-analysis.yml@dev
uses: Lombiq/PowerShell-Analyzers/.github/workflows/static-code-analysis.yml@issue/OSOE-580
with:
# Making sure that analysis runs through both PowerShell editions regardless of the default configuration of the
# workflow and the underlying action to ensure backwards-compatibility.
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/static-code-analysis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ jobs:
token: ${{ secrets.CHECKOUT_TOKEN }}

- name: PowerShell Static Code Analysis
uses: Lombiq/PowerShell-Analyzers/.github/actions/static-code-analysis@dev
uses: Lombiq/PowerShell-Analyzers/.github/actions/static-code-analysis@issue/OSOE-580
with:
run-windows-powershell: ${{ inputs.run-windows-powershell }}
run-powershell-core: ${{ inputs.run-powershell-core }}
Expand Down
10 changes: 10 additions & 0 deletions .github/workflows/test-analysis-failure.yml
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,15 @@ jobs:
PSAvoidUsingDoubleQuotesForConstantString: Use single quotes when a string is constant.
PSAvoidUsingEmptyCatchBlock: Empty catch block is used.
PSAvoidUsingLineContinuation: Using backtick (line continuation) makes the code harder to read and maintain.
PSAvoidUsingUnnecessaryBracesInVariableNames: Variable names should not use unnecessary braces
PSAvoidUsingWriteHost: File 'Violate-Analyzers.ps1' uses Write-Host.
PSPlaceOpenBrace: Open brace is not on a new line.
PSUseApprovedVerbs: The cmdlet 'Violate-Analyzers' uses an unapproved verb.
PSUseConsistentIndentation: Indentation not consistent
PSUseCorrectAutomaticVariableNames: Automatic variables should be used exactly as they are documented
PSUseCorrectParameterNameCasing: Parameter names should start with an uppercase letter
PSUseCorrectVariableNameCasing: Variable names should start with a lowercase letter
PSUseParametersAsDeclared: Parameters should be used with exactly as they were declared
PSUseSingularNouns: The cmdlet 'Violate-Analyzers' uses a plural noun.

call-test-analysis-failure-local:
Expand All @@ -44,8 +49,13 @@ jobs:
PSAvoidUsingDoubleQuotesForConstantString: Use single quotes when a string is constant.
PSAvoidUsingEmptyCatchBlock: Empty catch block is used.
PSAvoidUsingLineContinuation: Using backtick (line continuation) makes the code harder to read and maintain.
PSAvoidUsingUnnecessaryBracesInVariableNames: Variable names should not use unnecessary braces
PSAvoidUsingWriteHost: File 'Violate-Analyzers.ps1' uses Write-Host.
PSPlaceOpenBrace: Open brace is not on a new line.
PSUseApprovedVerbs: The cmdlet 'Violate-Analyzers' uses an unapproved verb.
PSUseConsistentIndentation: Indentation not consistent
PSUseCorrectAutomaticVariableNames: Automatic variables should be used exactly as they are documented
PSUseCorrectParameterNameCasing: Parameter names should start with an uppercase letter
PSUseCorrectVariableNameCasing: Variable names should start with a lowercase letter
PSUseParametersAsDeclared: Parameters should be used with exactly as they were declared
PSUseSingularNouns: The cmdlet 'Violate-Analyzers' uses a plural noun.
2 changes: 1 addition & 1 deletion Lombiq.Analyzers.PowerShell/Invoke-Analyzer.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ function Write-FileError([string] $Message, [string] $Path, [int] $Line = 0, [in
}
else
{
Write-Error $(if ($Path) { "[$Path|ln ${Line}:${Column}] $Message" } else { $Message })
Write-Error $(if ($Path) { "[$Path|ln $($Line):$Column] $Message" } else { $Message })
}
}

Expand Down
65 changes: 65 additions & 0 deletions Lombiq.Analyzers.PowerShell/Rules/AstFunctions.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
using namespace System.Management.Automation.Language

# Traverse the chain of parents of an AST object until a parent of a specific type is found.
function Find-AstNearestParent
{
param(
[Parameter(Mandatory = $true)] [Ast] $AstObject,
[Parameter(Mandatory = $true)] [Type] $ParentType
)

$parent = $AstObject.Parent
while ($null -ne $parent -and $parent -isNot $ParentType)
{
$parent = $parent.Parent
}

return $parent
}

# Traverse the chain of parents of an AST object to extract each parent of a specific type.
function Find-AstParent
{
param(
[Parameter(Mandatory = $true)] [Ast] $AstObject,
[Parameter(Mandatory = $true)] [Type] $ParentType
)

$parents = @()
$currentParent = Find-AstNearestParent -AstObject $AstObject -ParentType $ParentType
while ($null -ne $currentParent)
{
$parents += @($currentParent)
$currentParent = Find-AstNearestParent -AstObject $currentParent -ParentType $ParentType
}

return $parents
}

# Extract the parameters of a script block or a function definition.
function Find-AstParameter
{
param([Parameter(Mandatory = $true)] [Ast] $AstObject)

$parameters = @()

if (-not $AstObject -is [ScriptBlockAst] -and -not $AstObject -is [FunctionDefinitionAst])
{
throw 'The provided AST object is not a script block or a function definition.'
}

if ($AstObject.Parameters)
{
$parameters += $AstObject.Parameters
}
elseif ($AstObject.ParamBlock.Parameters)
{
$parameters += $AstObject.ParamBlock.Parameters
}
elseif ($AstObject.Body.ParamBlock.Parameters)
{
$parameters += $AstObject.Body.ParamBlock.Parameters
}

return $parameters
}
7 changes: 7 additions & 0 deletions Lombiq.Analyzers.PowerShell/Rules/CustomRules.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# Custom analyzer rules

Our custom analyzer rules are automatically included when using `Invoke-Analyzer.ps1` or GitHub Actions.

- `Measure-AutomaticVariableAlias`: Detects the usages of the alias `$_` of the automatic variable `$PSItem` and suggests to correct them.
- `Measure-LineContinuation`: Detects the usages of the backtick (line continuation) character.
- `Measure-VariableNameCasing`: Detects inconsistencies in the casing of parameter names and variable names (including automatic variables).
Original file line number Diff line number Diff line change
@@ -1,16 +1,18 @@
<#
.SYNOPSIS
Detects the usages of the alias $_ of the automatic variable $PSItem and suggests to correct them.
Detects the usages of the alias '$_' of the automatic variable '$PSItem' and suggests to correct them.
.DESCRIPTION
The full name of the automatic variable $PSItem should be used instead of its alias $_ for consistency.
The full name of the automatic variable '$PSItem' should be used instead of its alias '$_' for consistency. Produces
warnings of the type 'PSAvoidUsingAutomaticVariableAlias'.
.EXAMPLE
Measure-AutomaticVariableAlias -Token $Token
.INPUTS
[System.Management.Automation.Language.Token[]]
.OUTPUTS
[Microsoft.Windows.Powershell.ScriptAnalyzer.Generic.DiagnosticRecord[]]
.NOTES
Inspired by https://github.com/PowerShell/PSScriptAnalyzer/blob/master/Tests/Engine/CommunityAnalyzerRules/CommunityAnalyzerRules.psm1#L613.
Inspired by
https://github.com/PowerShell/PSScriptAnalyzer/blob/master/Tests/Engine/CommunityAnalyzerRules/CommunityAnalyzerRules.psm1#L613.
#>
function Measure-AutomaticVariableAlias
{
Expand All @@ -31,14 +33,12 @@ function Measure-AutomaticVariableAlias
try
{
# Filter down tokens to just variable tokens with the name "_".
foreach ($automaticVariableAliasToken in $Token | Where-Object { $PSItem.GetType().Name -eq 'VariableToken' -and $PSItem.Name -eq '_' })
foreach ($automaticVariableAliasToken in $Token | Where-Object {
$PSItem.Kind -eq [System.Management.Automation.Language.TokenKind]::Variable -and $PSItem.Name -eq '_' })
{
$correctionTypeName = 'Microsoft.Windows.PowerShell.ScriptAnalyzer.Generic.CorrectionExtent'
$correctionExtent = New-Object -TypeName $correctionTypeName -ArgumentList @(
$automaticVariableAliasToken.Extent.StartLineNumber
$automaticVariableAliasToken.Extent.EndLineNumber
$automaticVariableAliasToken.Extent.StartColumnNumber
$automaticVariableAliasToken.Extent.EndColumnNumber
$automaticVariableAliasToken.Extent
'$PSItem'
'Replaced the usage of the alias of the automatic variable "$_" with its full name "$PSItem".'
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@
In general, the community feels you should avoid using those backticks as "line continuation characters" when
possible. They are hard to read, and easy to miss and mistype. Also, adding an extra whitespace after the backtick
breaks the command execution. To fix a violation of this rule, please remove backticks from your script and use
parameter splatting instead. You can run "Get-Help about_splatting" to get more details.
parameter splatting instead. You can run "Get-Help about_splatting" to get more details. Produces warnings of type
'PSAvoidUsingLineContinuation'.
.EXAMPLE
Measure-LineContinuation -Token $Token
.INPUTS
Expand Down
Loading