Skip to content

Fix crash caused when formatting document #354

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 5 commits into from
Jan 25, 2017
Merged
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
110 changes: 33 additions & 77 deletions src/PowerShellEditorServices/Analysis/AnalysisService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
using System;
using System.Linq;
using System.Management.Automation.Runspaces;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.PowerShell.EditorServices.Console;
using System.Management.Automation;
Expand All @@ -28,6 +27,15 @@ public class AnalysisService : IDisposable
private const int NumRunspaces = 2;
private RunspacePool analysisRunspacePool;
private PSModuleInfo scriptAnalyzerModuleInfo;

private bool hasScriptAnalyzerModule
{
get
{
return scriptAnalyzerModuleInfo != null;
}
}

private string[] activeRules;
private string settingsPath;

Expand Down Expand Up @@ -102,7 +110,10 @@ public AnalysisService(IConsoleHost consoleHost, string settingsPath = null)
try
{
this.SettingsPath = settingsPath;

scriptAnalyzerModuleInfo = FindPSScriptAnalyzerModule();
var sessionState = InitialSessionState.CreateDefault2();
sessionState.ImportPSModulesFromPath(scriptAnalyzerModuleInfo.ModuleBase);
Copy link
Contributor

Choose a reason for hiding this comment

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

Thanks for changing that back! I felt dirty adding the other fix :)


// runspacepool takes care of queuing commands for us so we do not
// need to worry about executing concurrent commands
Expand All @@ -115,7 +126,7 @@ public AnalysisService(IConsoleHost consoleHost, string settingsPath = null)
this.analysisRunspacePool.Open();

