使用 System.CommandLine 的應用程式在某些命令行介面中具有內建的標籤自動完成支援。 若要啟用它,終端用戶必須在每個命令行介面中執行一些步驟。 完成此動作後,應用程式中的靜態值,例如列舉值或由呼叫 AcceptOnlyFromAmong(String[]) 定義的值,將自動完成索引標籤。 您也可以在運行時間動態提供值,以自定義索引標籤完成。
啟用標籤完成功能
在您想要啟用標籤完成功能的裝置上,請遵循以下步驟。
針對 .NET CLI:
- 請參閱 如何啟用索引標籤自動完成。
針對建置在 System.CommandLine 上的其他命令列應用程式:
安裝
dotnet-suggest全域工具。將適當的適配腳本加入至您的 shell 配置檔。 您可能需要建立 Shell 配置檔案。 墊片腳本會把完成要求從命令指示環境轉送至
dotnet-suggest工具,並將要求委派給適合的System.CommandLine-系統的應用程式。針對
bash,將 dotnet-suggest-shim.bash 的內容新增至 ~/.bash_profile。針對
zsh,將 dotnet-suggest-shim.zsh 的內容新增至 ~/.zshrc。針對 PowerShell,請將 dotnet-suggest-shim.ps1 的內容新增至 PowerShell 配置檔。 您可以在控制台中執行下列命令,以找到 PowerShell 設定檔的預期路徑:
echo $profile
呼叫
dotnet-suggest register --command-path $executableFilePath以註冊應用程式,其中$executableFilePath是應用程式可執行文件的路徑。
設定使用者的命令列環境並註冊可執行檔案後,所有使用 System.CommandLine 建置的應用程式都將支持自動補完功能。
針對 Windows 上的 cmd.exe (Windows 命令提示字元)沒有插入式索引標籤完成機制,因此沒有可用的填充碼腳本。 針對其他 Shell,尋找 GitHub 上標記為 Area-Completions的問題。 如果您找不到問題,您可以開啟新的問題。
在執行時取得分頁完成值
下列程式碼顯示一個應用程式,可在執行時動態擷取標籤自動完成的值。 此程式代碼會取得目前日期之後的接下來兩周日期清單。 清單透過呼叫 --date 被提供給 CompletionSources.Add 選項:
using System.CommandLine;
using System.CommandLine.Completions;
using System.CommandLine.Parsing;
new DateCommand().Parse(args).Invoke();
class DateCommand : Command
{
private Argument<string> subjectArgument = new("subject")
{
Description = "The subject of the appointment."
};
private Option<DateTime> dateOption = new("--date")
{
Description = "The day of week to schedule. Should be within one week."
};
public DateCommand() : base("schedule", "Makes an appointment for sometime in the next week.")
{
this.Arguments.Add(subjectArgument);
this.Options.Add(dateOption);
dateOption.CompletionSources.Add(ctx => {
var today = System.DateTime.Today;
List<CompletionItem> dates = new();
foreach (var i in Enumerable.Range(1, 7))
{
var date = today.AddDays(i);
dates.Add(new CompletionItem(
label: date.ToShortDateString(),
sortText: $"{i:2}"));
}
return dates;
});
this.SetAction(parseResult =>
{
Console.WriteLine($"Scheduled \"{parseResult.GetValue(subjectArgument)}\" for {parseResult.GetValue(dateOption)}");
});
}
}
按下 Tab 鍵時所顯示的值會以 CompletionItem 實例提供:
dates.Add(new CompletionItem(
label: date.ToShortDateString(),
sortText: $"{i:2}"));
已設定下列 CompletionItem 屬性:
-
Label是要顯示的完成值。 -
SortText確保清單中的值會以正確的順序呈現。 它透過將i轉換為兩位數字符串來設定,以使排序依照 01、02、03 等等,直到 14 為止。 如果您未設定此參數,則排序是以 為基礎Label,在此範例中為簡短日期格式,且無法正確排序。
還有其他 CompletionItem 屬性,例如 Documentation 和 Detail,但尚未在 中使用 System.CommandLine。
此程式代碼所建立的動態索引標籤完成清單也會出現在說明輸出中:
Description:
Makes an appointment for sometime in the next week.
Usage:
schedule <subject> [options]
Arguments:
<subject> The subject of the appointment.
Options:
--date The day of week to schedule. Should be within one week.
<2/4/2022|2/5/2022|2/6/2022|2/7/2022|2/8/2022|2/9/2022|2/10/2022>
--version Show version information
-?, -h, --help