libgit2 / libgit2sharp

Git + .NET = ❤
http://libgit2.github.com
MIT License
3.12k stars 878 forks source link

Feature request: Create blobs in-memory #2050

Open kaspermarstal opened 12 months ago

kaspermarstal commented 12 months ago

I would like to make a diff between two strings with libgit2sharp. The strings hold file contents loaded elsewhere. The diff.Compare-methods only take blobs, and the constructors of the Blobclass don't accept strings or streams and are marked internal. This prevents me from creating blobs directly. I have to write to disk first.

    var oldFileContents = @"
        Line 1
        Line 2
        Line 3
    ";

    var newFileContents = @"
        Line 1
        Line 2 has changed
    ";

    var path = Repository.Init("C:\\tmp");
    var repo = new Repository(path);

    var oldObjectId = repo.ObjectDatabase.Write<Blob>(Encoding.UTF8.GetBytes(oldFileContents));
    var newObjectId = repo.ObjectDatabase.Write<Blob>(Encoding.UTF8.GetBytes(newFileContents));
    var oldBlob = repo.Lookup<Blob>(oldObjectId);
    var newBlob = repo.Lookup<Blob>(newObjectId);
    var diff = repo.Diff.Compare(oldBlob, newBlob);  // Works as expected

    // git repo for in-memory operations
    var in_memory_repo = new Repository();

    // This line failes with the LibGit2SharpException "path cannot exist in repository". As far as I can see this is intentional.
    var in_memory_blob = in_memory_repo.ObjectDatabase.Write<Blob>(Encoding.UTF8.GetBytes(oldFileContents));

Seeing that libgit2sharp already supports working with diffs and patches in-memory, it would be nice to be able to create blobs from strings or streams.