jGit<转>
闪光的鱼 2019-04-21 11:18:04 /**
* 如果一个文件夹要被设为仓库,则此文件夹下必须有Dir + .git文件
* @author dzz
*/
public class GitUtil {
private final static String GIT = ".git";
private final static String REF_REMOTES = "refs/remotes/origin/";
/**
* 获取指定分支指定文件的内容
*
* @param gitRoot git仓库目录
* @param branchName 分支名称
* @param fileName 文件名称
* @return
* @throws Exception
*/
public static String getContentWithFile(String gitRoot, final String branchName, String fileName) throws Exception {
if (!StringUtils.isEmptyOrNull(gitRoot)) {
File rootDir = new File(gitRoot);
// 初始化git仓库
if (new File(gitRoot + File.separator + GIT).exists() == false) {
/*Git.init().setDirectory(rootDir).call();*/
Git result = Git.cloneRepository()
.setURI("https://github.com/dfightzz/201904.git")
.setDirectory(rootDir)
.call();
System.out.println("Having repository: " + result.getRepository().getDirectory());
}
final Git git = Git.open(new File(gitRoot));
Repository repository = git.getRepository();
RevWalk revWalk = new RevWalk(repository);
Ref ref = repository.getRef(branchName);
if (ref == null) {
ref = repository.getRef(REF_REMOTES + branchName);
}
ExecutorService executor = Executors.newCachedThreadPool();
FutureTask<Boolean> task = new FutureTask<Boolean>(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
return git.pull().call().isSuccessful();
}
});
executor.execute(task);
if (ref == null) {
System.out.println("指定引用错误");
return null;
}
ObjectId objectId = ref.getObjectId();
RevCommit revCommit = revWalk.parseCommit(objectId);
RevTree tree = revCommit.getTree();
//在此句上是否可以多次获取文件
TreeWalk treeWalk = TreeWalk.forPath(repository, fileName,tree);
if (treeWalk == null) {
System.out.println("文件名错误");
return null;
}
ObjectId objectId2 = treeWalk.getObjectId(0);
ObjectLoader loader = repository.open(objectId2);
byte[] bytes = loader.getBytes();
if (bytes != null) {
return new String(bytes);
}
git.close();
}
return null;
}
public static void main(String[] args) throws Exception {
System.out.println(getContentWithFile("C:\\Users\\dzz\\Desktop\\gitresp", "master", "src/cn/dzz/newFile"));\\\\