How do you fix a bad merge, and replay your good commits onto a fixed merge?

后端 未结 12 907
时光取名叫无心
时光取名叫无心 2020-11-21 10:25

I accidentally committed an unwanted file (filename.orig while resolving a merge) to my repository several commits ago, without me noticing it until now. I want

12条回答
  •  情书的邮戳
    2020-11-21 10:36

    The simplest way I found was suggested by leontalbot (as a comment), which is a post published by Anoopjohn. I think its worth its own space as an answer:

    (I converted it to a bash script)

    #!/bin/bash
    if [[ $1 == "" ]]; then
        echo "Usage: $0 FILE_OR_DIR [remote]";
        echo "FILE_OR_DIR: the file or directory you want to remove from history"
        echo "if 'remote' argument is set, it will also push to remote repository."
        exit;
    fi
    FOLDERNAME_OR_FILENAME=$1;
    
    #The important part starts here: ------------------------
    
    git filter-branch -f --index-filter "git rm -rf --cached --ignore-unmatch $FOLDERNAME_OR_FILENAME" -- --all
    rm -rf .git/refs/original/
    git reflog expire --expire=now --all
    git gc --prune=now
    git gc --aggressive --prune=now
    
    if [[ $2 == "remote" ]]; then
        git push --all --force
    fi
    echo "Done."
    

    All credits goes to Annopjohn, and to leontalbot for pointing it out.

    NOTE

    Be aware that the script doesn't include validations, so be sure you don't make mistakes and that you have a backup in case something goes wrong. It worked for me, but it may not work in your situation. USE IT WITH CAUTION (follow the link if you want to know what is going on).

提交回复
热议问题