I need to run the command
git reset --hard origin <branch-name>
via JGit to reset corrupt local commits done by users, and I'm using following code:
git.reset().setRef(<branch-name>).setMode(ResetCommand.ResetType.HARD).call()
but it doesn't overwrites local commits and pointing to current remote HEAD.
I have tried with git.fetch()
and git.pull()
previous to git.reset()
but it doesn't work, is there another method I need to use?
Also, how to print result why it's failing, I see that .call()
returns Ref
but the Ref
object doesn't have messages, only ObjectId
.
Note, that git reset --hard origin <branch-name>
is not a valid Git command. To reset the current HEAD to a remote branch, you need to specify the branch as origin/<branch-name>
. This is a short form of refs/remotes/origin/<branch-name>
. Is it this what you mean?
If you are specifying refs/heads/<branch-name>
, then you are referring to a local branch. See also What are the differences between local branch, local tracking branch, remote branch and remote tracking branch?
The equivalent JGit command is
git.reset()
.setRef("refs/remotes/origin/<branch-name>")
.setMode(ResetType.HARD)
.call()
Call fetch
or pull
only if you want to include updates that took place in the remote repository. Note, that pull
is just a composite command of fetch
, followed by rebase
or merge
(depending on the configuration). It tries to rebase or merge the remote branch into the local branch (i.e. refs/remotes/origin/<branch-name>
into refs/heads/<branch-name>
) and will fail with a dirty working directory. This is likely not what you want.