当前位置:网站首页 > 更多 > 玩电脑 > 正文

[玩转系统] 如何创建命令行预测器

作者:精品下载站 日期:2024-12-14 02:56:37 浏览:14 分类:玩电脑

如何创建命令行预测器


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

预测式 IntelliSense 通过在您键入时在命令行上提供建议来增强选项卡完成功能。预测建议显示为光标后面的彩色文本。这使您能够根据命令历史记录或其他特定于域的插件的匹配预测来发现、编辑和执行完整命令。

系统要求

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

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

预测器概述

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

预测器模块在加载时必须向 PowerShell 的 SubsystemManager 注册 CommandPredictor 子系统,并在卸载时注销自身。

下图显示了 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”出现。您可以按F2在Inline视图和List视图之间切换。

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

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

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

笔记

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

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