コマンドライン予測器を作成する方法
PSReadLine 2.1.0 では、予測 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 モジュール プロジェクトを作成します。
dotnet
コマンドライン ツールを使用して、スターター classlib プロジェクトを作成します。dotnet new classlib --name SamplePredictor
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>
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 のリスト ビューでは、複数行の候補はサポートされていません。 各候補は 1 行にする必要があります。 コードに複数行の候補がある場合は、行を個別の候補に分割するか、セミコロン (
;
) で行を結合する必要があります。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 で導入された試験的なコマンドレットです。このコマンドレットを使用するには、PSSubsystemPluginModel
試験的機能を有効にする必要があります。 詳細については、「試験的特徴の使用」を参照してください。
PowerShell