Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically do "Git blame -w" in C#

I need to programmatically get the last author of a specific line in the Git history with C#. I tried using 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

But this is the equivalent of the command

git blame <file>

And in fact I need

git blame -w <file> (to ignore whitespace when comparing)

Libgit2sharp do not set the -w switch and don't provide any parameter/option to set it. What are my options ? Do you know any other library compatible with the -w switch of the blame command ?

like image 702
JYL Avatar asked Mar 30 '16 13:03

JYL


Video Answer


3 Answers

When I hit similar advanced scenarios where the git lib isn't cutting it, I just shell out using start process to the real git command line. It's not sexy, but it's mighty effective.

like image 118
robrich Avatar answered Oct 12 '22 22:10

robrich


Maybe using NGIT library will help. That is direct (automatic) port of java JGIT library. Install via nuget package, then:

    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();
    }

Note SetTextComparator(RawTextComparator.WS_IGNORE_ALL) part.

like image 33
Evk Avatar answered Oct 12 '22 23:10

Evk


Unfortunately, libgit2sharp is too slow on extracting blames and using this feature is impractical in real scenarios. So, the best way I think is to employ a Powershell script to use the underlying superfast native git. And then redirect the result to your application.

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']}}
like image 1
Ehsan Mirsaeedi Avatar answered Oct 12 '22 22:10

Ehsan Mirsaeedi