Reputation: 79685
Is there a way to add a new commit to HEAD which has the same tree hash as an existing commit? Basically what Rollback to an old Git commit in a public repo is asking, but using git commit-tree
instead of git revert
or git reset --hard
?
Upvotes: 1
Views: 435
Reputation: 79685
OK, after some trying I came up with this script:
#/bin/bash
COMMITID=$1
git reset --hard $(git commit-tree -m "Revert to commit $COMMITID" -p $(git rev-parse HEAD) $(git rev-parse $COMMITID^{tree}))
This will get the tree hash from the commit we want to revert to, then create a new commit message specifying current HEAD as the parent commit, and then reset our branch to that new commit.
This would delete any unstaged or uncommitted changes so maybe we could use git reset --soft
instead.
Edit: Also many thanks to @RomainValeri, who provided a global alias for the command:
git config --global alias.reset-by-commit-tree '!f() { git reset --hard $(git commit-tree -m "Revert to commit $1" -p $(git rev-parse HEAD) $(git rev-parse $1^{tree})); }; f'
After running it, you can use git reset-by-commit-tree <sha>
to revert to a particular commit.
Upvotes: 1
Reputation: 30307
You could use git reset --soft
git checkout --detach revision-with-the-desired-tree
git reset --soft the-branch
# if you like the result
git branch -f the-branch
git checkout the-branch
Upvotes: 1