如何创建命令行预测器

PSReadLine 2.1.0 通过实现预测 IntelliSense 功能引入了智能命令行预测器的概念。 PSReadLine 2.2.2 通过添加一个允许你创建自己的命令行预测器的插件模型,在该功能的基础上进行了扩展。

预测 IntelliSense 会在你键入时在命令行上提供建议,以此增强 Tab 自动补全功能。 预测建议在光标后显示为彩色文本。 这使你可以基于命令历史记录或其他特定于域的插件中的匹配预测来发现、编辑和执行完整命令。

系统要求

若要创建和使用插件预测器,必须使用以下版本的软件:

  • PowerShell 7.2(或更高版本)- 提供创建命令预测器所需的 API
  • PSReadLine 2.2.2(或更高版本)- 允许将 PSReadLine 配置为使用插件

预测器概述

预测器是 PowerShell 二进制模块。 此模块必须实现 System.Management.Automation.Subsystem.Prediction.ICommandPredictor 接口。 此接口声明用于查询预测结果和提供反馈的方法。

预测器模块必须在加载时使用 PowerShell 的 CommandPredictor 注册 SubsystemManager 子系统,并在卸载时取消注册。

下图显示了 PowerShell 中预测器的体系结构。

体系结构

创建代码

若要创建预测器,必须为平台安装 .NET 6 SDK。 有关 SDK 的详细信息,请参阅下载 .NET 6.0

