How do I create an in-memory blob with libgit2sharp?

65 Views Asked by At

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 are internal. How do I create blobs without writing the strings to disk?

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

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

    // disk-backed repo
    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"
    var in_memory_blob = in_memory_repo.ObjectDatabase.Write<Blob>(Encoding.UTF8.GetBytes(oldFileContents));

After a deep-dive into the codebase, I still cannot see how to create a blob from directly from a string. Any thoughts?

0

There are 0 best solutions below