推送到远程时如何避免来自 Git pull 的合并提交

How to avoid merge commits from Git pull when pushing to remote

我有一个存储库和一些本地更改要提交。 在提交之前,我在 Eclipse 中使用 Egit 将更改拉到本地。

它创建了一个合并提交,我在上面提交了我的提交。

现在,当我尝试推送到原点时,它显示它将推送我的提交以及合并提交。 但理想情况下,合并提交不应该是远程存储库的一部分。

如何避免这种情况?

通常的策略是在一个分支上工作。当远程 master 发生变化时,将更改拉到 master 而不是合并,rebase 分支。

请参阅 Atlassian Git Rebase

无论何时从远程存储库中拉取,都使用变基选项。请按照以下步骤操作,

  1. 提交您的更改 - 它将在您的本地创建一个新的提交。
  2. 现在git pull --rebase <remote-name> <branch-name>.
  3. 基本上,rebase 会取出您在当前分支 HEAD 上作为补丁提交的提交。然后它将在 HEAD 之上应用所有远程提交,然后在其之上应用您的提交。
  4. 所以最佳做法是提交更改,然后使用变基选项拉取远程提交。

当您有未提交的更改时,您可以这样做,

git stash
git pull --rebase <remote> <branch>
git stash apply

你可以运行

git config --global branch.autosetuprebase always

使 git pull --rebase 成为 git 拉取的默认行为。

场景:

假设 a 是在 GIT 回购中提出的 PR:从 feature/my_bug_fixrelease/project-007。 但是 GIT 不允许合并,因为 以上分支之间存在冲突

然后这样做:

$ git checkout feature/my_bug_fix

$ git pull --rebase origin release/project-007

$ # resolve any conflicts encountered during the process

$ git rebase --continue

$ git push origin feature/my_bug_fix  --force

这是解决冲突分支的有效且干净的方法。此外,通过使用 --rebase 将不会获得合并提交 如果你使用 git merge.

此外:

pull          = fetch + merge

pull --rebase = fetch + rebase

所以,选择处理分支的方式。

你现在应该更好地理解 merge 和 rebase 之间的区别:)

如果您不想合并提交,将本地分支同步到远程分支的最佳方法是执行变基。建议您先执行 git fetch,然后执行 git rebase,但是,正如其他人提到的,您可以同时执行两项操作:

git pull --rebase --autostash

如果您总是这样做,您可以将 git pull 配置为自动执行此操作:

git config --global pull.rebase true
git config --global rebase.autostash true