-
Notifications
You must be signed in to change notification settings - Fork 382
/
UseSupportsShouldProcess.cs
511 lines (462 loc) · 19.3 KB
/
UseSupportsShouldProcess.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Linq;
using System.Collections.Generic;
#if !CORECLR
using System.ComponentModel.Composition;
#endif
using System.Globalization;
using System.Management.Automation.Language;
using Microsoft.Windows.PowerShell.ScriptAnalyzer.Generic;
using Microsoft.Windows.PowerShell.ScriptAnalyzer.Extensions;
namespace Microsoft.Windows.PowerShell.ScriptAnalyzer.BuiltinRules
{
/// <summary>
/// UseSupportsShouldProcess: Checks if a function defines Confirm and/or WhatIf parameters manually instead of using SupportsShouldProcess attribute.
/// </summary>
#if !CORECLR
[Export(typeof(IScriptRule))]
#endif
public class UseSupportsShouldProcess : IScriptRule
{
private const char whitespace = ' ';
private const int indentationSize = 4;
private Ast ast;
private Token[] tokens;
/// <summary>
/// Analyzes the given ast to find if a function defines Confirm and/or WhatIf parameters manually
/// instead of using SupportShouldProcess attribute.
/// </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(nameof(ast));
}
// your code goes here
this.ast = ast;
this.tokens = Helper.Instance.Tokens;
return FindViolations();
}
private List<DiagnosticRecord> FindViolations()
{
var foundAsts = ast.FindAll(x => x is FunctionDefinitionAst, true);
var diagnosticRecords = new List<DiagnosticRecord>();
foreach (var foundAst in foundAsts)
{
var functionDefinitionAst = foundAst as FunctionDefinitionAst;
int whatIfIndex, confirmIndex;
ParameterAst whatIfParamAst, confirmParamAst;
ParamBlockAst paramBlockAst;
var parameterAsts = functionDefinitionAst.GetParameterAsts(out paramBlockAst)?.ToArray();
if (parameterAsts == null)
{
continue;
}
// get paramterAsts and parameter block
// then use get parameter on the parameterAsts
var addsWhatIf = TryGetParameterAst(parameterAsts, "whatif", out whatIfIndex);
whatIfParamAst = addsWhatIf ? parameterAsts[whatIfIndex] : null;
var addsConfirm = TryGetParameterAst(parameterAsts, "confirm", out confirmIndex);
confirmParamAst = addsConfirm ? parameterAsts[confirmIndex] : null;
if (addsWhatIf || addsConfirm)
{
IScriptExtent scriptExtent;
// if both whatif and confirm are present,
// the extent will only contain whatif.
// we do this because editorservices relies on the text
// property of IScriptExtent and if we create a new extent
// with null Text value, it crashes editorservices.
if (addsWhatIf)
{
scriptExtent = whatIfParamAst.Extent;
}
else
{
scriptExtent = confirmParamAst.Extent;
}
diagnosticRecords.Add(new DiagnosticRecord(
GetError(functionDefinitionAst.Name),
scriptExtent,
GetName(),
GetDiagnosticSeverity(),
scriptExtent.File,
null,
GetCorrections(whatIfIndex, confirmIndex, parameterAsts, paramBlockAst, functionDefinitionAst)));
}
}
return diagnosticRecords;
}
private List<CorrectionExtent> GetCorrections(
int whatIfIndex,
int confirmIndex,
ParameterAst[] parameterAsts,
ParamBlockAst paramBlockAst,
FunctionDefinitionAst funcDefnAst)
{
var filePath = funcDefnAst.Extent.File;
var correctionExtents = new List<CorrectionExtent>();
if (paramBlockAst != null)
{
if (whatIfIndex != -1)
{
correctionExtents.Add(GetCorrectionToRemoveParam(whatIfIndex, parameterAsts));
}
if (confirmIndex != -1)
{
correctionExtents.Add(GetCorrectionToRemoveParam(confirmIndex, parameterAsts));
}
AttributeAst attributeAst = paramBlockAst.GetCmdletBindingAttributeAst();
// check if it has cmdletbinding attribute
if (attributeAst != null)
{
NamedAttributeArgumentAst shouldProcessAst = attributeAst.GetSupportsShouldProcessAst();
if (shouldProcessAst != null)
{
ExpressionAst argAst;
if (!shouldProcessAst.GetValue(out argAst)
&& argAst != null)
{
// SupportsShouldProcess is set to something other than $true.
// Set it to $true
correctionExtents.Add(GetCorrectionsToSetShouldProcessToTrue(argAst));
}
}
else
{
// add supportsshouldprocess to the attribute
correctionExtents.Add(GetCorrectionToAddShouldProcess(attributeAst));
}
}
else
{
// has no cmdletbinding attribute
// hence, add the attribute and supportsshouldprocess argument
correctionExtents.Add(GetCorrectionToAddAttribute(paramBlockAst));
}
}
else
{
// function doesn't have param block
// remove the parameter list
// and create an equivalent param block
// add cmdletbinding attribute and add supportsshouldprocess to it.
correctionExtents.Add(GetCorrectionToRemoveFuncParamDecl(funcDefnAst, ast, tokens));
correctionExtents.Add(GetCorrectionToAddParamBlock(funcDefnAst, parameterAsts));
}
// This is how we handle multiple edits-
// create separate edits
// apply those edits to the original script extent
// and then give the corrected extent as suggested correction.
// sort in descending order of start position
correctionExtents.Sort((x, y) =>
{
var xRange = (Range)x;
var yRange = (Range)y;
return xRange.Start < yRange.Start ? 1 : (xRange.Start == yRange.Start ? 0 : -1);
});
var editableText = new EditableText(funcDefnAst.Extent.Text);
var funcDefAstStartPos = funcDefnAst.Extent.ToRange().Start;
foreach (var correctionExtent in correctionExtents)
{
var shiftedCorrectionExtent = Normalize(funcDefAstStartPos, correctionExtent);
editableText.ApplyEdit(shiftedCorrectionExtent);
}
var result = new List<CorrectionExtent>();
result.Add(
new CorrectionExtent(
funcDefnAst.Extent.StartLineNumber,
funcDefnAst.Extent.EndLineNumber,
funcDefnAst.Extent.StartColumnNumber,
funcDefnAst.Extent.EndColumnNumber,
editableText.ToString(),
funcDefnAst.Extent.File));
return result;
}
private CorrectionExtent GetCorrectionsToSetShouldProcessToTrue(ExpressionAst argAst)
{
return new CorrectionExtent(
argAst.Extent.StartLineNumber,
argAst.Extent.EndLineNumber,
argAst.Extent.StartColumnNumber,
argAst.Extent.EndColumnNumber,
"$true",
argAst.Extent.File);
}
private CorrectionExtent GetCorrectionToAddParamBlock(
FunctionDefinitionAst funcDefnAst,
ParameterAst[] parameterAsts)
{
var funcStartScriptPos = funcDefnAst.Extent.StartScriptPosition;
var paramBlockText = WriteParamBlock(parameterAsts);
var indentation = new string(whitespace, funcStartScriptPos.ColumnNumber + 3);
var lines = new List<String>();
lines.Add("{");
lines.AddRange(paramBlockText.Select(line => indentation + line));
return new CorrectionExtent(
funcDefnAst.Body.Extent.StartLineNumber,
funcDefnAst.Body.Extent.StartLineNumber,
funcDefnAst.Body.Extent.StartColumnNumber,
funcDefnAst.Body.Extent.StartColumnNumber + 1,
lines,
funcDefnAst.Extent.File,
null);
}
private IList<String> WriteParamBlock(ParameterAst[] parameterAsts)
{
var lines = new List<String>();
lines.Add("[CmdletBinding(SupportsShouldProcess)]");
lines.Add("param(");
string indentation = new string(whitespace, indentationSize);
int count = 0;
var usableParamAsts = parameterAsts.Where(p => !IsWhatIf(p) && !IsConfirm(p));
var usableCount = usableParamAsts.Count();
foreach (var paramAst in usableParamAsts)
{
count++;
var suffix = ",";
if (count == usableCount)
{
suffix = "";
}
foreach (var line in paramAst.Extent.Text.GetLines())
{
lines.Add(indentation + line + suffix);
}
}
lines.Add(")");
return lines;
}
private static CorrectionExtent GetCorrectionToRemoveFuncParamDecl(
FunctionDefinitionAst funcDefnAst,
Ast ast,
Token[] tokens)
{
var funcDefnTokens = TokenOperations.GetTokens(ast, funcDefnAst, tokens).ToArray();
var lParenTokenIdx = Array.FindIndex(funcDefnTokens, tok => tok.Kind == TokenKind.LParen);
var rParenTokenIdx = Array.FindIndex(funcDefnTokens, tok => tok.Kind == TokenKind.RParen);
return new CorrectionExtent(
funcDefnTokens[lParenTokenIdx - 1].Extent.EndLineNumber,
funcDefnTokens[rParenTokenIdx].Extent.EndLineNumber,
funcDefnTokens[lParenTokenIdx - 1].Extent.EndColumnNumber,
funcDefnTokens[rParenTokenIdx].Extent.EndColumnNumber,
"",
ast.Extent.File);
}
private CorrectionExtent Normalize(
Position refPosition,
CorrectionExtent correctionExtent)
{
var shiftedRange = Range.Normalize(refPosition, (Range)correctionExtent);
return new CorrectionExtent(
shiftedRange.Start.Line,
shiftedRange.End.Line,
shiftedRange.Start.Column,
shiftedRange.End.Column,
correctionExtent.Text,
correctionExtent.File,
correctionExtent.Description);
}
private static CorrectionExtent GetCorrectionToAddAttribute(ParamBlockAst paramBlockAst)
{
return new CorrectionExtent(
paramBlockAst.Extent.StartLineNumber,
paramBlockAst.Extent.StartLineNumber,
1,
1,
new String[] {
new String(whitespace, paramBlockAst.Extent.StartColumnNumber - 1)
+ "[CmdletBinding(SupportsShouldProcess)]",
String.Empty
},
null,
null);
}
private static CorrectionExtent GetCorrectionToAddShouldProcess(AttributeAst cmdletBindingAttributeAst)
{
// 1 for the next position.
var startColumnNumber = cmdletBindingAttributeAst.Extent.Text.IndexOf("(")
+ cmdletBindingAttributeAst.Extent.StartColumnNumber
+ 1;
var extent = cmdletBindingAttributeAst.Extent;
var suffix = cmdletBindingAttributeAst.NamedArguments.Count > 0
|| cmdletBindingAttributeAst.PositionalArguments.Count > 0
? ", "
: "";
return new CorrectionExtent(
extent.StartLineNumber,
extent.StartLineNumber,
startColumnNumber,
startColumnNumber,
"SupportsShouldProcess" + suffix,
extent.File);
}
private static CorrectionExtent GetCorrectionToRemoveParam(
int paramIndex,
ParameterAst[] parameterAsts)
{
IScriptExtent paramExtent = parameterAsts[paramIndex].Extent;
int startLineNumber, startColumnNumber, endLineNumber, endColumnNumber;
startLineNumber = paramExtent.StartLineNumber;
startColumnNumber = paramExtent.StartColumnNumber;
if (paramIndex < parameterAsts.Length - 1)
{
endLineNumber = parameterAsts[paramIndex + 1].Extent.StartLineNumber;
endColumnNumber = parameterAsts[paramIndex + 1].Extent.StartColumnNumber;
}
else
{
// if last item in the parameter list then need to remove the
// trailing comma after the previous parameter.
if (paramIndex > 0)
{
var lp = parameterAsts[paramIndex - 1];
if (!IsWhatIf(lp) && !IsConfirm(lp))
{
startLineNumber = lp.Extent.EndLineNumber;
startColumnNumber = lp.Extent.EndColumnNumber;
}
}
endLineNumber = paramExtent.EndLineNumber;
endColumnNumber = paramExtent.EndColumnNumber;
}
return new CorrectionExtent(
startLineNumber,
endLineNumber,
startColumnNumber,
endColumnNumber,
"",
paramExtent.File);
}
private bool TryGetParameterAst(
FunctionDefinitionAst functionDefinitionAst,
string parameter,
out int parameterIndex,
out ParameterAst[] parameters,
out ParamBlockAst paramBlockAst)
{
if (functionDefinitionAst.Parameters != null)
{
if (TryGetParameterAst(functionDefinitionAst.Parameters, parameter, out parameterIndex))
{
parameters = new List<ParameterAst>(functionDefinitionAst.Parameters).ToArray();
paramBlockAst = null;
functionDefinitionAst.Parameters.CopyTo(parameters, 0);
return true;
}
}
else if (functionDefinitionAst.Body.ParamBlock?.Parameters != null)
{
if (TryGetParameterAst(
functionDefinitionAst.Body.ParamBlock.Parameters,
parameter,
out parameterIndex))
{
parameters = new List<ParameterAst>(functionDefinitionAst.Body.ParamBlock.Parameters).ToArray();
paramBlockAst = functionDefinitionAst.Body.ParamBlock;
return true;
}
}
parameterIndex = -1;
paramBlockAst = null;
parameters = null;
return false;
}
private bool TryGetParameterAst(
ICollection<ParameterAst> parameterAsts,
string parameter,
out int paramIndex)
{
paramIndex = 0;
foreach (var paramAst in parameterAsts)
{
if (IsParameter(paramAst, parameter))
{
return true;
}
++paramIndex;
}
paramIndex = -1;
return false;
}
private static bool IsParameter(ParameterAst parameterAst, string parameterName)
{
return parameterAst.Name.VariablePath.UserPath.Equals(
parameterName,
StringComparison.OrdinalIgnoreCase);
}
private static bool IsWhatIf(ParameterAst parameterAst)
{
return IsParameter(parameterAst, "whatif");
}
private static bool IsConfirm(ParameterAst parameterAst)
{
return IsParameter(parameterAst, "confirm");
}
private string GetError(string functionName)
{
return string.Format(
CultureInfo.CurrentCulture,
Strings.UseSupportsShouldProcessError,
functionName);
}
/// <summary>
/// Retrieves the common name of this rule.
/// </summary>
public string GetCommonName()
{
return string.Format(CultureInfo.CurrentCulture, Strings.UseSupportsShouldProcessCommonName);
}
/// <summary>
/// Retrieves the description of this rule.
/// </summary>
public string GetDescription()
{
return string.Format(CultureInfo.CurrentCulture, Strings.UseSupportsShouldProcessDescription);
}
/// <summary>
/// Retrieves the name of this rule.
/// </summary>
public string GetName()
{
return string.Format(
CultureInfo.CurrentCulture,
Strings.NameSpaceFormat,
GetSourceName(),
Strings.UseSupportsShouldProcessName);
}
/// <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;
}
/// <summary>
/// Retrieves the severity of the rule: error, warning or information.
/// </summary>
public RuleSeverity GetSeverity()
{
return RuleSeverity.Warning;
}
/// <summary>
/// Gets the severity of the returned diagnostic record: error, warning, or information.
/// </summary>
/// <returns></returns>
public DiagnosticSeverity GetDiagnosticSeverity()
{
return DiagnosticSeverity.Warning;
}
}
}