Find GitCommit by it's Hash

Answered

Hi.

I am working on a plugin related to VCS (currently only git) and I need to read commits one by one (to avoid OutOfMemory) from the beginning of project's history. 

While searching solution for this problem, I found 2 methods in GitHistoryUtils: 

GitHistoryUtils.history(project, projectRoot)

and 

GitHistoryUtils.loadDetails(project, projectRoot, handler)

But the first of these methods returns a whole list of commits, and it's can lead to high memory usage, and the second one is reading commits one by one, but from the last commit to earlier. 

So, I though that I can use the second one, loadDetails() to form a stack of commit hashes, and after it, getting commits one by one (if it is possible) by hash.

Therefore, the question is: is there something in intellij API for getting commit by it's hash?

0
3 comments
Official comment

Aleksey is quite correct, `loadDetails` accepts a list of parameters for executing a `git log` command, so you can pass --reverse there. The same method can be used to load commits by hash. To do so, use git4idea.history.GitHistoryUtils#formHashParameters, which can generate appropriate parameters for you. The code would look something like this:

GitHistoryUtils.loadDetails(project, root, Consumer { commit -> /*process commits*/ }, GitHistoryUtils.formHashParameters(GitVcs.getInstance(project), listOf(hashOfCommit1, hashOfCommit2, hashOfCommit3)))

Additionally, I'd like to point out that the second parameter of the method is not the project root, but rather a root of git repository. Here is the method documentation: https://github.com/JetBrains/intellij-community/blob/ce45c783cef4ab350e9b31b4efbcdc422a45991b/plugins/git4idea/src/git4idea/history/GitHistoryUtils.java#L45.

Commits that are loaded by this method are instances of `GitCommit` and they contain all the necessary information (including changes). If a complete commit information is not required, you can use `git4idea.history.GitHistoryUtils#loadTimedCommits` (similar to `loadDetails` but loads `TimedVcsCommit`s -- only with hash, parents list and commit time) or `git4idea.history.GitHistoryUtils#collectCommitsMetadata` (loads commit info without changes by given hashes).

`GitHistoryUtils.loadDetails` reads commits from `git log` command output.
You can try passing "--reverse" argument after `handler` to force git list commits from old to new.

1

Thank you, Julia, and thank you, Aleksey!

0

Please sign in to leave a comment.