2

let's say I have the following history on a repo

branch 1 :    1---2---4---5
                   \ /
branch 2 :          3

Are there ways to change the 3rd commit without breaking the history of the repo? (and so the commit ID of the 3rd commit should remain the same)

Alberto Sinigaglia
  • 12,097
  • 2
  • 20
  • 48
  • No way whatsoever. – yeputons Nov 02 '20 at 20:16
  • Why? The whole point of the SHA (ID) is to be a unique identifier. – JBallin Nov 02 '20 at 20:21
  • Rewriting history is normal for Git and does not "break" the history. Unlike other version control systems, Git does not consider the history to be immutable. [The repository is not a museum](https://www.youtube.com/watch?v=yXyPvhISkRQ). If you expand on what it would break we might be able to offer solutions that work better with Git. – Schwern Nov 02 '20 at 21:12

1 Answers1

1

Yes, but only locally.

You can use git-replace to replace a commit but retain the ID. This can only be done locally. If you want to push it, you still need to rewrite the commit, and all following commits, with a new ID.


Why not?

Unchanging commit IDs are fundamental to how Git works.

A commit ID represents a checksum of its contents and its parents IDs. This means if you and I both have commits ABC123 we know not only that we have the same commits, but the same history. This helps make Git push and pull so fast, they only need to exchange commit IDs.


A simple way to avoid problems with other collaborators when altering history is to encourage git pull --rebase=merges. Instead of trying to merge their local changes with the remote, which will cause problems because their local history has diverged from the remote history, it will rewrite their local changes on top of the new remote.

Unlike other rebases, this is safe. It avoids "update merges" which are of no value and only serve to complicate the history.

You can make this the default by setting pull.rebase to merges. merges will try to preserve local merge commits.

Schwern
  • 153,029
  • 25
  • 195
  • 336