Skip to content

Add Fix switch parameter for 'File' parameter set to auto-correct warnings (#802) #817

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 32 commits into from
Nov 30, 2017
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
77ff614
Add AutoFix switch parameter for 'File' parameter set, which uses the…
bergmeister Aug 30, 2017
ef75719
PR 817: Name switch 'Fix' and preserver Encoding of the file. However…
bergmeister Sep 12, 2017
24732ee
PR 817 Minor syntax fix for markdown file
bergmeister Sep 12, 2017
4dc4aeb
Improve encoding handling by not using the detectEncodingFromByteOrde…
bergmeister Sep 30, 2017
792fe30
improve wording of help as suggested in PR
bergmeister Nov 6, 2017
5a2f47b
Add simple test for -Fix switch
bergmeister Nov 6, 2017
023f9e3
improve test by restoring original file and also asserting against th…
bergmeister Nov 6, 2017
5d0b52d
Merge branch 'master' of https://github.com/PowerShell/PSScriptAnalyz…
bergmeister Nov 6, 2017
78d9663
Merge branch 'development' of https://github.com/PowerShell/PSScriptA…
bergmeister Nov 6, 2017
6edeef4
Clean up test
bergmeister Nov 6, 2017
f129846
Refactor 'fix' switch out of AnalyzePath method as requested in PR
bergmeister Nov 8, 2017
bfa1c54
Implement SupportShouldProcess for InvokeScriptAnalyzerCommand down t…
bergmeister Nov 8, 2017
50af5d2
Adapt the full .net wrapper in LibraryUsage.tests.ps1 with the -fix s…
bergmeister Nov 8, 2017
771ffb6
Fix Func wrapper in LibraryUsage.tests.ps1
bergmeister Nov 8, 2017
701c264
Another fix to LibraryUsage.tests.ps1 to accomodate -Fix switch and a…
bergmeister Nov 8, 2017
a16c232
Always return true for shouldprocess
bergmeister Nov 9, 2017
e64335f
Add supportshouldprocess to full .net wrapper library
bergmeister Nov 9, 2017
4297ff4
Add 'WhatIf' to common words for help tests
bergmeister Nov 9, 2017
9785993
Add 'Confirm' to common words for help tests
bergmeister Nov 9, 2017
14197ce
Add debug line to debug failing test
bergmeister Nov 9, 2017
fffcd76
Add more debug info for test failure
bergmeister Nov 9, 2017
c707a1e
Add comment about deliberate whitespace warning
bergmeister Nov 9, 2017
9d4e8ef
Number of expected warnings now 5 in -fix test due to PSAvoidTrailin…
bergmeister Nov 9, 2017
c0f881d
Update expected test file
bergmeister Nov 9, 2017
c59b6b0
Remove trailing whitespace in expected file since this gets fixed now
bergmeister Nov 9, 2017
6f6896a
Remove debugging line since test passes now
bergmeister Nov 9, 2017
f5ac9eb
Set-Content -NoNewline was only introduced in PS v5 and would therefo…
bergmeister Nov 9, 2017
8e46750
Syntax fix of last commit
bergmeister Nov 9, 2017
e184e3b
Another small syntax fix (sorry, I am commiting from my mobile)
bergmeister Nov 9, 2017
0df445b
Return $pscmdlet.shouldprocess in .net test wrapper
bergmeister Nov 9, 2017
8525e03
Optimize -Fix switch to only write the fixed file to disk if any fixe…
bergmeister Nov 13, 2017
e12c4a6
Merge branch 'AutoFixWarnings' of https://github.com/bergmeister/PSSc…
bergmeister Nov 13, 2017
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
13 changes: 12 additions & 1 deletion Engine/Commands/InvokeScriptAnalyzerCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,17 @@ public SwitchParameter SuppressedOnly
}
private bool suppressedOnly;

/// <summary>
/// Resolves rule violations automatically where possible.
/// </summary>
[Parameter(Mandatory = false, ParameterSetName = "File")]
public SwitchParameter Fix
{
get { return fix; }
set { fix = value; }
}
private bool fix;

/// <summary>
/// Returns path to the file that contains user profile or hash table for ScriptAnalyzer
/// </summary>
Expand Down Expand Up @@ -377,7 +388,7 @@ private void ProcessInput()
{
foreach (var p in processedPaths)
{
diagnosticsList = ScriptAnalyzer.Instance.AnalyzePath(p, this.recurse);
diagnosticsList = ScriptAnalyzer.Instance.AnalyzePath(p, this.recurse, this.fix);
WriteToOutput(diagnosticsList);
}
}
Expand Down
23 changes: 22 additions & 1 deletion Engine/ScriptAnalyzer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
using System.Collections.ObjectModel;
using System.Collections;
using System.Diagnostics;
using System.Text;