ActiveRules = IncludedRules.ToArray();
InitializePSScriptAnalyzer();
EnumeratePSScriptAnalyzerRules();
}
catch (Exception e)
{
Expand Down Expand Up @@ -158,7 +169,7 @@ public async Task<ScriptFileMarker[]> GetSemanticMarkersAsync(ScriptFile file, H
public IEnumerable<string> GetPSScriptAnalyzerRules()
{
List<string> ruleNames = new List<string>();
if (scriptAnalyzerModuleInfo != null)
if (hasScriptAnalyzerModule)
{
var ruleObjects = InvokePowerShell("Get-ScriptAnalyzerRule", new Dictionary<string, object>());
foreach (var rule in ruleObjects)
Expand Down Expand Up @@ -213,7 +224,7 @@ private async Task<ScriptFileMarker[]> GetSemanticMarkersAsync<TSettings>(
string[] rules,
TSettings settings) where TSettings : class
{
if (this.scriptAnalyzerModuleInfo != null
if (hasScriptAnalyzerModule
&& file.IsAnalysisEnabled
&& (typeof(TSettings) == typeof(string) || typeof(TSettings) == typeof(Hashtable))
&& (rules != null || settings != null))
Expand All @@ -228,12 +239,10 @@ private async Task<ScriptFileMarker[]> GetSemanticMarkersAsync<TSettings>(
}
}

private void FindPSScriptAnalyzer()
private static PSModuleInfo FindPSScriptAnalyzerModule()
{
using (var ps = System.Management.Automation.PowerShell.Create())
{
ps.RunspacePool = this.analysisRunspacePool;

ps.AddCommand("Get-Module")
.AddParameter("ListAvailable")
.AddParameter("Name", "PSScriptAnalyzer");
Expand All @@ -245,65 +254,29 @@ private void FindPSScriptAnalyzer()
ps.AddCommand("Select-Object")
.AddParameter("First", 1);

var modules = ps.Invoke();

var psModule = modules == null ? null : modules.FirstOrDefault();
if (psModule != null)
var modules = ps.Invoke<PSModuleInfo>();
var psModuleInfo = modules == null ? null : modules.FirstOrDefault();
if (psModuleInfo != null)
{
scriptAnalyzerModuleInfo = psModule.ImmediateBaseObject as PSModuleInfo;
Logger.Write(
LogLevel.Normal,
string.Format(
"PSScriptAnalyzer found at {0}",
scriptAnalyzerModuleInfo.Path));
}
else
{
Logger.Write(
LogLevel.Normal,
"PSScriptAnalyzer module was not found.");
}
}
}

private async Task<bool> ImportPSScriptAnalyzerAsync()
{
if (scriptAnalyzerModuleInfo != null)
{
var module =
await InvokePowerShellAsync(
"Import-Module",
new Dictionary<string, object>
{
{ "ModuleInfo", scriptAnalyzerModuleInfo },
{ "PassThru", true },
});

if (module.Count() == 0)
{
this.scriptAnalyzerModuleInfo = null;
Logger.Write(LogLevel.Warning,
String.Format("Cannot Import PSScriptAnalyzer: {0}"));
psModuleInfo.Path));

return false;
return psModuleInfo;
}
else
{
Logger.Write(LogLevel.Normal,
String.Format(
"Successfully imported PSScriptAnalyzer {0}",
scriptAnalyzerModuleInfo.Version));

return true;
}
Logger.Write(
LogLevel.Normal,
"PSScriptAnalyzer module was not found.");
return null;
}

return false;
}

private void EnumeratePSScriptAnalyzerRules()
{
if (scriptAnalyzerModuleInfo != null)
if (hasScriptAnalyzerModule)
{
var rules = GetPSScriptAnalyzerRules();
var sb = new StringBuilder();
Expand All @@ -317,31 +290,14 @@ private void EnumeratePSScriptAnalyzerRules()
}
}

private void InitializePSScriptAnalyzer()
{
FindPSScriptAnalyzer();

List<Task> importTasks = new List<Task>();
for (int i = 0; i < NumRunspaces; i++)
{
importTasks.Add(
ImportPSScriptAnalyzerAsync());
}

// Wait for the import requests to complete or fail
Task.WaitAll(importTasks.ToArray());

EnumeratePSScriptAnalyzerRules();
}

private async Task<IEnumerable<PSObject>> GetDiagnosticRecordsAsync<TSettings>(
private async Task<PSObject[]> GetDiagnosticRecordsAsync<TSettings>(
ScriptFile file,
string[] rules,
TSettings settings) where TSettings : class
{
IEnumerable<PSObject> diagnosticRecords = Enumerable.Empty<PSObject>();
var diagnosticRecords = new PSObject[0];

if (this.scriptAnalyzerModuleInfo != null
if (hasScriptAnalyzerModule
&& (typeof(TSettings) == typeof(string)
|| typeof(TSettings) == typeof(Hashtable)))
{
Expand Down Expand Up @@ -375,14 +331,14 @@ private async Task<IEnumerable<PSObject>> GetDiagnosticRecordsAsync<TSettings>(
return diagnosticRecords;
}

private IEnumerable<PSObject> InvokePowerShell(string command, IDictionary<string, object> paramArgMap)
private PSObject[] InvokePowerShell(string command, IDictionary<string, object> paramArgMap)
{
var task = InvokePowerShellAsync(command, paramArgMap);
task.Wait();
return task.Result;
}

private async Task<IEnumerable<PSObject>> InvokePowerShellAsync(string command, IDictionary<string, object> paramArgMap)
private async Task<PSObject[]> InvokePowerShellAsync(string command, IDictionary<string, object> paramArgMap)
{
using (var powerShell = System.Management.Automation.PowerShell.Create())
{
Expand All @@ -396,10 +352,10 @@ private async Task<IEnumerable<PSObject>> InvokePowerShellAsync(string command,
var result = await Task.Factory.FromAsync(powerShell.BeginInvoke(), powerShell.EndInvoke);
if (result == null)
{
return Enumerable.Empty<PSObject>();
return new PSObject[0];
}

return result;
return result.ToArray(); ;
}
}

Expand Down