File size: 13,138 Bytes
8c763fb | 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 | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Management.Automation.Language;
namespace System.Management.Automation
{
/// <summary>
/// This attribute is used to specify an argument completer for a parameter to a cmdlet or function.
/// <example>
/// <code>
/// [Parameter()]
/// [ArgumentCompleter(typeof(NounArgumentCompleter))]
/// public string Noun { get; set; }
/// </code>
/// </example>
/// </summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public class ArgumentCompleterAttribute : Attribute
{
/// <summary/>
[SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods")]
public Type Type { get; }
/// <summary/>
public ScriptBlock ScriptBlock { get; }
/// <param name="type">The type must implement <see cref="IArgumentCompleter"/> and have a default constructor.</param>
public ArgumentCompleterAttribute(Type type)
{
if (type == null || (type.GetInterfaces().All(static t => t != typeof(IArgumentCompleter))))
{
throw PSTraceSource.NewArgumentException(nameof(type));
}
Type = type;
}
/// <summary>
/// Initializes a new instance of the <see cref="ArgumentCompleterAttribute"/> class.
/// This constructor is used by derived attributes implementing <see cref="IArgumentCompleterFactory"/>.
/// </summary>
protected ArgumentCompleterAttribute()
{
if (this is not IArgumentCompleterFactory)
{
throw PSTraceSource.NewInvalidOperationException();
}
}
/// <summary>
/// This constructor is used primarily via PowerShell scripts.
/// </summary>
/// <param name="scriptBlock"></param>
public ArgumentCompleterAttribute(ScriptBlock scriptBlock)
{
if (scriptBlock is null)
{
throw PSTraceSource.NewArgumentNullException(nameof(scriptBlock));
}
ScriptBlock = scriptBlock;
}
internal IArgumentCompleter CreateArgumentCompleter()
{
return Type != null
? Activator.CreateInstance(Type) as IArgumentCompleter
: this is IArgumentCompleterFactory factory
? factory.Create()
: null;
}
}
/// <summary>
/// A type specified by the <see cref="ArgumentCompleterAttribute"/> must implement this interface.
/// </summary>
#nullable enable
public interface IArgumentCompleter
{
/// <summary>
/// Implementations of this function are called by PowerShell to complete arguments.
/// </summary>
/// <param name="commandName">The name of the command that needs argument completion.</param>
/// <param name="parameterName">The name of the parameter that needs argument completion.</param>
/// <param name="wordToComplete">The (possibly empty) word being completed.</param>
/// <param name="commandAst">The command ast in case it is needed for completion.</param>
/// <param name="fakeBoundParameters">
/// This parameter is similar to $PSBoundParameters, except that sometimes PowerShell cannot or
/// will not attempt to evaluate an argument, in which case you may need to use <paramref name="commandAst"/>.
/// </param>
/// <returns>
/// A collection of completion results, most like with <see cref="CompletionResult.ResultType"/> set to
/// <see cref="CompletionResultType.ParameterValue"/>.
/// </returns>
IEnumerable<CompletionResult> CompleteArgument(
string commandName,
string parameterName,
string wordToComplete,
CommandAst commandAst,
IDictionary fakeBoundParameters);
}
#nullable restore
/// <summary>
/// Creates a new argument completer.
/// </summary>
/// <para>
/// If an attribute that derives from <see cref="ArgumentCompleterAttribute"/> implements this interface,
/// it will be used to create the <see cref="IArgumentCompleter"/>, thus giving a way to parameterize a completer.
/// The derived attribute can have properties or constructor arguments that are used when creating the completer.
/// </para>
/// <example>
/// This example shows the intended usage of <see cref="IArgumentCompleterFactory"/> to pass arguments to an argument completer.
/// <code>
/// public class NumberCompleterAttribute : ArgumentCompleterAttribute, IArgumentCompleterFactory {
/// private readonly int _from;
/// private readonly int _to;
///
/// public NumberCompleterAttribute(int from, int to){
/// _from = from;
/// _to = to;
/// }
///
/// // use the attribute parameters to create a parameterized completer
/// IArgumentCompleter Create() => new NumberCompleter(_from, _to);
/// }
///
/// class NumberCompleter : IArgumentCompleter {
/// private readonly int _from;
/// private readonly int _to;
///
/// public NumberCompleter(int from, int to){
/// _from = from;
/// _to = to;
/// }
///
/// IEnumerable{CompletionResult} CompleteArgument(string commandName, string parameterName, string wordToComplete,
/// CommandAst commandAst, IDictionary fakeBoundParameters) {
/// for(int i = _from; i < _to; i++) {
/// yield return new CompletionResult(i.ToString());
/// }
/// }
/// }
/// </code>
/// </example>
public interface IArgumentCompleterFactory
{
/// <summary>
/// Creates an instance of a class implementing the <see cref="IArgumentCompleter"/> interface.
/// </summary>
/// <returns>An IArgumentCompleter instance.</returns>
IArgumentCompleter Create();
}
/// <summary>
/// Base class for parameterized argument completer attributes.
/// </summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public abstract class ArgumentCompleterFactoryAttribute : ArgumentCompleterAttribute, IArgumentCompleterFactory
{
/// <inheritdoc />
public abstract IArgumentCompleter Create();
}
/// <summary>
/// </summary>
[Cmdlet(VerbsLifecycle.Register, "ArgumentCompleter", HelpUri = "https://go.microsoft.com/fwlink/?LinkId=528576")]
public class RegisterArgumentCompleterCommand : PSCmdlet
{
private const string PowerShellSetName = "PowerShellSet";
private const string NativeCommandSetName = "NativeCommandSet";
private const string NativeFallbackSetName = "NativeFallbackSet";
// Use a key that is unlikely to be a file name or path to indicate the fallback completer for native commands.
internal const string FallbackCompleterKey = "___ps::<native_fallback_key>@@___";
/// <summary>
/// Gets or sets the command names for which the argument completer is registered.
/// </summary>
[Parameter(ParameterSetName = NativeCommandSetName, Mandatory = true)]
[Parameter(ParameterSetName = PowerShellSetName)]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] CommandName { get; set; }
/// <summary>
/// Gets or sets the name of the parameter for which the argument completer is registered.
/// </summary>
[Parameter(ParameterSetName = PowerShellSetName, Mandatory = true)]
public string ParameterName { get; set; }
/// <summary>
/// Gets or sets the script block that will be executed to provide argument completions.
/// </summary>
[Parameter(Mandatory = true)]
[AllowNull()]
public ScriptBlock ScriptBlock { get; set; }
/// <summary>
/// Indicates the argument completer is for native commands.
/// </summary>
[Parameter(ParameterSetName = NativeCommandSetName)]
public SwitchParameter Native { get; set; }
/// <summary>
/// Indicates the argument completer is a fallback for any native commands that don't have a completer registered.
/// </summary>
[Parameter(ParameterSetName = NativeFallbackSetName)]
public SwitchParameter NativeFallback { get; set; }
/// <summary>
/// </summary>
protected override void EndProcessing()
{
Dictionary<string, ScriptBlock> completerDictionary;
if (ParameterSetName is NativeFallbackSetName)
{
completerDictionary = Context.NativeArgumentCompleters ??= new(StringComparer.OrdinalIgnoreCase);
SetKeyValue(completerDictionary, FallbackCompleterKey, ScriptBlock);
}
else if (ParameterSetName is NativeCommandSetName)
{
completerDictionary = Context.NativeArgumentCompleters ??= new(StringComparer.OrdinalIgnoreCase);
foreach (string command in CommandName)
{
var key = command?.Trim();
if (string.IsNullOrEmpty(key))
{
continue;
}
SetKeyValue(completerDictionary, key, ScriptBlock);
}
}
else if (ParameterSetName is PowerShellSetName)
{
completerDictionary = Context.CustomArgumentCompleters ??= new(StringComparer.OrdinalIgnoreCase);
string paramName = ParameterName.Trim();
if (paramName.Length is 0)
{
return;
}
if (CommandName is null || CommandName.Length is 0)
{
SetKeyValue(completerDictionary, paramName, ScriptBlock);
return;
}
foreach (string command in CommandName)
{
var key = command?.Trim();
key = string.IsNullOrEmpty(key)
? paramName
: $"{key}:{paramName}";
SetKeyValue(completerDictionary, key, ScriptBlock);
}
}
static void SetKeyValue(Dictionary<string, ScriptBlock> table, string key, ScriptBlock value)
{
if (value is null)
{
table.Remove(key);
}
else
{
table[key] = value;
}
}
}
}
/// <summary>
/// This attribute is used to specify an argument completions for a parameter of a cmdlet or function
/// based on string array.
/// <example>
/// [Parameter()]
/// [ArgumentCompletions("Option1","Option2","Option3")]
/// public string Noun { get; set; }
/// </example>
/// </summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public class ArgumentCompletionsAttribute : Attribute
{
private readonly string[] _completions;
/// <summary>
/// Initializes a new instance of the ArgumentCompletionsAttribute class.
/// </summary>
/// <param name="completions">List of complete values.</param>
/// <exception cref="ArgumentNullException">For null arguments.</exception>
/// <exception cref="ArgumentOutOfRangeException">For invalid arguments.</exception>
public ArgumentCompletionsAttribute(params string[] completions)
{
if (completions == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(completions));
}
if (completions.Length == 0)
{
throw PSTraceSource.NewArgumentOutOfRangeException(nameof(completions), completions);
}
_completions = completions;
}
/// <summary>
/// The function returns completions for arguments.
/// </summary>
public IEnumerable<CompletionResult> CompleteArgument(string commandName, string parameterName, string wordToComplete, CommandAst commandAst, IDictionary fakeBoundParameters)
{
var wordToCompletePattern = WildcardPattern.Get(string.IsNullOrWhiteSpace(wordToComplete) ? "*" : wordToComplete + "*", WildcardOptions.IgnoreCase);
foreach (var str in _completions)
{
if (wordToCompletePattern.IsMatch(str))
{
yield return new CompletionResult(str, str, CompletionResultType.ParameterValue, str);
}
}
}
}
}
|