gitgit-branch

How can I rewrite the commit history?


After creating branch Y from working branch X, I deleted some files to reduce visual noise by not seeing those files around on the file system, while working on branch Y. These files are being changed in branch X.

Here is the scenario:

A - B [origin/master]
     \
      C - D - G - H [origin/X]
           \
            E - F [Y]

Changes from branch Y are also pushed to origin/Y.

I already raised a pull request (PR) on branch Y for review.


How can I rewrite the commit history in origin/Y to get a file back?


Solution

  • I will give you a simple recipe as a fallback, just in case. Suppose your branch is called A, and you deleted files on A~3 (that would be, 3 revisions behind A):

    git checkout A~3 # We set ourselves on the revision where the files where deleted
    git checkout HEAD~1 -- file1 file2 file3 # Get back the files from the previous revision
    git commit --amend --no-edit # Commit the new revision with the deleted files back in place
    git cherry-pick A~3..A # Replay revisions after this new revision
    # If you like the results:
    git branch -f A # Set the branch on this new position
    git checkout A
    git push -f origin A
    

    That should work.