按照以下步骤创建新的 PowerShell 模块项目:

  1. 使用 dotnet 命令行工具创建一个入门类库项目。

    dotnet new classlib --name SamplePredictor
    
  2. 编辑 SamplePredictor.csproj,使之包含以下信息:

    <Project Sdk="Microsoft.NET.Sdk">
    
      <PropertyGroup>
        <TargetFramework>net6.0</TargetFramework>
      </PropertyGroup>
    
      <ItemGroup>
        <PackageReference Include="Microsoft.PowerShell.SDK" Version="7.2.0" />
      </ItemGroup>
    
    </Project>
    
  3. 删除由 dotnet 创建的默认 Class1.cs 文件,并将以下代码复制到项目文件夹中的 SamplePredictorClass.cs 文件。

    using System;
    using System.Collections.Generic;
    using System.Threading;
    using System.Management.Automation;
    using System.Management.Automation.Subsystem;
    using System.Management.Automation.Subsystem.Prediction;
    
    namespace PowerShell.Sample
    {
        public class SamplePredictor : ICommandPredictor
        {
            private readonly Guid _guid;
    
            internal SamplePredictor(string guid)
            {
                _guid = new Guid(guid);
            }
    
            /// <summary>
            /// Gets the unique identifier for a subsystem implementation.
            /// </summary>
            public Guid Id => _guid;
    
            /// <summary>
            /// Gets the name of a subsystem implementation.
            /// </summary>
            public string Name => "SamplePredictor";
    
            /// <summary>
            /// Gets the description of a subsystem implementation.
            /// </summary>
            public string Description => "A sample predictor";
    
            /// <summary>
            /// Get the predictive suggestions. It indicates the start of a suggestion rendering session.
            /// </summary>
            /// <param name="client">Represents the client that initiates the call.</param>
            /// <param name="context">The <see cref="PredictionContext"/> object to be used for prediction.</param>
            /// <param name="cancellationToken">The cancellation token to cancel the prediction.</param>
            /// <returns>An instance of <see cref="SuggestionPackage"/>.</returns>
            public SuggestionPackage GetSuggestion(PredictionClient client, PredictionContext context, CancellationToken cancellationToken)
            {
                string input = context.InputAst.Extent.Text;
                if (string.IsNullOrWhiteSpace(input))
                {
                    return default;
                }
    
                return new SuggestionPackage(new List<PredictiveSuggestion>{
                    new PredictiveSuggestion(string.Concat(input, " HELLO WORLD"))
                });
            }
    
            #region "interface methods for processing feedback"
    
            /// <summary>
            /// Gets a value indicating whether the predictor accepts a specific kind of feedback.
            /// </summary>
            /// <param name="client">Represents the client that initiates the call.</param>
            /// <param name="feedback">A specific type of feedback.</param>
            /// <returns>True or false, to indicate whether the specific feedback is accepted.</returns>
            public bool CanAcceptFeedback(PredictionClient client, PredictorFeedbackKind feedback) => false;
    
            /// <summary>
            /// One or more suggestions provided by the predictor were displayed to the user.
            /// </summary>
            /// <param name="client">Represents the client that initiates the call.</param>
            /// <param name="session">The mini-session where the displayed suggestions came from.</param>
            /// <param name="countOrIndex">
            /// When the value is greater than 0, it's the number of displayed suggestions from the list
            /// returned in <paramref name="session"/>, starting from the index 0. When the value is
            /// less than or equal to 0, it means a single suggestion from the list got displayed, and
            /// the index is the absolute value.
            /// </param>
            public void OnSuggestionDisplayed(PredictionClient client, uint session, int countOrIndex) { }
    
            /// <summary>
            /// The suggestion provided by the predictor was accepted.
            /// </summary>
            /// <param name="client">Represents the client that initiates the call.</param>
            /// <param name="session">Represents the mini-session where the accepted suggestion came from.</param>
            /// <param name="acceptedSuggestion">The accepted suggestion text.</param>
            public void OnSuggestionAccepted(PredictionClient client, uint session, string acceptedSuggestion) { }
    
            /// <summary>
            /// A command line was accepted to execute.
            /// The predictor can start processing early as needed with the latest history.
            /// </summary>
            /// <param name="client">Represents the client that initiates the call.</param>
            /// <param name="history">History command lines provided as references for prediction.</param>
            public void OnCommandLineAccepted(PredictionClient client, IReadOnlyList<string> history) { }
    
            /// <summary>
            /// A command line was done execution.
            /// </summary>
            /// <param name="client">Represents the client that initiates the call.</param>
            /// <param name="commandLine">The last accepted command line.</param>
            /// <param name="success">Shows whether the execution was successful.</param>
            public void OnCommandLineExecuted(PredictionClient client, string commandLine, bool success) { }
    
            #endregion;
        }
    
        /// <summary>
        /// Register the predictor on module loading and unregister it on module un-loading.
        /// </summary>
        public class Init : IModuleAssemblyInitializer, IModuleAssemblyCleanup
        {
            private const string Identifier = "843b51d0-55c8-4c1a-8116-f0728d419306";
    
            /// <summary>
            /// Gets called when assembly is loaded.
            /// </summary>
            public void OnImport()
            {
                var predictor = new SamplePredictor(Identifier);
                SubsystemManager.RegisterSubsystem(SubsystemKind.CommandPredictor, predictor);
            }
    
            /// <summary>
            /// Gets called when the binary module is unloaded.
            /// </summary>
            public void OnRemove(PSModuleInfo psModuleInfo)
            {
                SubsystemManager.UnregisterSubsystem(SubsystemKind.CommandPredictor, new Guid(Identifier));
            }
        }
    }
    

    下面的示例代码为所有用户输入的预测结果返回字符串“HELLO WORLD”。 由于示例预测器不处理任何反馈,因此该代码不会从接口实现反馈方法。 更改预测和反馈代码,以满足预测器的需求。

    注意

    PSReadLine 的列表视图不支持多行建议。 每条建议都应该是一行。 如果代码具有一条多行建议,则应将这些行拆分为多条单独的建议,或使用分号 (;) 将这些行连接起来。

  4. 运行 dotnet build 以生成程序集。 可以在项目文件夹的 bin/Debug/net6.0 位置找到已编译的程序集。

    注意

    为了确保响应迅速的用户体验,ICommandPredictor 接口对来自预测器的响应具有 20 毫秒的超时时间。 预测器代码必须在 20 毫秒内返回结果才能进行显示。

使用预测器插件

若要尝试新的预测器,请打开新的 PowerShell 7.2 会话并运行以下命令:

Set-PSReadLineOption -PredictionSource HistoryAndPlugin
Import-Module .\bin\Debug\net6.0\SamplePredictor.dll

在会话中加载程序集后,在终端中键入时,将显示文本“HELLO WORLD”。 可以按 F2Inline 视图和 List 视图之间切换。

有关 PSReadLine 选项的详细信息,请参阅 Set-PSReadLineOption

可以使用以下命令获取已安装预测器的列表:

Get-PSSubsystem -Kind CommandPredictor
Kind              SubsystemType      IsRegistered Implementations
----              -------------      ------------ ---------------
CommandPredictor  ICommandPredictor          True {SamplePredictor}

备注

Get-PSSubsystem 是 PowerShell 7.1 中引入的实验性 cmdlet,必须启用 PSSubsystemPluginModel 实验性功能才能使用此 cmdlet。 有关详细信息,请参阅使用实验性功能