Austin Dady
Austin Dady

Reputation: 9

Read a line from a file on a specific commit in C#

I am trying to capture a specific line in a file given a FilePath, LineNumber, and the CommitID (Hash) for that file repo I have stored locally. I have it working except for I have not been able to access a specify Commit yet. I am currently looking into LibGit2Sharp for the implementation.

Currently I have:

using System.IO;
...
string lineContent;
string[] lines = File.ReadAllLines(filePath);
if (lineNumber > 0 && lineNumber <= lines.Length)
{
    lineContent = lines[lineNumber - 1].Trim();
}

I have a Commit hash similarly to this one: "bc1fd7e96dabd2a3180e5fe7146885208c12f279"

How would I: First specify I would like to access this commit at the root repo directory. Then go to the given file path of that "Repo" in my local files and copy the line from the file that is associated with this commit ID?

Upvotes: -2

Views: 180

Answers (1)

Austin Dady
Austin Dady

Reputation: 9

In order to access the Contents of a specific file at a given path within a Repo Using LibGit2Sharp, given a specific Commit RSA ID. You would need to do something like this:

string lineContent;

Repository repo = new Repository(@"C:\Path");
Commit commit = repo.Lookup<Commit>("CommitHashID");
string[] paths = "Directory/SubDirectory/FilePath.extension".Split('/');
string fullPath = paths[0];
Tree tree = commit.Tree;
TreeEntry entry = tree.First(x => x.Path == fullPath);
if(entry.TargetType == TreeEntryTargetType.Tree)
{
    foreach(string pathPart in paths.Skip(1).ToArray())
    {
        if(entry.TargetType == TreeEntryTargetType.Tree)
            tree = (Tree)entry.Target;

        fullPath += "/" + pathPart;
        entry = tree.First(x => x.Path == fullPath);
    }
}
LibGit2Sharp.Blob blob = (LibGit2Sharp.Blob)entry.Target;
string[] lines = blob.GetContentText().Split(new char[] { '\n' });

if (lineNumber > 0 && lineNumber <= lines.Length)
{
    lineContent = lines[lineNumber - 1].Trim();
}

Upvotes: 1

Related Questions