Pregunta

I am trying to figure out way to get source of same file from two different commits, but I just can't find any documentation about this.

I know there is Repository.Dif.Compare which is useful but I can only get Patch from it and that doesn't help much since I would like to implement my own side by side comparison.

Can someone provide an example? Is this even possible in libgit2sharp?

¿Fue útil?

Solución

I am trying to figure out way to get source of same file from two different commits [...] Is this even possible in libgit2sharp?

Each Commit or Tree type exposes a string indexer that allows one to directly access a TreeEntry through its path. A TreeEntry can either be a Blob (ie. a file), another Tree (ie. a directory), or a GitLink (ie. a submodule).

The code below, gives a quick example of how to access the content of the same file in two different commits.

[Fact]
public void CanRetrieveTwoVersionsOfTheSameBlob()
{
    using (var repo = new Repository(BareTestRepoPath))
    {
        var c1 = repo.Lookup<Commit>("8496071");
        var b1 = c1["README"].Target as Blob;

        var c2 = repo.Lookup<Commit>("4a202b3");
        var b2 = c2["README"].Target as Blob;

        Assert.NotEqual(b1.ContentAsText(), b2.ContentAsText());
    }
}

I would like to implement my own side by side comparison

Depending of the size of the blob you're dealing with, you may not be willing to retrieve the whole content in memory. In that case, blob.ContentStream may be handy.

Update

I was missing the cast to blob, to figure the rest out

FWIW, you can rely on revparse expressions to directly access the Blob. As the result, the following should also work ;-)

[Fact]
public void CanRetrieveTwoVersionsOfTheSameBlob_ReduxEdition()
{
    using (var repo = new Repository(BareTestRepoPath))
    {
        var b1 = repo.Lookup<Blob>("8496071:README");
        var b2 = repo.Lookup<Blob>("4a202b3:README");

        Assert.NotEqual(b1.ContentAsText(), b2.ContentAsText());
    }
}

Otros consejos

This post should answer your question, it's from another question here on this site:

How to diff the same file between two different commits on the same branch?

I hope that helps.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top