//历史记录
package example;
import java.io.File;
import java.io.IOException;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.api.errors.NoHeadException;
import org.eclipse.jgit.revwalk.RevCommit;
public class JgitGetVersion {
static Git git;
public static void main(String[] args) {
getHistoryInfo();
}
//历史记录
public static void getHistoryInfo() {
File gitDir = new File("D:/cfrManage/ConfigFile/.git");
try {
if (git == null) {
git = Git.open(gitDir);
}
Iterable<RevCommit> gitlog= git.log().call();
for (RevCommit revCommit : gitlog) {
String version=revCommit.getName();//版本号
revCommit.getAuthorIdent().getName();
revCommit.getAuthorIdent().getEmailAddress();
revCommit.getAuthorIdent().getWhen();//时间
System.out.println(version);
}
}catch (NoHeadException e) {
e.printStackTrace();
} catch (GitAPIException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
// 获取指定版本内容
public static byte[] read(String revision,String gitFilePath) {
OutputStream out = null;
Repository repository = null;
Git git = null;
try {
if(git==null){
File gitDir=new File(URL);
try {
git=Git.open(gitDir);
} catch (IOException e) {
e.printStackTrace();
}
}
repository = git.getRepository();
RevWalk walk = new RevWalk(repository);
ObjectId objId = repository.resolve(revision);
RevCommit revCommit = walk.parseCommit(objId);
RevTree revTree = revCommit.getTree();
TreeWalk treeWalk = TreeWalk.forPath(repository,
gitFilePath, revTree);
if (treeWalk == null)
return null;
ObjectId blobId = treeWalk.getObjectId(0);
ObjectLoader loader = repository.open(blobId);
byte[] bytes = loader.getBytes();
if (bytes != null)
return bytes;
} catch (IOException e) {
} catch (JGitInternalException e) {
} finally {
if (repository != null)
repository.close();
}
return null;
}
上一版本信息
/**
*
* @param revision 版本号
* @param gitFilePath 文件路径
* @return
*/
public static byte[] getParentContent(String revision,String gitFilePath) {
Git git;
byte[] perContent =null;
try {
git = Git.open(new File(URL));
Repository repository = git.getRepository();
RevWalk walk = new RevWalk(repository);
ObjectId objId = repository.resolve(revision);//通过版本号分解,得到版本对象(String>>>object)
RevCommit revCommit = walk.parseCommit(objId);
String preVision = revCommit.getParent(0).getName();//反回上一版本号
ObjectId preId= repository.resolve(preVision);//再次分解
RevCommit revTree = walk.parseCommit(preId);//反回树子树/文件的引用。
RevTree tree= revTree.getTree();
ObjectId objectId= tree.getId();
TreeWalk treeWalk=TreeWalk.forPath(repository, gitFilePath,objectId);//打开一棵树筛选一条路径。
ObjectId treeObj= treeWalk.getObjectId(0);
perContent =repository.open(treeObj).getBytes();//得到文本数据 、、这里可以根据传入不同Objectid反回相应内容
repository.close();
} catch (IOException e) {
e.printStackTrace();
}
return perContent;
}