通过 JGit 将分支重置为 HEAD

Reset branch to HEAD via JGit

我需要运行命令 git reset --hard origin <branch-name> 通过 JGit 重置用户所做的损坏的本地提交,我正在使用以下代码:

git.reset().setRef(<branch-name>).setMode(ResetCommand.ResetType.HARD).call()

但它不会覆盖本地提交并指向当前的远程 HEAD。 我已经尝试在 git.reset() 之前使用 git.fetch()git.pull() 但它不起作用,我需要使用另一种方法吗?

此外,如何打印失败的结果,我看到 .call() returns Ref 但是 Ref 对象没有消息,只有 ObjectId.

请注意,git reset --hard origin <branch-name> 不是有效的 Git 命令。要将当前 HEAD 重置为 远程分支 ,您需要将分支指定为 origin/<branch-name>。这是 refs/remotes/origin/<branch-name> 的缩写形式。是这个意思吗?

如果您指定 refs/heads/<branch-name>,那么您指的是 本地分支 。另见 What are the differences between local branch, local tracking branch, remote branch and remote tracking branch?

等价的JGit命令是

git.reset()
    .setRef("refs/remotes/origin/<branch-name>")
    .setMode(ResetType.HARD)
    .call()

仅当您想要包含在远程存储库中发生的更新时才调用 fetchpull。请注意,pull 只是 fetch 的复合命令,后跟 rebasemerge(取决于配置)。它尝试将远程分支变基或合并到本地分支(即 refs/remotes/origin/<branch-name>refs/heads/<branch-name>),并且会因工作目录变脏而失败。这可能不是您想要的。