JGit API: Reading configuration information

JGit API: Reading configuration information

Lately I’ve been adding Git support to the Yoxos Workspace Provisioning. This should be done in time for Eclipse Indigo SR1 and this will mean you can easily share your Git configurations in your Yoxos profiles.

I wanted to make it easy to share your existing repository settings, but unlike CVS or SVN, sharing your Git repository makes very little sense.  Likely you want to point someone to a remote (say one you have shared on GitHub). This means I needed to read the repository settings, find all the remote repositories and order them (such that the one called ‚origin‘ is on top).

This turns out to be very easy with the JGit API.  JGit reads the configuration information and stores it in a properties style object where the values are keyed based on their subsection and name. You can get a list of all the remotes by asking for the remote subsection. From here, you can get each remote URL by asking for the URL to a particular remoteName in the remote subsection.

The following code prints out each remote and its URL.

[sourcecode language=“java“]
package com.ianbull;

import java.io.File;
import java.io.IOException;
import java.util.Set;

import org.eclipse.jgit.lib.Config;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.lib.RepositoryBuilder;

public class RemoteReader {

public static void main(String[] args) throws IOException {
Repository repository = new RepositoryBuilder().findGitDir(new File(„/home/irbull/git/p2“)).build();
Config storedConfig = repository.getConfig();
Set remotes = storedConfig.getSubsections(„remote“);

for (String remoteName : remotes) {
String url = storedConfig.getString(„remote“, remoteName, „url“);
System.out.println(remoteName + “ “ + url);
}
}
}
[/sourcecode]