Skip to content

Commit cbf5b07

Browse files
author
Quoc Truong
committed
Merge pull request #392 from PowerShell/ThrowErrorInsteadOfWarningForProfiles
Throw error instead of warning for profiles
2 parents 710b43b + ac11a2d commit cbf5b07

File tree

7 files changed

+282
-80
lines changed

7 files changed

+282
-80
lines changed

Engine/Commands/InvokeScriptAnalyzerCommand.cs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -169,6 +169,8 @@ public string Configuration
169169
}
170170
private string configuration;
171171

172+
private bool stopProcessing;
173+
172174
#endregion Parameters
173175

174176
#region Overrides
@@ -181,6 +183,12 @@ protected override void BeginProcessing()
181183
string[] rulePaths = Helper.ProcessCustomRulePaths(customRulePath,
182184
this.SessionState, recurseCustomRulePath);
183185

186+
if (!ScriptAnalyzer.Instance.ParseProfile(this.configuration, this.SessionState.Path, this))
187+
{
188+
stopProcessing = true;
189+
return;
190+
}
191+
184192
ScriptAnalyzer.Instance.Initialize(
185193
this,
186194
rulePaths,
@@ -196,6 +204,12 @@ protected override void BeginProcessing()
196204
/// </summary>
197205
protected override void ProcessRecord()
198206
{
207+
if (stopProcessing)
208+
{
209+
stopProcessing = false;
210+
return;
211+
}
212+
199213
if (String.Equals(this.ParameterSetName, "File", StringComparison.OrdinalIgnoreCase))
200214
{
201215
// throws Item Not Found Exception

Engine/ScriptAnalyzer.cs

Lines changed: 82 additions & 71 deletions
Original file line numberDiff line numberDiff line change
@@ -151,49 +151,25 @@ public void Initialize(
151151
profile);
152152
}
153153

154-
private void Initialize(
155-
IOutputWriter outputWriter,
156-
PathIntrinsics path,
157-
CommandInvocationIntrinsics invokeCommand,
158-
string[] customizedRulePath,
159-
string[] includeRuleNames,
160-
string[] excludeRuleNames,
161-
string[] severity,
162-
bool suppressedOnly = false,
163-
string profile = null)
154+
internal bool ParseProfile(string profile, PathIntrinsics path, IOutputWriter writer)
164155
{
165-
if (outputWriter == null)
166-
{
167-
throw new ArgumentNullException("outputWriter");
168-
}
169-
170-
this.outputWriter = outputWriter;
171-
172-
#region Verifies rule extensions and loggers path
173-
174-
List<string> paths = this.GetValidCustomRulePaths(customizedRulePath, path);
156+
IEnumerable<string> includeRuleList = new List<string>();
157+
IEnumerable<string> excludeRuleList = new List<string>();
158+
IEnumerable<string> severityList = new List<string>();
175159

176-
#endregion
177-
178-
#region Initializes Rules
179-
180-
this.severity = severity;
181-
this.suppressedOnly = suppressedOnly;
182-
this.includeRule = includeRuleNames;
183-
this.excludeRule = excludeRuleNames;
184-
this.includeRegexList = new List<Regex>();
185-
this.excludeRegexList = new List<Regex>();
160+
bool hasError = false;
186161

187-
#region ParseProfile
188162
if (!String.IsNullOrWhiteSpace(profile))
189163
{
190164
try
191-
{
165+
{
192166
profile = path.GetResolvedPSPathFromPSPath(profile).First().Path;
193167
}
194168
catch
195169
{
196-
this.outputWriter.WriteWarning(string.Format(CultureInfo.CurrentCulture, Strings.FileNotFound, profile));
170+
writer.WriteError(new ErrorRecord(new FileNotFoundException(string.Format(CultureInfo.CurrentCulture, Strings.FileNotFound, profile)),
171+
Strings.ConfigurationFileNotFound, ErrorCategory.ResourceUnavailable, profile));
172+
hasError = true;
197173
}
198174

199175
if (File.Exists(profile))
@@ -206,7 +182,9 @@ private void Initialize(
206182
// no hashtable, raise warning
207183
if (hashTableAsts.Count() == 0)
208184
{
209-
this.outputWriter.WriteWarning(string.Format(CultureInfo.CurrentCulture, Strings.InvalidProfile, profile));
185+
writer.WriteError(new ErrorRecord(new ArgumentException(string.Format(CultureInfo.CurrentCulture, Strings.InvalidProfile, profile)),
186+
Strings.ConfigurationFileHasNoHashTable, ErrorCategory.ResourceUnavailable, profile));
187+
hasError = true;
210188
}
211189
else
212190
{
@@ -217,8 +195,9 @@ private void Initialize(
217195
if (!(kvp.Item1 is StringConstantExpressionAst))
218196
{
219197
// first item (the key) should be a string
220-
this.outputWriter.WriteWarning(
221-
string.Format(CultureInfo.CurrentCulture, Strings.WrongKeyFormat, kvp.Item1.Extent.StartLineNumber, kvp.Item1.Extent.StartColumnNumber, profile));
198+
writer.WriteError(new ErrorRecord(new InvalidDataException(string.Format(CultureInfo.CurrentCulture, Strings.WrongKeyFormat, kvp.Item1.Extent.StartLineNumber, kvp.Item1.Extent.StartColumnNumber, profile)),
199+
Strings.ConfigurationKeyNotAString, ErrorCategory.InvalidData, profile));
200+
hasError = true;
222201
continue;
223202
}
224203

@@ -241,10 +220,10 @@ private void Initialize(
241220
// Statements property is never null
242221
if (arrayExp.SubExpression != null)
243222
{
244-
StatementAst stateAst = arrayExp.SubExpression.Statements.First();
223+
StatementAst stateAst = arrayExp.SubExpression.Statements.FirstOrDefault();
245224
if (stateAst != null && stateAst is PipelineAst)
246225
{
247-
CommandBaseAst cmdBaseAst = (stateAst as PipelineAst).PipelineElements.First();
226+
CommandBaseAst cmdBaseAst = (stateAst as PipelineAst).PipelineElements.FirstOrDefault();
248227
if (cmdBaseAst != null && cmdBaseAst is CommandExpressionAst)
249228
{
250229
CommandExpressionAst cmdExpAst = cmdBaseAst as CommandExpressionAst;
@@ -268,8 +247,9 @@ private void Initialize(
268247
// all the values in the array needs to be string
269248
if (!(element is StringConstantExpressionAst))
270249
{
271-
this.outputWriter.WriteWarning(
272-
string.Format(CultureInfo.CurrentCulture, Strings.WrongValueFormat, element.Extent.StartLineNumber, element.Extent.StartColumnNumber, profile));
250+
writer.WriteError(new ErrorRecord(new InvalidDataException(string.Format(CultureInfo.CurrentCulture, Strings.WrongValueFormat, element.Extent.StartLineNumber, element.Extent.StartColumnNumber, profile)),
251+
Strings.ConfigurationValueNotAString, ErrorCategory.InvalidData, profile));
252+
hasError = true;
273253
continue;
274254
}
275255

@@ -281,55 +261,82 @@ private void Initialize(
281261

282262
if (rhsList.Count == 0)
283263
{
284-
this.outputWriter.WriteWarning(
285-
string.Format(CultureInfo.CurrentCulture, Strings.WrongValueFormat, kvp.Item2.Extent.StartLineNumber, kvp.Item2.Extent.StartColumnNumber, profile));
286-
break;
264+
writer.WriteError(new ErrorRecord(new InvalidDataException(string.Format(CultureInfo.CurrentCulture, Strings.WrongValueFormat, kvp.Item2.Extent.StartLineNumber, kvp.Item2.Extent.StartColumnNumber, profile)),
265+
Strings.ConfigurationValueWrongFormat, ErrorCategory.InvalidData, profile));
266+
hasError = true;
267+
continue;
287268
}
288269

289-
switch ((kvp.Item1 as StringConstantExpressionAst).Value.ToLower())
270+
string key = (kvp.Item1 as StringConstantExpressionAst).Value.ToLower();
271+
272+
switch (key)
290273
{
291274
case "severity":
292-
if (this.severity == null)
293-
{
294-
this.severity = rhsList.ToArray();
295-
}
296-
else
297-
{
298-
this.severity = this.severity.Union(rhsList).ToArray();
299-
}
275+
severityList = severityList.Union(rhsList);
300276
break;
301277
case "includerules":
302-
if (this.includeRule == null)
303-
{
304-
this.includeRule = rhsList.ToArray();
305-
}
306-
else
307-
{
308-
this.includeRule = this.includeRule.Union(rhsList).ToArray();
309-
}
278+
includeRuleList = includeRuleList.Union(rhsList);
310279
break;
311280
case "excluderules":
312-
if (this.excludeRule == null)
313-
{
314-
this.excludeRule = rhsList.ToArray();
315-
}
316-
else
317-
{
318-
this.excludeRule = this.excludeRule.Union(rhsList).ToArray();
319-
}
281+
excludeRuleList = excludeRuleList.Union(rhsList);
320282
break;
321283
default:
322-
this.outputWriter.WriteWarning(
323-
string.Format(CultureInfo.CurrentCulture, Strings.WrongKey, kvp.Item1.Extent.StartLineNumber, kvp.Item1.Extent.StartColumnNumber, profile));
284+
writer.WriteError(new ErrorRecord(
285+
new InvalidDataException(string.Format(CultureInfo.CurrentCulture, Strings.WrongKey, key, kvp.Item1.Extent.StartLineNumber, kvp.Item1.Extent.StartColumnNumber, profile)),
286+
Strings.WrongConfigurationKey, ErrorCategory.InvalidData, profile));
287+
hasError = true;
324288
break;
325289
}
326290
}
327291
}
328292
}
329293
}
330294

295+
if (hasError)
296+
{
297+
return false;
298+
}
299+
300+
this.severity = (severityList.Count() == 0) ? null : severityList.ToArray();
301+
this.includeRule = (includeRuleList.Count() == 0) ? null : includeRuleList.ToArray();
302+
this.excludeRule = (excludeRuleList.Count() == 0) ? null : excludeRuleList.ToArray();
303+
304+
return true;
305+
}
306+
307+
private void Initialize(
308+
IOutputWriter outputWriter,
309+
PathIntrinsics path,
310+
CommandInvocationIntrinsics invokeCommand,
311+
string[] customizedRulePath,
312+
string[] includeRuleNames,
313+
string[] excludeRuleNames,
314+
string[] severity,
315+
bool suppressedOnly = false,
316+
string profile = null)
317+
{
318+
if (outputWriter == null)
319+
{
320+
throw new ArgumentNullException("outputWriter");
321+
}
322+
323+
this.outputWriter = outputWriter;
324+
325+
#region Verifies rule extensions and loggers path
326+
327+
List<string> paths = this.GetValidCustomRulePaths(customizedRulePath, path);
328+
331329
#endregion
332330

331+
#region Initializes Rules
332+
333+
this.suppressedOnly = suppressedOnly;
334+
this.severity = this.severity == null ? severity : this.severity.Union(severity ?? new String[0]).ToArray();
335+
this.includeRule = this.includeRule == null ? includeRuleNames : this.includeRule.Union(includeRuleNames ?? new String[0]).ToArray();
336+
this.excludeRule = this.excludeRule == null ? excludeRuleNames : this.excludeRule.Union(excludeRuleNames ?? new String[0]).ToArray();
337+
this.includeRegexList = new List<Regex>();
338+
this.excludeRegexList = new List<Regex>();
339+
333340
//Check wild card input for the Include/ExcludeRules and create regex match patterns
334341
if (this.includeRule != null)
335342
{
@@ -339,6 +346,7 @@ private void Initialize(
339346
this.includeRegexList.Add(includeRegex);
340347
}
341348
}
349+
342350
if (this.excludeRule != null)
343351
{
344352
foreach (string rule in excludeRule)
@@ -1446,7 +1454,10 @@ public IEnumerable<DiagnosticRecord> AnalyzeSyntaxTree(
14461454
if (severity != null)
14471455
{
14481456
var diagSeverity = severity.Select(item => Enum.Parse(typeof(DiagnosticSeverity), item, true));
1449-
diagnosticsList = diagnostics.Where(item => diagSeverity.Contains(item.Severity));
1457+
if (diagSeverity.Count() != 0)
1458+
{
1459+
diagnosticsList = diagnostics.Where(item => diagSeverity.Contains(item.Severity));
1460+
}
14501461
}
14511462

14521463
return this.suppressedOnly ?

Engine/Strings.Designer.cs

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

Engine/Strings.resx

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -193,7 +193,7 @@
193193
<value>Cannot find any DiagnosticRecord with the Rule Suppression ID {0}.</value>
194194
</data>
195195
<data name="WrongKey" xml:space="preserve">
196-
<value>{0} is not a valid key in the profile hashtable: line {0} column {1} in file {2}</value>
196+
<value>{0} is not a valid key in the profile hashtable: line {1} column {2} in file {3}. Valid keys are ExcludeRules, IncludeRules and Severity.</value>
197197
</data>
198198
<data name="WrongKeyFormat" xml:space="preserve">
199199
<value>Key in the profile hashtable should be a string: line {0} column {1} in file {2}</value>
@@ -216,4 +216,22 @@
216216
<data name="VerboseScriptDefinitionMessage" xml:space="preserve">
217217
<value>Analyzing Script Definition.</value>
218218
</data>
219+
<data name="ConfigurationFileHasNoHashTable" xml:space="preserve">
220+
<value>ConfigurationFileHasNoHashTable</value>
221+
</data>
222+
<data name="ConfigurationFileNotFound" xml:space="preserve">
223+
<value>ConfigurationFileNotFound</value>
224+
</data>
225+
<data name="ConfigurationKeyNotAString" xml:space="preserve">
226+
<value>ConfigurationKeyNotAString</value>
227+
</data>
228+
<data name="ConfigurationValueNotAString" xml:space="preserve">
229+
<value>ConfigurationValueNotAString</value>
230+
</data>
231+
<data name="ConfigurationValueWrongFormat" xml:space="preserve">
232+
<value>ConfigurationValueWrongFormat</value>
233+
</data>
234+
<data name="WrongConfigurationKey" xml:space="preserve">
235+
<value>WrongConfigurationKey</value>
236+
</data>
219237
</root>

0 commit comments

Comments
 (0)