Skip to content

Commit 8919af7

Browse files
committed
Fix exceptions in importing CustomizedRule
1 parent e2650ba commit 8919af7

11 files changed

+66
-55
lines changed

Engine/Commands/InvokeScriptAnalyzerCommand.cs

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,14 +14,11 @@
1414
using Microsoft.Windows.Powershell.ScriptAnalyzer.Generic;
1515
using System;
1616
using System.Collections.Generic;
17-
using System.ComponentModel.Composition;
1817
using System.Diagnostics.CodeAnalysis;
1918
using System.Globalization;
2019
using System.Linq;
2120
using System.Management.Automation;
2221
using System.Management.Automation.Language;
23-
using System.Resources;
24-
using System.Threading;
2522
using System.Reflection;
2623
using System.IO;
2724
using System.Text;

Engine/Generic/SourceType.cs

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -10,12 +10,6 @@
1010
// THE SOFTWARE.
1111
//
1212

13-
using System;
14-
using System.Collections.Generic;
15-
using System.Linq;
16-
using System.Text;
17-
using System.Threading.Tasks;
18-
1913
namespace Microsoft.Windows.Powershell.ScriptAnalyzer.Generic
2014
{
2115
/// <summary>

Engine/ScriptAnalyzer.cs

Lines changed: 37 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -142,7 +142,7 @@ public void Initilaize(Dictionary<string, List<string>> result)
142142
paths = result.ContainsKey("ValidDllPaths") ? result["ValidDllPaths"] : result["ValidPaths"];
143143
foreach (string path in paths)
144144
{
145-
if (Path.GetExtension(path).ToLower(CultureInfo.CurrentCulture) == ".dll")
145+
if (String.Equals(Path.GetExtension(path),".dll", StringComparison.OrdinalIgnoreCase))
146146
{
147147
catalog.Catalogs.Add(new AssemblyCatalog(path));
148148
}
@@ -241,8 +241,8 @@ public List<ExternalRule> GetExternalRule(string[] moduleNames)
241241

242242
FunctionInfo funcInfo = (FunctionInfo)psobject.ImmediateBaseObject;
243243
ParameterMetadata param = funcInfo.Parameters.Values
244-
.First<ParameterMetadata>(item => item.Name.ToLower(CultureInfo.CurrentCulture).EndsWith("ast", StringComparison.CurrentCulture) ||
245-
item.Name.ToLower(CultureInfo.CurrentCulture).EndsWith("token", StringComparison.CurrentCulture));
244+
.First<ParameterMetadata>(item => item.Name.EndsWith("ast", StringComparison.OrdinalIgnoreCase) ||
245+
item.Name.EndsWith("token", StringComparison.OrdinalIgnoreCase));
246246

247247
//Only add functions that are defined as rules.
248248
if (param != null)
@@ -251,7 +251,7 @@ public List<ExternalRule> GetExternalRule(string[] moduleNames)
251251
string desc =posh.AddScript(script).Invoke()[0].ImmediateBaseObject.ToString()
252252
.Replace("\r\n", " ").Trim();
253253

254-
rules.Add(new ExternalRule(funcInfo.Name, funcInfo.Name, desc, param.Name,
254+
rules.Add(new ExternalRule(funcInfo.Name, funcInfo.Name, desc, param.ParameterType.Name,
255255
funcInfo.ModuleName, funcInfo.Module.Path));
256256
}
257257
}
@@ -337,7 +337,7 @@ public IEnumerable<DiagnosticRecord> GetExternalRecord(Ast ast, Token[] token, E
337337
{
338338
// Find all AstTypes that appeared in rule groups.
339339
IEnumerable<Ast> childAsts = ast.FindAll(new Func<Ast, bool>((testAst) =>
340-
(testAst.GetType().Name.ToLower(CultureInfo.CurrentCulture) == astRuleGroup.Key.ToLower(CultureInfo.CurrentCulture))), false);
340+
Strings.Equals(testAst.GetType().Name, astRuleGroup.Key)), false);
341341

342342
foreach (Ast childAst in childAsts)
343343
{
@@ -381,30 +381,34 @@ public IEnumerable<DiagnosticRecord> GetExternalRecord(Ast ast, Token[] token, E
381381
string message = string.Empty;
382382
string ruleName = string.Empty;
383383

384-
// Because error stream is merged to output stream,
385-
// we need to handle the error records.
386-
if (psobject.ImmediateBaseObject is ErrorRecord)
384+
//Make sure returned DiagnosticRecord is not null
385+
if (psobject!= null && psobject.ImmediateBaseObject != null)
387386
{
388-
ErrorRecord record = (ErrorRecord)psobject.ImmediateBaseObject;
389-
command.WriteError(record);
390-
continue;
391-
}
392-
393-
// DiagnosticRecord may not be correctly returned from external rule.
394-
try
395-
{
396-
Enum.TryParse<DiagnosticSeverity>(psobject.Properties["Severity"].Value.ToString().ToUpper(), out severity);
397-
message = psobject.Properties["Message"].Value.ToString();
398-
extent = (IScriptExtent)psobject.Properties["Extent"].Value;
399-
ruleName = psobject.Properties["RuleName"].Value.ToString();
400-
}
401-
catch (Exception ex)
402-
{
403-
command.WriteError(new ErrorRecord(ex, ex.HResult.ToString("X"), ErrorCategory.NotSpecified, this));
404-
continue;
387+
// Because error stream is merged to output stream,
388+
// we need to handle the error records.
389+
if (psobject.ImmediateBaseObject is ErrorRecord)
390+
{
391+
ErrorRecord record = (ErrorRecord)psobject.ImmediateBaseObject;
392+
command.WriteError(record);
393+
continue;
394+
}
395+
396+
// DiagnosticRecord may not be correctly returned from external rule.
397+
try
398+
{
399+
Enum.TryParse<DiagnosticSeverity>(psobject.Properties["Severity"].Value.ToString().ToUpper(), out severity);
400+
message = psobject.Properties["Message"].Value.ToString();
401+
extent = (IScriptExtent)psobject.Properties["Extent"].Value;
402+
ruleName = psobject.Properties["RuleName"].Value.ToString();
403+
}
404+
catch (Exception ex)
405+
{
406+
command.WriteError(new ErrorRecord(ex, ex.HResult.ToString("X"), ErrorCategory.NotSpecified, this));
407+
continue;
408+
}
409+
410+
if (!string.IsNullOrEmpty(message)) yield return new DiagnosticRecord(message, extent, ruleName, severity, null);
405411
}
406-
407-
if (!string.IsNullOrEmpty(message)) yield return new DiagnosticRecord(message, extent, ruleName, severity, null);
408412
}
409413
}
410414

@@ -453,7 +457,11 @@ public Dictionary<string, List<string>> CheckRuleExtension(string[] path, PSCmdl
453457
// Adds original path, otherwise path.Except<string>(validModPaths) will fail.
454458
// It's possible that user can provide something like this:
455459
// "..\..\..\ScriptAnalyzer.UnitTest\modules\CommunityAnalyzerRules\CommunityAnalyzerRules.psd1"
456-
if (moduleInfo.ExportedFunctions.Count > 0) validModPaths.Add(childPath);
460+
if (moduleInfo.ExportedFunctions.Count > 0)
461+
{
462+
validModPaths.Add(childPath);
463+
cmdlet.WriteVerbose(string.Format(CultureInfo.CurrentCulture, Strings.ImportCustomizedRuleSuccess, childPath));
464+
}
457465
}
458466
}
459467
catch
@@ -478,7 +486,7 @@ public Dictionary<string, List<string>> CheckRuleExtension(string[] path, PSCmdl
478486

479487
cmdlet.WriteDebug(string.Format(CultureInfo.CurrentCulture, Strings.CheckAssemblyFile, resolvedPath));
480488

481-
if (Path.GetExtension(resolvedPath).ToLower(CultureInfo.CurrentCulture) == ".dll")
489+
if (String.Equals(Path.GetExtension(resolvedPath),".dll",StringComparison.OrdinalIgnoreCase))
482490
{
483491
if (!File.Exists(resolvedPath))
484492
{

Engine/ScriptAnalyzerEngine.csproj

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,9 @@
8282
</ItemGroup>
8383
<ItemGroup>
8484
<None Include="PSScriptAnalyzer.psd1" />
85-
<None Include="ScriptAnalyzer.format.ps1xml" />
85+
<None Include="ScriptAnalyzer.format.ps1xml">
86+
<SubType>Designer</SubType>
87+
</None>
8688
<None Include="ScriptAnalyzer.types.ps1xml" />
8789
</ItemGroup>
8890
<ItemGroup>

Engine/Strings.Designer.cs

Lines changed: 17 additions & 10 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Engine/Strings.resx

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,9 @@
135135
<data name="FileNotFound" xml:space="preserve">
136136
<value>Cannot find file '{0}'.</value>
137137
</data>
138+
<data name="ImportCustomizedRuleSuccess" xml:space="preserve">
139+
<value>Customized rules found. Imported to PSScriptAnalyzer rule collections successfully...</value>
140+
</data>
138141
<data name="InvalidPath" xml:space="preserve">
139142
<value>Cannot find the path '{0}'.</value>
140143
</data>

Rules/Strings.Designer.cs

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Rules/Strings.resx

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -678,4 +678,7 @@
678678
<data name="AvoidUsingWMIObjectCmdletName" xml:space="preserve">
679679
<value>AvoidUsingWMIObjectCmdlet</value>
680680
</data>
681+
<data name="ImportCustomizedRuleSuccess" xml:space="preserve">
682+
<value>Customized rules found. Imported to PSScriptAnalyzer engine successfully...</value>
683+
</data>
681684
</root>

Rules/UseCmdletCorrectly.cs

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -45,9 +45,6 @@ public IEnumerable<DiagnosticRecord> AnalyzeScript(Ast ast, string fileName)
4545
{
4646
CommandAst cmdAst = (CommandAst)foundAst;
4747

48-
// Handles the exception caused by commands like, {& $PLINK $args 2> $TempErrorFile}.
49-
// You can also review the remark section in following document,
50-
// MSDN: CommandAst.GetCommandName Method
5148
if (cmdAst.GetCommandName() == null) continue;
5249

5350
// Checks mandatory parameters.

Tests/Disabled Rules/AvoidOneChar.tests.ps1

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ $oneCharMessage = "The cmdlet name O only has one character."
33
$oneCharName = "PSOneChar"
44
$directory = Split-Path -Parent $MyInvocation.MyCommand.Path
55
$invoke = Invoke-ScriptAnalyzer $directory\AvoidUsingReservedCharOneCharNames.ps1 | Where-Object {$_.RuleName -eq $oneCharName}
6-
$noViolations = Invoke-ScriptAnalyzer $directory\GoodCmdlet.ps1 | Where-Object {$_.RuleName -eq $oneCharName}
6+
$noViolations = Invoke-ScriptAnalyzer $directory\..\Rules\GoodCmdlet.ps1 | Where-Object {$_.RuleName -eq $oneCharName}
77

88
Describe "Avoid Using One Char" {
99
Context "When there are violations" {

Tests/Disabled Rules/CommandNotFound.tests.ps1

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
Import-Module -Verbose ScriptAnalyzer
1+
Import-Module -Verbose PSScriptAnalyzer
22
$violationMessage = "Command Get-WrongCommand Is Not Found"
33
$violationName = "PSCommandNotFound"
44
$directory = Split-Path -Parent $MyInvocation.MyCommand.Path

0 commit comments

Comments
 (0)