How do I do git push with JGit?

John Smith picture John Smith · Nov 19, 2012 · Viewed 22.5k times · Source

I'm trying to build a Java application that allows users to use Git based repositories. I was able to do this from the command-line, using the following commands:

git init
<create some files>
git add .
git commit
git remote add <remote repository name> <remote repository URI>
git push -u <remote repository name> master

This allowed me to create, add and commit content to my local repository and push contents to the remote repository. I am now trying to do the same thing in my Java code, using JGit. I was able to easily do git init, add and commit using JGit API.

Repository localRepo = new FileRepository(localPath);
this.git = new Git(localRepo);        
localRepo.create();  
git.add().addFilePattern(".").call();
git.commit().setMessage("test message").call();

Again, all of this works fine. I couldn't find any example or equivalent code for git remote add and git push. I did look at this SO question.

testPush() fails with the error message TransportException: origin not found. In the other examples I've seen https://gist.github.com/2487157 do git clone before git push and I don't understand why that's necessary.

Any pointers to how I can do this will be appreciated.

Answer

OlgaMaciaszek picture OlgaMaciaszek · Nov 23, 2017

The easiest way is to use the JGit Porcelain API:

    Git git = Git.open(localPath); 

    // add remote repo:
    RemoteAddCommand remoteAddCommand = git.remoteAdd();
    remoteAddCommand.setName("origin");
    remoteAddCommand.setUri(new URIish(httpUrl));
    // you can add more settings here if needed
    remoteAddCommand.call();

    // push to remote:
    PushCommand pushCommand = git.push();
    pushCommand.setCredentialsProvider(new UsernamePasswordCredentialsProvider("username", "password"));
    // you can add more settings here if needed
    pushCommand.call();