4

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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Sebastian P.
  • 818
  • 8
  • 20

1 Answers1

6

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.

Rüdiger Herrmann
  • 20,512
  • 11
  • 62
  • 79