Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to do git rebase with keeping the existing commit hashes?

Tags:

git

rebase

Imagine a scenario where a project has an existing git tree you're 100% satisfied with. Now you discover some ancient source code predating migration to git and would like to make it a part of git history.

There are many ways how to achieve this but to my knowledge it always ends up with a new git tree, i.e. where all the existing commits have different IDs.

In this specific case it doesn't seem to be necessary, I'm not changing anything but the first commit's parent. Is there a way to do this?

like image 943
Miro Kropacek Avatar asked Aug 20 '17 11:08

Miro Kropacek


People also ask

How do you rebase without going through each commit?

If you don't want rebase to stop at each commit if you get any merge conflicts and want it to stop only once during the rebase process, you can squash all the commits into one in your fix/align-div-vertically branch by squashing them using interactive rebase before rebasing with the master.

Does rebase change hash?

A Rebase Changes Hashes, a Merge Does Not.

Why does rebase change commit hash?

this is because when you rebase the node in HEAD that's 20 commits prior to the current one interactively, you are starting at the node in HEAD 20 commits ago and reapplying the subsequent 20 commits as if they're new, with the option to make changes.

Do I need to commit again after rebase?

The purpose of rebase is make your commits look as if they were changes to the branch you rebase onto. So the most logical way is to incorporate merge conflicts into these commits. No additional commits is required thus.


1 Answers

No, this is fundamentally impossible. A commit’s id is the hash of its combined content. That includes not only the whole tree and file content, but also the commit message, author information, and the reference to its parent.

So by changing the parent of a commit, you are changing its content and as such invalidate its previous id. Git will have to recalculate its hash in order to integrate the commit into the history. Otherwise it would reject that commit as being broken and leave your repository in a broken state.

The fact that any commit id matches the hash of its content, and that this is true for any direct or indirect parent is a core part of Git’s integrity. You cannot avoid this.

So no, you cannot do what you want without affecting commit hashes. What you maybe could do is simply add another completely unrelated branch that has no connection to your current branches. That way you wouldn’t affect your existing commits but you would also have a way to integrate that old history into the repository so it would be stored inside—not integrated but at least it’s there.

like image 187
poke Avatar answered Oct 13 '22 00:10

poke