Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
659 views
in Technique[技术] by (71.8m points)

c# - Get files modified/added/removed from a commit in LibGit2Sharp

I've this method, where I get files from my last commit:

static void GetFiles(Tree t, String dir = "")
{
    foreach (TreeEntry treeEntry in t)
    {
        if (treeEntry.TargetType == TreeEntryTargetType.Tree)
        {
            Tree tr = repo.Lookup<Tree>(treeEntry.Target.Sha);
            GetFiles(tr, dir + "/" + treeEntry.Name);
        }
        else
        {
            string caminho = dir + "/" + treeEntry.Path;
            arquivos.Add(caminho);
        }
        
    }
    return;
}

I did a look on this question, but I'm newbie with C# and don't understand.

I have this repository:

c:/teste
| - octocat.txt
| - parentoctocat.txt
| - /outros
| | - octocatblue.txt
| | - octored.txt

My last commit have this files modified:

c:/teste
| - /outros
| | - octocatblue.txt <- This modified
| | - octored.txt <- This new

With my method GetFiles I've all files like in this print. How get only the modified/added/removed files?

Program execution


How can I get the previous commit and compare getting the tree of difference?


Solution

static void CompareTrees()
{
    using (repo)
    {
        Tree commitTree = repo.Head.Tip.Tree; // Main Tree
        Tree parentCommitTree = repo.Head.Tip.Parents.First().Tree; // Secondary Tree

        var patch = repo.Diff.Compare<Patch>(parentCommitTree, commitTree); // Difference

        foreach (var ptc in patch)
        {
            Console.WriteLine(ptc.Status +" -> "+ptc.Path); // Status -> File Path
        }
    }
}

Solution

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Because of how git store data in the file systems, a git commit is a snapshot of all the files contained in the commit. Then the Tree object return you the state of all the files of the repository.

I think that you must do the diff between the tree of this commit and the tree of the previous one and I think it should be done with the method Repository.Diff.Compare()


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...