【问题标题】:Prevent merging a file from master with Git防止将来自 master 的文件与 Git 合并
【发布时间】:2023-03-16 08:59:01
【问题描述】:

another question 中建议使用.gitattributes 以保持文件被跟踪但不合并到不同的分支,但我下面的用例似乎不起作用..

mkdir git
cd git
git init
echo "B" > b.txt
git add b.txt 
git commit -m 'Initial commit'

echo "b.txt merge=keepMine" > .gitattributes
git add .gitattributes 
git config merge.keepMine.name "always keep mine during merge"
git config merge.keepMine.driver "keepMine.sh %O %A %B"
git commit -m 'Ignore b.txt'

git checkout -b test # Create a branch
git checkout master # Back to master and make change
echo "Only in master" > b.txt
git commit -a -m 'In master'

git checkout test
git merge master # The change in b.txt is being merged...

有什么想法吗?谢谢..

【问题讨论】:

  • 这看起来像是一种奇怪的愿望,即合并除一个文件之外的所有内容。当所有内容作为一个整体维护时,这违反了 git 意识形态。你能解释一下用例吗?为什么需要它?

标签: git merge branch git-branch branching-and-merging


【解决方案1】:

我怀疑它不起作用,因为没有合并冲突。

但是,我可以确认 git merge master --strategy=ours 可以正常工作。

这可能就是您要查找的内容:How to tell Git to always select my local version

如果您想为特定文件指定特定的合并策略,您真正需要做的是编写自定义合并驱动程序并在您的存储库配置中指定您希望将该合并驱动程序用作默认值。有关如何使用它,请参阅上面的链接。

简而言之,它在您的用例中不起作用的原因是因为您的用例不是合并。它只描绘了 master 上的一堆更改,其中创建了一个名为 test 的临时分支,然后稍后再向上移动到 master。 当你在测试分支上时,你永远不会真正引入提交

【讨论】:

  • git merge master --strategy=ours work 预期,但有时我们只需要将此策略应用于特定文件,而不是整个树。好像是个bug?
  • 不,这不是错误。在您的问题中,合并太容易了,这就是 Git 不尝试替代合并策略的原因。这是一个简单的实验——在每个分支上对同一行引入不同的更改,然后尝试合并。这会产生冲突,然后 git 会使用属性文件来选择你的。
  • 所以是否可以停止自动合并(仅限每个文件,而不是全局)
  • 您需要使用自定义合并驱动程序。
  • 我认为您正在寻找的方法是:引入冲突。这将迫使 git 退回到 .gitattributes 文件。然后它将使用您的版本。每次发生冲突时,此行为都会继续,从而确保您的版本是 master 中的版本。
【解决方案2】:

carleeto提到的自定义合并驱动在“Tell git not to merge binary files but to choose”中说明:

您可以在.gitattributes 文件中声明您想要的合并类型:

echo yourConfigFile merge=keepMine > parentDirectory\.gitattributes

【讨论】:

  • 我已经更新了上面的命令日志,但仍然无法正常工作。至少 git 应该提示我缺少 keepMine.sh 但似乎它只是被忽略了..
  • @Yoga:对,在你没有冲突的情况下它不起作用(仅来自master 分支的新修改)
  • 是的,所以似乎唯一的方法是使用git merge master --strategy=ours
猜你喜欢
  • 2016-07-25
  • 2021-12-05
  • 2012-08-07
  • 1970-01-01
  • 1970-01-01
  • 2011-07-11
  • 1970-01-01
  • 2014-08-04
  • 2014-01-28
相关资源
最近更新 更多