You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在ICommandPredictor中获取调用预测器的Shell当前目录?

解决ICommandPredictor获取PowerShell当前工作目录的问题

直接通过PowerShell的Runspace会话状态获取当前工作目录即可——Environment.CurrentDirectory和Directory.GetCurrentDirectory()返回的是进程启动目录,而PowerShell的工作目录是会话级状态,由Runspace单独维护。

具体实现步骤

  • 在PredictSuggestionsAsync方法中,通过Runspace.DefaultRunspace获取当前会话的Runspace实例
  • 利用Runspace的SessionStateProxy.Path.CurrentLocation.Path拿到当前Shell的工作目录
  • 基于该目录查询Git分支列表,再转为预测建议返回

代码示例

using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Management.Automation.Subsystem;
using System.Management.Automation.Subsystem.Prediction;

public class GitBranchPredictor : ICommandPredictor
{
    public string Name => "GitBranchPredictor";
    public Guid Id => new Guid("你的预测器唯一GUID");

    public async Task<PredictorPredictionResult> PredictSuggestionsAsync(PredictorCommandPredictionContext context, CancellationToken cancellationToken)
    {
        // 获取当前Runspace实例
        var runspace = Runspace.DefaultRunspace;
        if (runspace == null)
        {
            return PredictorPredictionResult.NoSuggestions;
        }

        // 获取当前Shell的工作目录
        string currentWorkingDir = runspace.SessionStateProxy.Path.CurrentLocation.Path;

        // 查询当前目录下的Git本地分支
        var gitBranches = GetLocalGitBranches(currentWorkingDir);

        // 转换为PowerShell命令建议格式
        var suggestions = gitBranches.Select(branch => new CommandSuggestion(branch)).ToList();
        return new PredictorPredictionResult(suggestions);
    }

    private List<string> GetLocalGitBranches(string directory)
    {
        var branchList = new List<string>();
        try
        {
            var startInfo = new ProcessStartInfo
            {
                FileName = "git",
                Arguments = "branch --list",
                WorkingDirectory = directory,
                RedirectStandardOutput = true,
                UseShellExecute = false,
                CreateNoWindow = true
            };

            using var process = Process.Start(startInfo);
            if (process == null) return branchList;

            string output = process.StandardOutput.ReadToEnd();
            process.WaitForExit();

            // 解析Git分支输出,去除前缀的*和空格
            branchList = output.Split(new[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries)
                               .Select(line => line.TrimStart('*', ' '))
                               .ToList();
        }
        catch
        {
            // 处理Git未安装、当前目录不是Git仓库等异常情况
        }
        return branchList;
    }

    // 实现ICommandPredictor接口的其他必要方法
    public void OnCommandLineAccepted(string commandLine) { }
    public void OnCommandLineExecuted(string commandLine) { }
    public void OnSessionStateChanged(SessionStateChangedEventArgs args) { }
    public bool CanAcceptFeedback(PredictionFeedbackKind feedback) => false;
    public void OnSuggestionAccepted(SuggestionAcceptedFeedback feedback) { }
    public void OnCommandLinePredictionFeedback(CommandLinePredictionFeedback feedback) { }
}

关键说明

  • Runspace是PowerShell的会话容器,每个会话的工作目录独立维护,通过SessionStateProxy可直接访问会话级状态信息
  • 若想避免依赖外部Git命令,也可以使用LibGit2Sharp库直接操作Git仓库,代码会更简洁可控

内容的提问来源于stack exchange,提问作者Ashijo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 04:05:24