Git undo auto merging on a specific file only, not the whole branch

后端 未结 3 1180
醉梦人生
醉梦人生 2021-02-18 18:04

Is there a way I can undo a auto-merge of one file that has been changed instead of the whole branch in Git?

I want to undo this merge:

Auto-mergi

相关标签:
3条回答
  • 2021-02-18 18:31

    You probably want git checkout commit-ish -- file.

    0 讨论(0)
  • 2021-02-18 18:38

    You cannot reset a single file, because reset only works on whole commits (it basically "forgets" newer commits). Also, you cannot "change" an existing commit - more on that below.

    In your case, you have several options:

    The safest method would be to just checkout the old version of your file, and check-in again

    $ git checkout HEAD~1 -- public/stylesheet/application.css
    # Back at old version, change already staged
    $ git commit -m "Reverted change to public/stylesheet/application.css"
    

    This will simply create a new commit that turns back your accidental changes, and should be your preferred option unless you know exactly what you are doing.

    Second, reset the repository as above, and re-check in the commit:

    $ git reset HEAD~1
    # Now restore your file public/stylesheets/application.css
    $ git commit -m "Re-checkin of the commit"
    # You may use the old checkin message here
    

    This will effectively "change" the existing commit in the way that you will have the same commit in your history, with the same description, minus the modifications to the one file. However, this changes you history, so you must not use this if have already pushed the original commit to any upstream repository.

    Git does not allow you to change existing commits in any other way than by throwing away the existing ones and creating new ones. This will always "break" your history and should be only used if you exactly know what this feature does and why you want to do it.

    0 讨论(0)
  • 2021-02-18 18:43

    When you do:

    git reset HEAD~1 public/stylesheet/application.css
    

    ... that changes the version of your file in the index (i.e. the staged version) to the version in HEAD~1 - your working copy remains the same. The current documentation explains this as:

    This form resets the index entries for all <paths> to their state at <commit%gt;. (It does not affect the working tree, nor the current branch.)

    If you do:

    git checkout HEAD~1 -- public/stylesheet/application.css
    

    ... that will change both the working copy and the staged version to the version from HEAD~1. The -- is there for safety, just in case you have file name that can also be understood as a commit.

    Now that you're got that change staged, you could amend the merge commit with:

    git commit --amend
    

    ... which is fair enough as long has you haven't pushed the merge anywhere, since the merge will still just have changes from one branch or the other.

    0 讨论(0)
提交回复
热议问题