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
?
Asked
Active
Viewed 336 times
1

sashoalm
- 75,001
- 122
- 434
- 781
-
Why? What's the point? – phd Dec 19 '19 at 16:20
-
There is a reason, but what is the point to ask why I need it? Maybe it's just curiosity. Suffice it to say that I'm interested in a solution to this. – sashoalm Dec 19 '19 at 16:22
-
1@sashoalm I guess phd asks because it's the best way to spot an XY problem. Which are extremely frequent on SO. – Romain Valeri Dec 19 '19 at 16:45
-
@RomainValeri I understand that, I was responding more to the tone of his question which was definitely not politely phrased. Anyway I can't give more details without disclosing details about our deployment pipeline which I'd rather not do. I apologize for that. – sashoalm Dec 20 '19 at 10:20
2 Answers
1
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.

sashoalm
- 75,001
- 122
- 434
- 781
-
1I love it, thanks a lot. If anyone needs the corresponding alias : `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'` – Romain Valeri Dec 19 '19 at 16:53
-
Thank you, I didn't know you could do that. Can I add this to my answer? – sashoalm Dec 20 '19 at 10:24
-
Of course, be my guest, you came up with the real work here, I only put it in alias form. Go ahead. – Romain Valeri Dec 20 '19 at 10:35
1
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

eftshift0
- 26,375
- 3
- 36
- 60