5

I have following git command:

git log --stat=1000 --all > gitstat.log

Is it possible to achieve this in JGit?

If yes, what is the equivalent way to write this in JGit?

Rüdiger Herrmann
  • 20,512
  • 11
  • 62
  • 79
Maytham Fahmi
  • 31,138
  • 14
  • 118
  • 137

1 Answers1

6

To access the history of a repository, JGit provides the RevWalk. Its markStart() method is used to specify at which commits the history should start. All refs in a repository can be obtained with Repository::getAllRefs().

Once a RevWalk instance is set up, use its iterator or its next() method to traverse the history.

Putting that together would look like this:

try (RevWalk revWalk = new RevWalk(repository)) {
  for (Ref ref : repository.getAllRefs().values()) {
    revWalk.markStart(revWalk.parseCommit(ref.getObjectId()));
  }
  for (RevCommit commit : revWalk) {
    // print commit metadata and diff
  }
}

Note that the RevWalk instance that calls parseCommit() must be the same as the one that calls markStart(). Otherwise, the RevWalk will yield funny results.

Once you have a commit (and through this, access to its parent) you can use the DiffFormatter to obtain a list of Diffs and Edits that tell how many files and lines per file were changed.

You may want to look at this post to get started: How to show changes between commits with JGit

And here for an article that covers JGit's diff APIs in depth: http://www.codeaffine.com/2016/06/16/jgit-diff/

Rüdiger Herrmann
  • 20,512
  • 11
  • 62
  • 79
  • Not sure what 'total lines added, deleted in repo' means. You can, of course, calculate the number of lines added/removed between two commits. The link to the article in the answer, in particular the list of `Edit`s should get you there. – Rüdiger Herrmann Nov 25 '16 at 17:26
  • What have you tried? Did you follow the links in the answer? They should contain everything you need. – Rüdiger Herrmann Nov 26 '16 at 17:44
  • `getAllRefs().values()` is deprecated now. use `getRefDatabase().getRefs()` instead. – MehraD Jan 12 '21 at 21:02