Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.
like image 424
adnan kamili Avatar asked Jan 06 '16 12:01

adnan kamili


2 Answers

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:

  • ConvenientPatch: https://www.nodegit.org/api/convenient_patch/
  • DiffFile: https://www.nodegit.org/api/#DiffFile
  • All API docs: https://www.nodegit.org/api/
like image 125
Juan Avatar answered Nov 10 '22 09:11

Juan


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.

like image 45
jotadepicas Avatar answered Nov 10 '22 09:11

jotadepicas