adnan kamili
adnan kamili

Reputation: 9455

Nodegit - get diff between two commits

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.

Upvotes: 7

Views: 2882

Answers (2)

Juan
Juan

Reputation: 118

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:

Upvotes: 5

jotadepicas
jotadepicas

Reputation: 2493

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.

Upvotes: 3

Related Questions