// 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 { /// /// This attribute is used to specify an argument completer for a parameter to a cmdlet or function. /// /// /// [Parameter()] /// [ArgumentCompleter(typeof(NounArgumentCompleter))] /// public string Noun { get; set; } /// /// /// [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] public class ArgumentCompleterAttribute : Attribute { /// [SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods")] public Type Type { get; } /// public ScriptBlock ScriptBlock { get; } /// The type must implement and have a default constructor. public ArgumentCompleterAttribute(Type type) { if (type == null || (type.GetInterfaces().All(static t => t != typeof(IArgumentCompleter)))) { throw PSTraceSource.NewArgumentException(nameof(type)); } Type = type; } /// /// Initializes a new instance of the class. /// This constructor is used by derived attributes implementing . /// protected ArgumentCompleterAttribute() { if (this is not IArgumentCompleterFactory) { throw PSTraceSource.NewInvalidOperationException(); } } /// /// This constructor is used primarily via PowerShell scripts. /// /// 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; } } /// /// A type specified by the must implement this interface. /// #nullable enable public interface IArgumentCompleter { /// /// Implementations of this function are called by PowerShell to complete arguments. /// /// The name of the command that needs argument completion. /// The name of the parameter that needs argument completion. /// The (possibly empty) word being completed. /// The command ast in case it is needed for completion. /// /// 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 . /// /// /// A collection of completion results, most like with set to /// . /// IEnumerable CompleteArgument( string commandName, string parameterName, string wordToComplete, CommandAst commandAst, IDictionary fakeBoundParameters); } #nullable restore /// /// Creates a new argument completer. /// /// /// If an attribute that derives from implements this interface, /// it will be used to create the , thus giving a way to parameterize a completer. /// The derived attribute can have properties or constructor arguments that are used when creating the completer. /// /// /// This example shows the intended usage of to pass arguments to an argument completer. /// /// 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()); /// } /// } /// } /// /// public interface IArgumentCompleterFactory { /// /// Creates an instance of a class implementing the interface. /// /// An IArgumentCompleter instance. IArgumentCompleter Create(); } /// /// Base class for parameterized argument completer attributes. /// [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] public abstract class ArgumentCompleterFactoryAttribute : ArgumentCompleterAttribute, IArgumentCompleterFactory { /// public abstract IArgumentCompleter Create(); } /// /// [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::@@___"; /// /// Gets or sets the command names for which the argument completer is registered. /// [Parameter(ParameterSetName = NativeCommandSetName, Mandatory = true)] [Parameter(ParameterSetName = PowerShellSetName)] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] CommandName { get; set; } /// /// Gets or sets the name of the parameter for which the argument completer is registered. /// [Parameter(ParameterSetName = PowerShellSetName, Mandatory = true)] public string ParameterName { get; set; } /// /// Gets or sets the script block that will be executed to provide argument completions. /// [Parameter(Mandatory = true)] [AllowNull()] public ScriptBlock ScriptBlock { get; set; } /// /// Indicates the argument completer is for native commands. /// [Parameter(ParameterSetName = NativeCommandSetName)] public SwitchParameter Native { get; set; } /// /// Indicates the argument completer is a fallback for any native commands that don't have a completer registered. /// [Parameter(ParameterSetName = NativeFallbackSetName)] public SwitchParameter NativeFallback { get; set; } /// /// protected override void EndProcessing() { Dictionary 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 table, string key, ScriptBlock value) { if (value is null) { table.Remove(key); } else { table[key] = value; } } } } /// /// This attribute is used to specify an argument completions for a parameter of a cmdlet or function /// based on string array. /// /// [Parameter()] /// [ArgumentCompletions("Option1","Option2","Option3")] /// public string Noun { get; set; } /// /// [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] public class ArgumentCompletionsAttribute : Attribute { private readonly string[] _completions; /// /// Initializes a new instance of the ArgumentCompletionsAttribute class. /// /// List of complete values. /// For null arguments. /// For invalid arguments. 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; } /// /// The function returns completions for arguments. /// public IEnumerable 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); } } } } }