PowerShell/PowerShell-RFC

RFC for ArgumentCompleter base class

powercode opened this issue · 0 comments

#269

Provide a base class, ArgumentCompleter, to simplify writing custom argument completers

Some common tasks need to be done almost every time a completer is written.

Things like quoting arguments if they contain spaces, matching against WordToComplete, and ensuring that the results are sorted is another such task.

Motivation

As a Developer,
I can use the base class when writing custom argument completers,
so that results are achieved faster, with high quality, and
so that users get a consistent completion experience.

User Experience

using namespace System.Management.Automation;

public class GetCommitCompleter : ArgumentCompleter
{
    // override simplified completer
    protected override CompletionResultSortKind AddCompletionsFor(string commandName, string parameterName, IDictionary fakeBoundParameters)
    {
        switch (parameterName)
        {
            case nameof(GitRebaseCommand.CommitHash):
                CompleteGitCommitHash();
                break;
        }

        return CompletionResultSortKind.Sorted;
    }

    private void CompleteGitCommitHash()
    {
        var user = GetFakeBoundParameter<string>("User");
        foreach(var commit in GitExe.Log())
        {
            if (user is { } u && commit.User != u){
                continue;
            }
            // use a function to complete if the text or tooltip matches WordToComplete
            CompleteMatching(text: commit.Hash, tooltip: $"{commit.User}\r\n{commit.Description}}": CompletionMatch.AnyContainsWithWordToComplete);
        }
    }
}