Nodegit - get diff between two commits
Asked Answered
A

2

7

I have two branches master and master.min in my repo.

Suppose my current branch is master.min.

My master branch is at commit - abcd

Some pushes occur to master branch - efgh, ijkl

I store the current commit of my master branch:

 repo.getBranchCommit("master")
        .then(function(commit) {
            startCommit = commit;
        })

Due to high switching time between branches I need to do all the operations remaining on master.min

So, I do a fetch:

repo.fetch("master");

Now, I need to get the list of all the files which were added, modified or deleted between abcd & ijkl

commit.getDiff() is not enough. I need diff between two commits.
Agamic answered 6/1, 2016 at 12:47 Comment(0)
W
5

For those looking for more clear answer:

const nodegit = require('nodegit');
const repo = await nodegit.Repository.open(repoDirectory);

const from = await repo.getCommit(fromCommitSHA);
const fromTree = await from.getTree();

const to = await repo.getCommit(toCommitSHA);
const toTree = await to.getTree();

const diff = await toTree.diff(fromTree);
const patches = await diff.patches();

for (const patch of patches) {
    console.log(patch.newFile().path());
}

Every patch represents a modified file and is an instance of ConvenientPatch. It has two methods oldFile() and newFile() which return an instance of DiffFile representing the file before and after modification.

NodeGit API docs:

Wow answered 2/12, 2020 at 18:39 Comment(0)
G
3

I need this too, but it seems is not supported by nodegit yet.

Having a look at https://github.com/nodegit/nodegit/blob/master/lib/commit.js#L196 I see the diff is calculated by comparing the commit tree and the parent tree:

return thisTree.diffWithOptions(parentTree, options)

So, I assume this could be achieved by implementing a variation of commit#getDiff that receives another commit's OID and calls tree1 = this.getTree() and tree2 = getTheOtherCommit(OID).getTree() and then invoke tree1.diffWithOptions(tree2, options).

Of course the getTheOtherCommit is pseudocode but it's just to picture the idea.

As soon as I can I will try to implement it and post the progress here.

Gig answered 29/2, 2016 at 5:45 Comment(2)
I ended up using git-promise wrapper for git command to get diff. So my code uses nodegit as well as gitAgamic
Very nice approach @jotadepicas. I implemented it and it works. It's not trivial because of the huge amount of Promises.Pinch

© 2022 - 2024 — McMap. All rights reserved.