forked from PowerShell/PSScriptAnalyzer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCommandInfoCache.cs
More file actions
156 lines (134 loc) · 5.58 KB
/
CommandInfoCache.cs
File metadata and controls
156 lines (134 loc) · 5.58 KB
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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Concurrent;
using System.Management.Automation;
using System.Linq;
using System.Management.Automation.Runspaces;
namespace Microsoft.Windows.PowerShell.ScriptAnalyzer
{
/// <summary>
/// Provides threadsafe caching around CommandInfo lookups with `Get-Command -Name ...`.
/// </summary>
internal class CommandInfoCache : IDisposable
{
private readonly ConcurrentDictionary<CommandLookupKey, Lazy<CommandInfo>> _commandInfoCache;
private readonly RunspacePool _runspacePool;
private bool disposed = false;
/// <summary>
/// Create a fresh command info cache instance.
/// </summary>
public CommandInfoCache()
{
_commandInfoCache = new ConcurrentDictionary<CommandLookupKey, Lazy<CommandInfo>>();
_runspacePool = RunspaceFactory.CreateRunspacePool(1, 10);
_runspacePool.Open();
}
/// <summary>Dispose the runspace pool</summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if ( disposed )
{
return;
}
if ( disposing )
{
_runspacePool.Dispose();
}
disposed = true;
}
/// <summary>
/// Retrieve a command info object about a command.
/// </summary>
/// <param name="commandName">Name of the command to get a commandinfo object for.</param>
/// <param name="commandTypes">What types of command are needed. If omitted, all types are retrieved.</param>
/// <param name="bypassCache">When needed due to runspace affinity problems of some PowerShell objects.</param>
/// <returns></returns>
public CommandInfo GetCommandInfo(string commandName, CommandTypes? commandTypes = null, bool bypassCache = false)
{
if (string.IsNullOrWhiteSpace(commandName))
{
return null;
}
var key = new CommandLookupKey(commandName, commandTypes);
if (bypassCache)
{
return GetCommandInfoInternal(commandName, commandTypes);
}
// Atomically either use PowerShell to query a command info object, or fetch it from the cache
return _commandInfoCache.GetOrAdd(key, new Lazy<CommandInfo>(() => GetCommandInfoInternal(commandName, commandTypes))).Value;
}
/// <summary>
/// Get a CommandInfo object of the given command name
/// </summary>
/// <returns>Returns null if command does not exists</returns>
private CommandInfo GetCommandInfoInternal(string cmdName, CommandTypes? commandType)
{
string moduleName = null;
string actualCmdName = cmdName;
// Check if cmdName is in the format "moduleName\CmdletName" (exactly one backslash)
int backslashIndex = cmdName.IndexOf('\\');
if (
backslashIndex > 0 &&
backslashIndex == cmdName.LastIndexOf('\\') &&
backslashIndex != cmdName.Length - 1 &&
backslashIndex != 0
)
{
moduleName = cmdName.Substring(0, backslashIndex);
actualCmdName = cmdName.Substring(backslashIndex + 1);
}
// 'Get-Command ?' would return % for example due to PowerShell interpreting is a single-character-wildcard search and not just the ? alias.
// For more details see https://github.com/PowerShell/PowerShell/issues/9308
actualCmdName = WildcardPattern.Escape(actualCmdName);
using (var ps = System.Management.Automation.PowerShell.Create())
{
ps.RunspacePool = _runspacePool;
ps.AddCommand("Get-Command")
.AddParameter("Name", actualCmdName)
.AddParameter("ErrorAction", "SilentlyContinue");
if (commandType != null)
{
ps.AddParameter("CommandType", commandType);
}
if (!string.IsNullOrEmpty(moduleName))
{
ps.AddParameter("Module", moduleName);
}
return ps.Invoke<CommandInfo>()
.FirstOrDefault();
}
}
private struct CommandLookupKey : IEquatable<CommandLookupKey>
{
private readonly string Name;
private readonly CommandTypes CommandTypes;
internal CommandLookupKey(string name, CommandTypes? commandTypes)
{
Name = name;
CommandTypes = commandTypes ?? CommandTypes.All;
}
public bool Equals(CommandLookupKey other)
{
return CommandTypes == other.CommandTypes
&& Name.Equals(other.Name, StringComparison.OrdinalIgnoreCase);
}
public override int GetHashCode()
{
// Algorithm from https://stackoverflow.com/questions/1646807/quick-and-simple-hash-code-combinations
unchecked
{
int hash = 17;
hash = hash * 31 + Name.ToUpperInvariant().GetHashCode();
hash = hash * 31 + CommandTypes.GetHashCode();
return hash;
}
}
}
}
}