Monday, October 14, 2013

JGit in short example

JGit is the great java library, that provides functionality to perform basic git operations. I used it when I decided to implement release cutting helper for my team. One of the requirements was to make this tool cross-platform (part of the team uses Windows PCs, and another one - Macs), that's why I decided to use java.

The very first search in google pointed me to JGit as "one of the best solutions to work with git from java".

Despite its popularity, it was hard to find some useful code examples for beginners, instead I've found a lot of general descriptions of how cool this library is.

Finally I've got some working examples in stackoverflow, that allowed me to start building my tool.

So trying to fix that situation - listing basic git operations using JGit:

public class GitUtils {
    private Git git;

    public GitUtils(String localPath) throws Exception {
        if(!localPath.endsWith(File.separator)){
            localPath += File.separator;
        }
        git = new Git(new FileRepository(localPath + ".git"));
    }

    public void pull() throws Exception {
        String currentBranch = git.getRepository().getBranch();
        StoredConfig config = git.getRepository().getConfig();
        if(config.getString("branch", currentBranch, "remote") == null){
            config.setString("branch", currentBranch, "remote", "origin");
            config.setString("branch", currentBranch, "merge", "refs/heads/" + currentBranch);
        }
        git.pull().call();
    }

    public void commit(String message) throws Exception {
        git.commit()
                .setMessage(message)
                .setAll(true)
                .call();
    }

    public void push() throws Exception{
        git.push().call();
    }

    public void checkout(String branchName, String sourceBranchName, boolean createNew) throws Exception {
        CheckoutCommand command = git.checkout()
                .setName(branchName)
                //.setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK)
                .setForce(true)
                .setCreateBranch(createNew);
        if(StringUtils.isNotBlank(sourceBranchName)){
            command = command.setStartPoint(sourceBranchName);
        }
        command.call();
    }
}

Enjoy coding!

No comments:

Post a Comment