Skip to content

Commit

Permalink
Merge pull request centic9#57 from shaozhengmao/master
Browse files Browse the repository at this point in the history
fetch commits from a remote Git repository via ssh protocol authentication
  • Loading branch information
centic9 authored Apr 4, 2019
2 parents e16c937 + 57e4d66 commit 31de08c
Showing 1 changed file with 69 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
package org.dstadler.jgit.porcelain;

import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.LsRemoteCommand;
import org.eclipse.jgit.api.TransportConfigCallback;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.transport.JschConfigSessionFactory;
import org.eclipse.jgit.transport.OpenSshConfig;
import org.eclipse.jgit.transport.SshSessionFactory;
import org.eclipse.jgit.transport.SshTransport;
import org.eclipse.jgit.transport.Transport;
import org.eclipse.jgit.util.FS;

import java.util.Map;

/**
* Simple snippet which shows how to fetch commits from a remote Git repository
* via ssh protocol authentication.
* <p>
* Created by zhengmaoshao on 2019/4/3 上午12:38
*/
public class FetchRemoteCommitsWithSshAuth
{

private static final String REMOTE_URL = "ssh://<user>@<host>:22/<path-to-remote-repo>/";

public static void main(String[] args) throws GitAPIException {

final SshSessionFactory sshSessionFactory = new JschConfigSessionFactory()
{
@Override
protected void configure(OpenSshConfig.Host host, Session session) {

}

@Override
protected JSch createDefaultJSch(FS fs) throws JSchException {

JSch defaultJSch = super.createDefaultJSch(fs);
defaultJSch.addIdentity("/path/to/private_key");
return defaultJSch;
}
};

LsRemoteCommand lsRemoteCommand = Git.lsRemoteRepository();
lsRemoteCommand.setRemote(REMOTE_URL);
lsRemoteCommand.setTransportConfigCallback(new TransportConfigCallback()
{
@Override
public void configure(Transport transport) {
SshTransport sshTransport = (SshTransport) transport;
sshTransport.setSshSessionFactory(sshSessionFactory);
}
});

final Map<String, Ref> map = lsRemoteCommand.setHeads(true)
.setTags(true)
.callAsMap();

for (Map.Entry<String, Ref> entry : map.entrySet()) {
System.out.println("Key: " + entry.getKey()/*eg.refs/heads/develop*/ + ", Ref: " + entry.getValue().getObjectId().getName()/*eg.e16c937848d5c1ad50ef163003c7b076103f7e37*/);
}

}
}

0 comments on commit 31de08c

Please sign in to comment.