Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetching all Git branches programmatically with JGit

Tags:

git

jgit

I am using JGit in a project and I would like to achieve the programmatic equivalent of a git --fetch all. The JGit API Documentation provides three alternative fetch operations called setRefSpecs(...). All alternatives require the developer to define the concrete RefSpecs to update.

I expect that I have to query the repository for all available RefSpecs and aggregate them for one combined fetch call (similar to Getting all branches with JGit ). However, I do not understand how to transform a Ref into a RefSpec. I would appreciate any pointer here.

Very related to this, I am also not sure how to prune local branches that have been deleted remotely (fetch --prune). Am I right to assume that setting setRemoveDeletedRefs to true achieves exactly this?

like image 912
Sebastian P. Avatar asked Oct 19 '25 04:10

Sebastian P.


1 Answers

According to the git fetch documentation, --all will fetch branches from all (configured) remotes.

JGit's RemoteListCommand can be used to get a list of all configured remotes. Fore each remote, you would need to fetch branches. I assume, the refspec fetch said branches is derived from the respective remote's configuration.

Using the JGit API, this would be

Git git = ...
List<RemoteConfig> remotes = git.remoteList().call();
for(RemoteConfig remote : remotes) {
  git.fetch()
      .setRemote(remote.getName())
      .setRefSpecs(remote.getFetchRefSpecs())
      .call();
}

You can, of course, use your own refspec, for example refs/heads/*:refs/remotes/<remote-name>/* to synchronize all branches .

To answer your second question: yes, FetchCommand::setRemoveDeletedRefs is used to prune local branches, the equivalent of --prune.

like image 179
Rüdiger Herrmann Avatar answered Oct 21 '25 22:10

Rüdiger Herrmann