使用jgit从较早的提交创建新的提交?

时间:2019-12-04 06:41:35

标签: java git github gitlab jgit

我想将文件还原到同一master分支中的给定提交。我为此创建了临时分支更改,但仍然没有成功。我只想更改旧提交ID。我不想合并当前和旧的提交更改,仅合并旧的提交更改,然后将其作为新的提交提交。

Repository repository = new FileRepository("E:" + "/.git");
Git gitObj = new Git(repository);

// create changes branch
Ref changes = gitObj.branchCreate().setName("changes").call();
System.out.println("result of branch create " + changes);

// checkout branch changes
Ref checkout = gitObj.checkout().setName("changes").call();
System.out.println("result of checkout " + checkout);

// apply that specific commit to this branch
CherryPickCommand cherryPickCommand = gitObj.cherryPick();
cherryPickCommand.include(getAnyObjectIdFromRevision(2));
cherryPickCommand.setStrategy(MergeStrategy.OURS);
cherryPickCommand.call();

// switch back to master branch
checkout = gitObj.checkout().setName("master").call();
System.out.println("master checkout result " + checkout);

//retrive the object id of the latest commit on branch
ObjectId mergeBase = repository.resolve("changes");

//actual merge
MergeResult merge = gitObj.merge().include(mergeBase).setMessage("merged changes").call();


System.out.println("Merge-Results for id: " + mergeBase + ": " + merge);
for (Map.Entry<String,int[][]> entry : merge.getConflicts().entrySet()) {
    System.out.println("Key: " + entry.getKey());
    for(int[] arr : entry.getValue()) {
        System.out.println("value: " + Arrays.toString(arr));
    }
}   

// delete branch
DeleteBranchCommand deleteBranchCommand = gitObj.branchDelete();
deleteBranchCommand.setBranchNames("changes");
deleteBranchCommand.setForce(true);

0 个答案:

没有答案