namespace Microsoft.Windows.PowerShell.ScriptAnalyzer
{
Expand Down Expand Up @@ -1451,11 +1452,12 @@ public Dictionary<string, List<string>> CheckRuleExtension(string[] path, PathIn
/// </summary>
/// <param name="path">The path of the file or directory to analyze.</param>
/// <param name="searchRecursively">
/// <param name="fix">
/// If true, recursively searches the given file path and analyzes any
/// script files that are found.
/// </param>
/// <returns>An enumeration of DiagnosticRecords that were found by rules.</returns>
public IEnumerable<DiagnosticRecord> AnalyzePath(string path, bool searchRecursively = false)
public IEnumerable<DiagnosticRecord> AnalyzePath(string path, bool searchRecursively = false, bool fix = false)
{
List<string> scriptFilePaths = new List<string>();

Expand All @@ -1475,6 +1477,13 @@ public IEnumerable<DiagnosticRecord> AnalyzePath(string path, bool searchRecursi
this.BuildScriptPathList(path, searchRecursively, scriptFilePaths);
foreach (string scriptFilePath in scriptFilePaths)
{
if (fix)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can some tests be added to test new code?

{
Copy link

@kapilmb kapilmb Sep 8, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the right place for this block is in the InvokeScriptAnalyzerCommand.cs file. We do not need to change behavior 'Analyzepath` method, which should only analyze and not fix.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This would require some re-factoring of the project because one needs to call the private method BuildScriptPathList of the ScriptAnalyzer class first to get the list of files, therefore it would probably be best to extract the BuildScriptPathList method into a separate class. Can you confirm that you really want this or suggest other options?

var fileEncoding = GetFileEncoding(scriptFilePath);
var scriptFileContentWithFixes = Fix(File.ReadAllText(scriptFilePath, fileEncoding));
File.WriteAllText(scriptFilePath, scriptFileContentWithFixes, fileEncoding); // although this preserves the encoding, it will add a BOM to UTF8 files
}

// Yield each record in the result so that the
// caller can pull them one at a time
foreach (var diagnosticRecord in this.AnalyzeFile(scriptFilePath))
Expand Down Expand Up @@ -1613,6 +1622,18 @@ public EditableText Fix(EditableText text, Range range, out Range updatedRange)
return text;
}

private static Encoding GetFileEncoding(string path)
{
using (var stream = new FileStream(path, FileMode.Open))
{
using (var reader = new StreamReader(stream))
{
reader.Peek(); // needed in order to populate the CurrentEncoding property
return reader.CurrentEncoding;
}
}
}

private static Range SnapToEdges(EditableText text, Range range)
{
// todo add TextLines.Validate(range) and TextLines.Validate(position)
Expand Down
19 changes: 18 additions & 1 deletion docs/markdown/Invoke-ScriptAnalyzer.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ Evaluates a script or module based on selected best practice rules
### UNNAMED_PARAMETER_SET_1
```
Invoke-ScriptAnalyzer [-Path] <String> [-CustomRulePath <String>] [-RecurseCustomRulePath]
[-ExcludeRule <String[]>] [-IncludeRule <String[]>] [-Severity <String[]>] [-Recurse] [-SuppressedOnly]
[-ExcludeRule <String[]>] [-IncludeRule <String[]>] [-Severity <String[]>] [-Recurse] [-SuppressedOnly] [-Fix]
[-Settings <String>]
```

Expand Down Expand Up @@ -399,6 +399,23 @@ Accept pipeline input: False
Accept wildcard characters: False
```

### -Fix
Certain warnings contain a suggested fix in their DiagnosticRecord and therefore those warnings will be fixed automatically using this fix.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I suggest a bit of rewording to be like other switch parameters

Fixes certain warnings which contain a fix in their DiagnosticRecord.


When you used Fix, Invoke-ScriptAnalyzer runs as usual but will apply the fixes before running the analysis. Please make sure that you have a backup of your files when using this switch. It tries to pre-server the file encoding but it is possible that a BOM gets added to the fixed files.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

pre-server -> preserve.


```yaml
Type: SwitchParameter
Parameter Sets: UNNAMED_PARAMETER_SET_1
Aliases:

Required: False
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```

### -Settings
File path that contains user profile or hash table for ScriptAnalyzer

Expand Down