在 C# 中以编程方式执行 "Git blame -w"

Programmatically do "Git blame -w" in C#

我需要使用 C# 以编程方式获取 Git 历史中特定行的最后一位作者。 我尝试使用 libgit2sharp :

var repo = new LibGit2Sharp.Repository(gitRepositoryPath);
string relativePath = MakeRelativeSimple(filename);
var blameHunks = repo.Blame(relativePath);
// next : find the hunk which overlap the desired line number

但这相当于命令

git blame <file>

事实上我需要

git blame -w <file>(比较时忽略空格)

Libgit2sharp 不设置 -w 开关并且不提供任何 parameter/option 来设置它。 我有哪些选择?您知道与 blame 命令的 -w 开关兼容的任何其他库吗?

也许使用 NGIT 库会有所帮助。那是 java JGIT 库的直接(自动)端口。通过nuget包安装,然后:

    static void Main() {
        var git = Git.Init().SetDirectory("C:\MyGitRepo").Call();            
        string relativePath = "MyFolder/MyFile.cs";            
        var blameHunks = git.Blame().SetFilePath(relativePath).SetTextComparator(RawTextComparator.WS_IGNORE_ALL).Call();
        blameHunks.ComputeAll();
        var firstLineCommit = blameHunks.GetSourceCommit(0);
        // next : find the hunk which overlap the desired line number
        Console.ReadKey();
    }

注意 SetTextComparator(RawTextComparator.WS_IGNORE_ALL) 部分。

当我遇到 git lib 没有削减它的类似高级场景时,我只是 shell 使用启动进程到真正的 git 命令行。不性感,但是很有效。

不幸的是,libgit2sharp 在提取责任方面太慢了,在实际场景中使用此功能是不切实际的。因此,我认为最好的方法是使用 Powershell 脚本来使用底层超快本机 git。然后将结果重定向到您的应用程序。

git blame -l -e -c {commit-sha} -- "{file-path}" | where { $_ -match '(?<sha>\w{40})\s+\(<(?<email>[\w\.\-]+@[\w\-]+\.\w{2,3})>\s+(?<datetime>\d\d\d\d-\d\d-\d\d\s\d\d\:\d\d:\d\d\s-\d\d\d\d)\s+(?<lineNumber>\d+)\)\w*' } | 
foreach { new-object PSObject –prop @{  Email = $matches['email'];lineNumber = $matches['lineNumber'];dateTime = $matches['dateTime'];Sha = $matches['sha']}}