您的位置:首页 > 编程语言 > Java开发

java使用jgit提交代码

2015-09-20 21:24 375 查看
import org.eclipse.jgit.api.AddCommand;
import org.eclipse.jgit.api.CommitCommand;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.PushCommand;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.storage.file.FileRepositoryBuilder;
import org.junit.Test;

import java.io.File;
import java.io.IOException;

/**
* Created by kxw on 2015/9/18.
* {<a href='http://wiki.eclipse.org/JGit/User_Guide'>@link</a>}
*/
public class TestJgit {

@Test
public void test() throws IOException, GitAPIException {
//在用户的账号配置了ssh,即可提交
FileRepositoryBuilder builder = new FileRepositoryBuilder();
String projectURL = System.getProperty("user.dir");
Repository repository = builder.setGitDir(new File(projectURL.substring(0, projectURL.lastIndexOf("\\"))+"\\.git"))
.readEnvironment() // scan environment GIT_* variables
.findGitDir() // scan up the file system tree
.build();
Git git = new Git(repository);
AddCommand add = git.add();
add.addFilepattern(".").call();//git add .
CommitCommand commit = git.commit();
/**-Dusername=%teamcity.build.username%**/
commit.setCommitter("Kingson_Wu", "Kingson_Wu@163.com");
commit.setAuthor("Kingson_Wu","Kingson_Wu@163.com");
commit.setAll(true);
//commit.setCommitter(new PersonIdent(repository));
RevCommit revCommit = commit.setMessage("use jgit").call();//git commit -m "use jgit"
String commitId = revCommit.getId().name();
System.out.println(commitId);
PushCommand push = git.push();
push.call();//git push
}

@Test
public void testURL(){
String url = this.getClass().getClassLoader().getResource("").getPath();
System.out.println(url);
String projectURL = System.getProperty("user.dir");
//System.out.println(projectURL.lastIndexOf("\\"));
System.out.println(projectURL.substring(0, projectURL.lastIndexOf("\\"))+"\\.git");
}
}


reference: http://wiki.eclipse.org/JGit/User_Guide

github code :https://github.com/Kingson4Wu/Utils4Java/tree/master/jgit
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: