/**
* 克隆代码
* @param localPath 拉取到本地的地址
* @param remotePath 远程仓库地址
* @param branch 拉去的分支
* @throws IOException
* @throws GitAPIException
*/
public static void cloneCode(String localPath,String remotePath,String branch) throws IOException, GitAPIException {
//获取路径中的本地文件夹
String localPathName = localPath + JGitCommon.getFileName(remotePath);
File file = new File(localPathName);
if(!file.exists()){
file.mkdir();
}
//设置远程服务器上的用户名和密码
UsernamePasswordCredentialsProvider usernamePasswordCredentialsProvider =new
UsernamePasswordCredentialsProvider(_configReader.getVal("UserName"),_configReader.getVal("PassWord"));
//克隆代码库命令
CloneCommand cloneCommand = Git.cloneRepository();
Git git= cloneCommand.setURI(remotePath) //设置远程URI
.setBranch(branch) //设置clone下来的分支
.setDirectory(new File(localPathName)) //设置下载存放路径
.setCredentialsProvider(usernamePasswordCredentialsProvider) //设置权限验证
.call();
System.out.println("代码拉去完毕");
//System.out.print(git.tag());
}
/**
* 提交修改后的文件
* @param localPath 本地修改的代码地址
* @param remotePath 需要提交到的远程地址
* @param message 提交信息
* @throws IOException
* @throws GitAPIException
*/
public static void gitAddYamlCommit(String localPath,String remotePath,String message) throws IOException, GitAPIException {
//找到本地的git路径,一般在隐藏.git文件夹下
Git git = new Git(new FileRepository(localPath + JGitCommon.getFileName(remotePath)+"/.git"));
//提交代码
git.add().addFilepattern(".").call();
git.commit().setAll(true).setMessage(message).call();
UsernamePasswordCredentialsProvider usernamePasswordCredentialsProvider =new
UsernamePasswordCredentialsProvider(_configReader.getVal("UserName"),_configReader.getVal("PassWord"));
//git仓库地址
git.push().setRemote("origin").setCredentialsProvider(usernamePasswordCredentialsProvider).call();
System.out.println(remotePath+"===提交成功");
}
/**
* 推送新分支到远程
* @param localPath 本地git地址
* @param remotePath 远程git地址
* @param newbranch 新分支名称
* @return
*/
public static void newBranch(String localPath,String remotePath,String newbranch){
try {
// 账号密码认证
UsernamePasswordCredentialsProvider usernamePasswordCredentialsProvider =new
UsernamePasswordCredentialsProvider(_configReader.getVal("UserName"),_configReader.getVal("PassWord"));
//找到本地的git路径,一般在隐藏.git文件夹下
Git git = new Git(new FileRepository(localPath + JGitCommon.getFileName(remotePath)+"/.git"));
//检查新建的分支是否已经存在,如果存在则将已存在的分支强制删除并新建一个分支
List<Ref> refs = git.branchList().call();
for (Ref ref : refs) {
if (ref.getName().equals(newbranch)) {
System.out.println("Removing branch before");
git.branchDelete()
.setBranchNames(newbranch)
.setForce(true)
.call();
break;
}
}
//新建分支
Ref ref = git.branchCreate().setName(newbranch).call();
//推送到远程
git.push().add(ref).setCredentialsProvider(usernamePasswordCredentialsProvider).call();
System.out.println(newbranch+"分支推送完毕");
} catch (Exception e) {
e.printStackTrace();
}
}