代码之家  ›  专栏  ›  技术社区  ›  Community wiki

Git:目前与私有远程回购存在合并/冲突。如何告诉Git只使用我的本地文件?

  •  13
  • Community wiki  · 技术社区  · 2 年前

    尝试在个人项目中使用/学习git。只有我和一个远程git repo,几次提交,我陷入了一次失败的合并。我的很多文件现在也有Git合并冲突标记。

    我该怎么告诉git把所有东西都扔掉,用我的?

    我是如何进入目前状态的一个具体例子:

    echo A new file > myFile.txt             # example file
    git add myFile.txt                       # add file
    git commit                               # commit changes
    git push                                 # push changes to remote repo
    echo A conflicting edit > myFile.txt     # oh, no, forgot some changes
    git add myFile.txt                       # add again
    git commit --amend                       # amend previous commit
    git push                                 # fails. Git suggests to do a pull first
    git pull origin HEAD                     # "Automatic merge failed" Now what?
                                             # Just use what I have locally!
    
    2 回复  |  直到 12 年前
        1
  •  17
  •   Kache    12 年前
    git checkout --ours . # checkout our local version of all files
    git add -u            # mark all conflicted files as merged/resolved
    git commit            # commit the merge
    

    有一种混乱的替代方案可以破坏使用相同远程源的其他所有人的回购。只有当你是唯一一个使用它的人时,才考虑它:

    git reset --hard HEAD # undo that failed merge
    git push --force      # replace everything remote with local
    

    解释 (现在我明白了 git 更好)
    之所以会发生这种情况,是因为修改提交更改了“历史”。在本地执行此操作是安全的,因为它不会影响其他任何人。然而,修改已经推动的承诺 影响其他回购,不安全。

        2
  •  6
  •   Jeff Bowman    12 年前

    您的GUI可能只是在设置 --strategy=ours ( git merge -s ours <branch> )。这将执行合并,引用两个提交作为父级,但保留整个目录状态。

    您的另一个选择是使用 git merge -s recursive -X ours <branch> ,它将尝试从两个分支引入文件,但在发生冲突时会更喜欢您的版本。

    Docs

    使用以下演示shell脚本,您可以看到两种不同的样式在工作:

    #!/bin/sh
    
    mkdir gittest
    cd gittest
    git init
    
    git checkout master
    echo "Line one" > bar
    git add bar
    git commit -m "Original commit"
    
    git checkout -b fork1
    echo "Line one and something" > bar
    echo "Line two" > bam
    git add bar bam
    git commit -m "Fork1 commit."
    
    git checkout master
    git checkout -b fork2
    echo "Line one and other stuff" > bar
    echo "Line three" > baz
    git add bar baz
    git commit -m "Fork2 commit."
    
    git checkout fork1
    if [ "$1" = "ours" ]; then
      # `ls gittest` => bam bar
      # `cat gittest/bar` => Line one and something
      git merge -s ours fork2
    else
      # `ls gittest` => bam bar baz
      # `cat gittest/bar` => Line one and something
      git merge -X ours fork2
    fi