在我的分支上,我在.gitignore中有一些文件

在另一个分支上,这些文件不是。

我想将不同的分支合并到我的分支中,我不关心这些文件是否不再被忽略。

不幸的是,我得到了这个:

以下未跟踪的工作树文件将被合并覆盖

我如何修改我的pull命令来覆盖这些文件,而不需要我自己找到、移动或删除这些文件?


当前回答

如果你考虑使用-f标志,你可以先运行它作为一个演练。你只需要提前知道你接下来会遇到什么样有趣的情况;-P

-n 
--dry-run 
    Don’t actually remove anything, just show what would be done.

其他回答

删除所有未跟踪的文件:

git clean  -d  -fx .

警告:这将删除IDE文件和任何有用的文件,只要你不跟踪这些文件。请谨慎使用此命令

如果你考虑使用-f标志,你可以先运行它作为一个演练。你只需要提前知道你接下来会遇到什么样有趣的情况;-P

-n 
--dry-run 
    Don’t actually remove anything, just show what would be done.

一种方法是存储本地更改并从远程回购中提取。这样,你就不会丢失你的本地文件,因为文件会去隐藏。

git add -A
git stash
git pull

你可以使用git stash list这个命令检查你的本地存储文件

安全地删除/覆盖麻烦的文件

当你想合并时:

git checkout -f donor-branch   # replace bothersome files with tracked versions
git checkout receiving-branch  # tracked bothersome files disappear
git merge donor-branch         # merge works

当你想拉的时候:

git fetch
git checkout -f origin/mybranch   # replace bothersome files with tracked versions
git checkout mybranch             # tracked bothersome files disappear
git pull origin/mybranch          # pull works

这就是你使用它所需要知道的。下面是一个解释。


详细解释

我们要删除的烦人文件:

存在于捐赠分支(对于git拉:上游分支), 在接收分支中不存在, 并且正在阻止合并,因为它们在你的工作目录中存在并且未被跟踪。

Git merge -f和Git pull -f不存在,但是Git checkout -f存在。

我们将使用git checkout -f + git checkout来跟踪+删除麻烦的文件,然后您的合并可以正常进行。

步骤1。这一步强制将未跟踪的Bothersome Files替换为跟踪的捐赠分支版本(它还检出捐赠分支,并更新工作目录的其余部分)。

git checkout -f donor-branch

步骤2。这一步删除了麻烦文件,因为它们在我们当前(捐赠)分支中被跟踪,而在我们切换到的接收分支中不存在。

git checkout receiving-branch

步骤3。现在Bothersome Files不存在了,在捐赠分支中合并将不会覆盖任何未跟踪的文件,因此我们不会得到错误。

git merge donor-branch

更新-一个更好的版本

此工具(https://github.com/mklepaczewski/git-clean-before-merge)将:

删除未跟踪的文件,这些文件与它们的git拉等价物相同, 将更改还原到修改后的文件,这些文件的修改版本与它们的git拉等价物相同, 报告修改/未跟踪的文件,与他们的git拉版本不同, 该工具有——pretend选项,不会修改任何文件。

旧版本

这个答案与其他答案有何不同?

这里给出的方法只删除将被merge覆盖的文件。如果目录中有其他未跟踪(可能被忽略)的文件,此方法将不会删除它们。

解决方案

这段代码将提取所有将被git删除并覆盖的未跟踪文件。

git pull 2>&1|grep -E '^\s'|cut -f2-|xargs -I {} rm -rf "{}"

然后就这样做:

git pull

这不是git瓷器命令,所以总是仔细检查它会做什么:

git pull 2>&1|grep -E '^\s'|cut -f2-|xargs -I {} echo "{}"

解释——因为有一句台词很吓人:

以下是它的功能:

git pull 2>&1 - capture git pull output and redirect it all to stdout so we can easily capture it with grep. grep -E '^\s - the intent is to capture the list of the untracked files that would be overwritten by git pull. The filenames have a bunch of whitespace characters in front of them so we utilize it to get them. cut -f2- - remove whitespace from the beginning of each line captured in 2. xargs -I {} rm -rf "{}" - us xargs to iterate over all files, save their name in "{}" and call rm for each of them. We use -rf to force delete and remove untracked directories.

如果用瓷器命令代替第1-3步就太好了,但我不知道有什么等价的。