Git info for current file in plugin

I'm writing a plugin that records some info about the current file.  I'm able to get the current file info, get selected text, and some other basic stuff.  However, I'd also like to check if the file is under source control, and if so, get info about the source control.

I assume this is trickier because the details of source control differ between implementations.  Eventually I may want to handle multiple, but for today, I just want to check if git support is enabled, and get the git info for that file.  Ideally:

current commit
if the file has been edited

I know git is more complex than this interenally.  Selecting a range of text, there may be different commits represented in the text selection, but if I could simply get the latest, that would be good enough.

Thoughts?  I have the Project, VirtualFile, and Editor instances.  Also grabbed the intellij community source and am taking a look at the git plugin source.  Any ideas how to close the loop on this?

Thanks in advance.


Hi Kevin,

You may use ProjectLevelVcsManager.getInstance(Project).getVcsFor(VirtualFile). That would return the instance of the AbstractVcs which controlls the file, or null if it is not under version control.
Then you may get the particular VCS root (as defined in Settings | Version Control table): ProjectLevelVcsManager#getVcsRootFor(VirtualFile).

To check the status of the file you can call ChangeListManager#getStatus(VirtualFile) or #getChange().

As about current commit, could you please clarify: do you want to get the HEAD (tip) commit made in the repository, or you want to get the latest commit in which the particular file was modified?


Thanks for this.  Its exactly what I'm looking for.

"do you want to get the HEAD (tip) commit made in the repository, or you want to get the latest commit in which the particular file was modified?"

latest commit for the file, ideally.



There is no common API for all VCSs for this task, but for Git you can use git4idea.history.GitHistoryUtils#getLastRevision(Project, FilePath).


Absolutely perfect.  Took a little bit of wrestling, but I can pull the repo hash.  Owe you a virtual beer or whatever!



Btw, if you need not just the hash, but other commit details as well, there is also GitHistoryUtils#history (the one with the longest signature), that allows to specify additional parameters ("-n1" in the case when you need just the tip commit).

I'm glad to be of help :-)


Please sign in to leave a comment.