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"));\\\\

...全文
35 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

67,513

社区成员

发帖
与我相关
我的任务
社区描述
J2EE只是Java企业应用。我们需要一个跨J2SE/WEB/EJB的微容器,保护我们的业务核心组件(中间件),以延续它的生命力,而不是依赖J2SE/J2EE版本。
社区管理员
  • Java EE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