Skip to content

Add PSAvoidTrailingWhitespace rule #820

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

Merged
merged 4 commits into from
Nov 8, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
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
7 changes: 7 additions & 0 deletions RuleDocumentation/AvoidTrailingWhitespace.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# AvoidTrailingWhitespace

**Severity Level: Information**

## Description

Lines should not end with whitespace characters. This can cause problems with the line-continuation backtick, and also clutters up future commits to source control.
159 changes: 159 additions & 0 deletions Rules/AvoidTrailingWhitespace.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
// Copyright (c) Microsoft Corporation.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
#if !CORECLR
using System.ComponentModel.Composition;
#endif
using System.Globalization;
using System.Linq;
using System.Management.Automation.Language;
using Microsoft.Windows.PowerShell.ScriptAnalyzer.Generic;

namespace Microsoft.Windows.PowerShell.ScriptAnalyzer.BuiltinRules
{
/// <summary>
/// A class to walk an AST to check for violation.
/// </summary>
#if !CORECLR
[Export(typeof(IScriptRule))]
#endif
public class AvoidTrailingWhitespace : IScriptRule
{
/// <summary>
/// Analyzes the given ast to find violations.
/// </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>A an enumerable type containing the violations</returns>
public IEnumerable<DiagnosticRecord> AnalyzeScript(Ast ast, string fileName)
{
if (ast == null)
{
throw new ArgumentNullException("ast");
}

var diagnosticRecords = new List<DiagnosticRecord>();

string[] lines = Regex.Split(ast.Extent.Text, @"\r?\n");

for (int lineNumber = 0; lineNumber < lines.Length; lineNumber++)
{
var line = lines[lineNumber];

var match = Regex.Match(line, @"\s+$");
if (match.Success)
{
var startLine = lineNumber + 1;
var endLine = startLine;
var startColumn = match.Index + 1;
var endColumn = startColumn + match.Length;

var violationExtent = new ScriptExtent(
new ScriptPosition(
ast.Extent.File,
startLine,
startColumn,
line
),
new ScriptPosition(
ast.Extent.File,
endLine,
endColumn,
line
));

var suggestedCorrections = new List<CorrectionExtent>();
suggestedCorrections.Add(new CorrectionExtent(
violationExtent,
string.Empty,
ast.Extent.File
));

diagnosticRecords.Add(
new DiagnosticRecord(
String.Format(CultureInfo.CurrentCulture, Strings.AvoidTrailingWhitespaceError),
violationExtent,
GetName(),
GetDiagnosticSeverity(),
ast.Extent.File,
null,
suggestedCorrections
));
}
}

return diagnosticRecords;
}

/// <summary>
/// Retrieves the common name of this rule.
/// </summary>
public string GetCommonName()
{
return string.Format(CultureInfo.CurrentCulture, Strings.AvoidTrailingWhitespaceCommonName);
}

/// <summary>
/// Retrieves the description of this rule.
/// </summary>
public string GetDescription()
{
return string.Format(CultureInfo.CurrentCulture, Strings.AvoidTrailingWhitespaceDescription);
}

/// <summary>
/// Retrieves the name of this rule.
/// </summary>
public string GetName()
{
return string.Format(
CultureInfo.CurrentCulture,
Strings.NameSpaceFormat,
GetSourceName(),
Strings.AvoidTrailingWhitespaceName);
}

/// <summary>
/// Retrieves the severity of the rule: error, warning or information.
/// </summary>
public RuleSeverity GetSeverity()
{
return RuleSeverity.Information;
}

/// <summary>
/// Gets the severity of the returned diagnostic record: error, warning, or information.
/// </summary>
/// <returns></returns>
public DiagnosticSeverity GetDiagnosticSeverity()
{
return DiagnosticSeverity.Information;
}

/// <summary>
/// Retrieves the name of the module/assembly the rule is from.
/// </summary>
public string GetSourceName()
{
return string.Format(CultureInfo.CurrentCulture, Strings.SourceName);
}

/// <summary>
/// Retrieves the type of the rule, Builtin, Managed or Module.
/// </summary>
public SourceType GetSourceType()
{
return SourceType.Builtin;
}
}
}
12 changes: 12 additions & 0 deletions Rules/Strings.resx
Original file line number Diff line number Diff line change
Expand Up @@ -870,6 +870,18 @@
<data name="AvoidGlobalAliasesName" xml:space="preserve">
<value>AvoidGlobalAliases</value>
</data>
<data name="AvoidTrailingWhitespaceName" xml:space="preserve">
<value>AvoidTrailingWhitespace</value>
</data>
<data name="AvoidTrailingWhitespaceCommonName" xml:space="preserve">
<value>Avoid trailing whitespace</value>
</data>
<data name="AvoidTrailingWhitespaceDescription" xml:space="preserve">
<value>Each line should have no trailing whitespace.</value>
</data>
<data name="AvoidTrailingWhitespaceError" xml:space="preserve">
<value>Line has trailing whitespace</value>
</data>
<data name="PlaceOpenBraceName" xml:space="preserve">
<value>PlaceOpenBrace</value>
</data>
Expand Down
4 changes: 2 additions & 2 deletions Tests/Engine/GetScriptAnalyzerRule.tests.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ Describe "Test Name parameters" {

It "get Rules with no parameters supplied" {
$defaultRules = Get-ScriptAnalyzerRule
$expectedNumRules = 51
$expectedNumRules = 52
if ((Test-PSEditionCoreClr) -or (Test-PSVersionV3) -or (Test-PSVersionV4))
{
# for PSv3 PSAvoidGlobalAliases is not shipped because
Expand Down Expand Up @@ -159,7 +159,7 @@ Describe "TestSeverity" {

It "filters rules based on multiple severity inputs"{
$rules = Get-ScriptAnalyzerRule -Severity Error,Information
$rules.Count | Should be 13
$rules.Count | Should be 14
}

It "takes lower case inputs" {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@
{
param(
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[ValidateNotNullOrEmpty()]
[string]
$Param1,
[Parameter(Mandatory=$false)]
[ValidateNotNullOrEmpty()]
[ValidateNotNullOrEmpty()]
[string]
$Param2=$null
)
Expand Down
35 changes: 35 additions & 0 deletions Tests/Rules/AvoidTrailingWhitespace.tests.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
$directory = Split-Path -Parent $MyInvocation.MyCommand.Path
$testRootDirectory = Split-Path -Parent $directory

Import-Module PSScriptAnalyzer
Import-Module (Join-Path $testRootDirectory "PSScriptAnalyzerTestHelper.psm1")

$ruleName = "PSAvoidTrailingWhitespace"

$settings = @{
IncludeRules = @($ruleName)
}

Describe "AvoidTrailingWhitespace" {
$testCases = @(
@{
Type = 'spaces'
Whitespace = ' '
}

@{
Type = 'tabs'
Whitespace = "`t`t`t"
}
)

It 'Should find a violation when a line contains trailing <Type>' -TestCases $testCases {
param (
[string] $Whitespace
)

$def = "`$null = `$null$Whitespace"
$violations = Invoke-ScriptAnalyzer -ScriptDefinition $def -Settings $settings
Test-CorrectionExtentFromContent $def $violations 1 $Whitespace ''
}
}
12 changes: 6 additions & 6 deletions Tests/Rules/BadCmdlet.ps1
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
function Verb-Files
{
[CmdletBinding(DefaultParameterSetName='Parameter Set 1',
SupportsShouldProcess=$true,
[CmdletBinding(DefaultParameterSetName='Parameter Set 1',
SupportsShouldProcess=$true,
PositionalBinding=$false,
HelpUri = 'http://www.microsoft.com/',
ConfirmImpact='Medium')]
Expand All @@ -12,17 +12,17 @@
Param
(
# Param1 help description
[Parameter(Mandatory=$true,
[Parameter(Mandatory=$true,
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true,
ValueFromRemainingArguments=$false,
ValueFromPipelineByPropertyName=$true,
ValueFromRemainingArguments=$false,
Position=0,
ParameterSetName='Parameter Set 1')]
[ValidateNotNull()]
[ValidateNotNullOrEmpty()]
[ValidateCount(0,5)]
[ValidateSet("sun", "moon", "earth")]
[Alias("p1")]
[Alias("p1")]
$Param1,

# Param2 help description
Expand Down