jgit是eclipse开发的用于拉取代码的一个jar包,可以使用代码实现git的拉取等操作
1.使用前需要先引入maven配置,注意版本号,高版本的有些功能不支持
<dependency> <groupId>org.eclipse.jgit</groupId> <artifactId>org.eclipse.jgit</artifactId> <version>5.5.0.201909110433-r</version> </dependency>
2.使用https方式clone代码
使用用户名密码clone
UsernamePasswordCredentialsProvider user = new UsernamePasswordCredentialsProvider(login, password);
cloneCommand.setURI(url)
.setBranch(branchName) //设置clone下来的分支
.setDirectory(new File(sourceTaskFolderPath)) //设置下载存放路径
.setCredentialsProvider(usernamePasswordCredentialsProvider) //设置权限验证
.call();
使用用户名密码pull
Git git = new Git(new FileRepository(sourceTaskFolderPath + "/.git"));
git.pull().setRemoteBranchName(branchName).
setCredentialsProvider(usernamePasswordCredentialsProvider).call();
3.使用sshkey方式拉取代码
首先自己新建一个ssh工厂类
package com.jd.ptp.utils;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import org.eclipse.jgit.transport.JschConfigSessionFactory;
import org.eclipse.jgit.transport.OpenSshConfig;
import org.eclipse.jgit.transport.OpenSshConfig.Host;
import org.eclipse.jgit.util.FS;
public class MySShSessionFactory extends JschConfigSessionFactory {
private String sshKeyFilePath; //存放ssh的私钥地址,一般为.ssh/id_rsa
private String knownHost; //存放ssh的信任host地址,一般为.ssh/known_hosts
@Override
protected JSch getJSch(final OpenSshConfig.Host hc, FS fs) throws JSchException {
JSch jsch = new JSch();
jsch.removeAllIdentity();
jsch.addIdentity(sshKeyFilePath);
jsch.setKnownHosts(knownHost);
return jsch;
}
@Override
protected void configure(Host hc, Session session) {
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
}
public String getSshKeyFilePath() {
return sshKeyFilePath;
}
public void setSshKeyFilePath(String sshKeyFilePath) {
this.sshKeyFilePath = sshKeyFilePath;
}
public String getKnownHost() {
return knownHost;
}
public void setKnownHost(String knownHost) {
this.knownHost = knownHost;
}
}
使用方法,在要用到的类中新建ssh类对象
MySShSessionFactory myFactory = new MySShSessionFactory();
myFactory.setKnownHost(knownHost);
myFactory.setSshKeyFilePath(privateKeyDir);
SshSessionFactory.setInstance(myFactory);
//执行克隆操作
try {
Git.cloneRepository().setURI(url).
setBranch(branchName).setDirectory(new File(sourceTaskFolderPath)).call();
} catch (Exception e) {
e.printStackTrace();
}
//执行pull操作
try {
Git git = new Git(new FileRepository(sourceTaskFolderPath + "/.git"));
git.pull().setRemoteBranchName(branchName).call();
} catch (Exception e) {
e.printStackTrace();
}
}
注意:生成sshkey时要使用低版本,具体命令为ssh-keygen -m PEM -t rsa -b 4096 -C "xxx@xxx.com"