我无法还原到特定版本。以下是我正在运行的代码。
运行此代码后,我希望在文件中仅看到“第1行”和“第2行”。但是,当我打开它时,共有3行。我希望提交一个新修订,包括与修订2中的内容一样。
import java.io.File;
import java.util.Iterator;
import org.apache.commons.io.FileUtils;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.RevertCommand;
import org.eclipse.jgit.revwalk.RevCommit;
public class JGit1 {
public static void main(String[] args) {
try {
// create a clean repository
File path = new File("c:/temp/agit/gitrepo");
if (path.exists()) {
FileUtils.deleteDirectory(path);
}
Git git = Git.init().setDirectory(path).call();
System.out.println("Created a new repository at " + git.getRepository().getDirectory());
// Create a new file and add it to the index
File newFile = new File(path, "file1.txt");
FileUtils.writeStringToFile(newFile, "Line 1\r\n", "UTF-8", true);
git.add().addFilepattern("file1.txt").call();
RevCommit rev1 = git.commit().setAuthor("test", "test@test.com").setMessage("Commit Log 1").call();
// commit some changes
FileUtils.writeStringToFile(newFile, "Line 2\r\n", "UTF-8", true);
git.add().addFilepattern("file1.txt").call();
RevCommit rev2 = git.commit().setAll(true).setAuthor("test", "test@test.com").setMessage("Commit Log 2").call();
// commit some changes
FileUtils.writeStringToFile(newFile, "Line 3\r\n", "UTF-8", true);
git.add().addFilepattern("file1.txt").call();
RevCommit rev3 = git.commit().setAll(true).setAuthor("test", "test@test.com").setMessage("Commit Log 3").call();
RevertCommand revertCommand = git.revert();
// revert to revision 2
revertCommand.include(rev2);
RevCommit revCommit = revertCommand.call();
// print logs
Iterable<RevCommit> gitLog = git.log().call();
Iterator<RevCommit> it = gitLog.iterator();
while (it.hasNext()) {
RevCommit logMessage = it.next();
System.out.println(logMessage.getName() + " - " + logMessage.getFullMessage());
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
编辑:已更正代码。有点进步。现在打开文件时,内容为:
Line 1
<<<<<<< master
Line 2
Line 3
=======
>>>>>>> 54e7037 Commit Log 2
但是,我希望
Line 1
Line 2
答案 0 :(得分:0)
RevertCommand.include()的Javadoc声明包含对要还原的提交的引用,因此您实际上需要指定应还原的提交,即rev3,而不是要重置的提交
您实际尝试的是还原在commit rev2中所做的更改,在这种情况下,这导致与commit rev3中的更改发生合并冲突。调用后,可以通过getUnmergedPaths()/ getFailingResults()的revertComment看到它。
因此,以下代码应添加第4次提交,以还原rev3中的更改:
RevertCommand revertCommand = git.revert();
// revert to revision 2
revertCommand.include(rev3);
RevCommit revCommit = revertCommand.call();
System.out.println("Reverted: " + revCommit);
System.out.println("Reverted refs: " + revertCommand.getRevertedRefs());
System.out.println("Unmerged paths: " + revertCommand.getUnmergedPaths());
System.out.println("Failing results: " + revertCommand.getFailingResult());
// print logs
gitLog = git.log().call();
for (RevCommit logMessage : gitLog) {
System.out.println("After revert: " + logMessage.getName() + " - " + logMessage.getFullMessage());
}
System.out.println("File contents: " + FileUtils.readFileToString(newFile, "UTF-8"));