[英]How to get the file list for a commit with JGit
我一直在開發一個基於 Java 的產品,它將集成 Git 功能。 使用其中一項 Git 功能,我通過暫存並在一次提交中提交這些文件,將 10 多個文件添加到 Git 存儲庫中。
上述過程的逆過程是否可能? 即查找作為提交的一部分提交的文件列表。
我在git.log()
命令的幫助下得到了提交,但我不確定如何獲取提交的文件列表。
示例代碼:
Git git = (...);
Iterable<RevCommit> logs = git.log().call();
for(RevCommit commit : logs) {
String commitID = commit.getName();
if(commitID != null && !commitID.isEmpty()) {
TableItem item = new TableItem(table, SWT.None);
item.setText(commitID);
// Here I want to get the file list for the commit object
}
}
每個提交都指向一個樹,該樹表示構成提交的所有文件。
請注意,這不僅包括在此特定提交中添加、修改或刪除的文件,還包括此修訂版中包含的所有文件。
如果提交表示為RevCommit
,則可以像這樣獲取樹的 ID:
ObjectId treeId = commit.getTree().getId();
如果提交 ID 來自另一個來源,則需要首先解析它以獲取關聯的樹 ID。 例如,請參見此處: 如何使用 JGit 從 SHA1 ID 字符串獲取 RevCommit 或 ObjectId?
為了迭代一棵樹,請使用TreeWalk
:
try (TreeWalk treeWalk = new TreeWalk(repository)) {
treeWalk.reset(treeId);
while (treeWalk.next()) {
String path = treeWalk.getPathString();
// ...
}
}
如果您只對某個提交記錄的更改感興趣,請參閱此處:使用 JGit 創建差異或此處: 使用 JGit 與上次提交的文件差異
我從這個鏈接中給出的代碼中編輯了一些。 您可以嘗試使用以下代碼。
public void commitHistory(Git git) throws NoHeadException, GitAPIException, IncorrectObjectTypeException, CorruptObjectException, IOException, UnirestException
{
Iterable<RevCommit> logs = git.log().call();
int k = 0;
for (RevCommit commit : logs) {
String commitID = commit.getName();
if (commitID != null && !commitID.isEmpty())
{
LogCommand logs2 = git.log().all();
Repository repository = logs2.getRepository();
tw = new TreeWalk(repository);
tw.setRecursive(true);
RevCommit commitToCheck = commit;
tw.addTree(commitToCheck.getTree());
for (RevCommit parent : commitToCheck.getParents())
{
tw.addTree(parent.getTree());
}
while (tw.next())
{
int similarParents = 0;
for (int i = 1; i < tw.getTreeCount(); i++)
if (tw.getFileMode(i) == tw.getFileMode(0) && tw.getObjectId(0).equals(tw.getObjectId(i)))
similarParents++;
if (similarParents == 0)
System.out.println("File names: " + fileName);
}
}
}
}
您可以嘗試:
git diff --stat --name-only ${hash} ${hash}~1
或者看到更大范圍的差異:
git diff --stat --name-only ${hash1} ${hash2}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.