gitgit-commit

How to change past commit to include a missed file after other commits have been made?


I have committed a change and forgot to add a file to the change set. After other commits, I realized the file is now missing from a HEAD^4 commit.

Because this is beyond the immediately previous commit, I cannot use the --amend solution.

How do I rewrite a previous commit to include the missing file if it's beyond the immediately previous commit?


Solution

  • Use git rebase --interactive HEAD~4 and set edit option for the commit you'd like to amend.

    Remember that you should not modify commits pushed to the remote repository this way. It's better to add a new commit with missing file in that case.


    To make this more clear, first stash any current changes with git stash. Then, git rebase --interactive HEAD~4. You get the following in a text editor (note that you'll get 5 commits, in descending order):

    pick 123e123 fifth last commit message
    pick 321e122 fourth last commit message
    pick 1d23e3f third last commit message
    pick 987a987 second last commit message
    pick 8a8a8a8 last commit message
    

    Modify the change entry's prefix from pick to edit. That'd be edit 321e122 ... for the OP.

    git rebase goes through the entries, in order. As there's only one we're changing, you'll only have one entry to change. Now, add your files with git add, and git commit --amend to amend the current commit with those added files.

    Finally, git rebase --continue moves onto the next file. As there's only one, the rebase is complete