git 提交的代码行消失

git commited code lines disappear

在工作中,我们开始注意到一些奇怪的 git 行为,我无法解释。有人会提交,稍后(通常在合并之后),提交中的某些代码行将被撤消。这不是整个提交,可能只影响文件的一部分。它似乎也发生在正常的成功合并之后(即没有解决不当的冲突)。

有时这很明显,例如当文件的一部分发生更改时,有时它可能更微妙。它看起来并不刻意,受影响的人似乎也没有使用 rebase、commit amend、revert 等可以提供简单解释的东西。自然地,消失的代码总是在较新的提交中未修改的旧代码。

在无冲突合并期间,git 是否有任何其他方式可以覆盖先前提交的部分内容?

有时团队成员会在准备合并时squash他们的提交。在开发过程中,进行多次提交并拥有相当活跃的 git 历史记录可能会有所帮助。

当需要将你的分支合并到 master 时(当然你的 PR 已经被你的同事审查过 :wink:) 你可能会选择将你的提交压缩成一个,这将使历史更易于管理对于大型团队。

您可以通过检查 git 日志来做到这一点:

git log

然后选择要合并为一个的提交:

git rebase -i HEAD~4

根据文档,您的 EDITOR 将在每次提交时加载,并按照编辑器中的提示进行操作:

pick 01d1124 Adding license
pick 6340aaa Moving license into its own file
pick ebfd367 Jekyll has become self-aware.
pick 30e0ccb Changed the tagline in the binary, too.

# Rebase 60709da..30e0ccb onto 60709da
#
# Commands:
#  p, pick = use commit
#  e, edit = use commit, but stop for amending
#  s, squash = use commit, but meld into previous commit
#
# If you remove a line here THAT COMMIT WILL BE LOST.
# However, if you remove everything, the rebase will be aborted.
#

Some teams follow this particular workflow and prefer their teammates do this, there are arguments against this.